原文地址:http://siligence.ai/article-465-1.html
上一期我们简单的介绍了,DNN和CNN的tensoflow接口,现在我们来讲一下RNN的接口,由于梯度消失的问题,目前人们经常使用LSTM和GRU代替最原始的RNN。我现在一一举例子:
关于单向lstm:
lstmCell = tf.contrib.rnn.BasicLSTMCell(lstmUnits)
lstmCell = tf.contrib.rnn.DropoutWrapper(cell=lstmCell,output_keep_prob=0.75)
value,_ = tf.nn.dynamic_rnn(lstmCell,data,dtype=tf.float32)
weight = tf.Variable(tf.truncated_normal([lstmUnits,numClasses]))
bias = tf.Variable(tf.constant(0.1,shape=[numClasses]))
value = tf.transpose(value,[1,0,2])
last = tf.gather(value,int(value.get_shape()[0])-1)
with tf.name_scope(‘prediction’):
prediction = (tf.matmul(last,weight) + bias)
这里可以看到一个新概念,Drop_out,Drop_out是在你定义的张量中随机去除一部分值,output_keep_prob表示输出时保留多少百分比的元素,in_keep_prob表示输入时保留多少百分比的元素,这么做的好处在模型训练的时候,减少模型输入的特征增加了模型的鲁棒性能(就像蒙住了一部分的图片让你猜图片的内容),减少了过拟合的可能性。
我们运用tf.contrib.rnn.BasicLSTMCell(lstmUnits)来定义LSTM细胞,之后放入tf.nn.dynamic_rnn()里,强调这里的原因时因为双向LSTM定义方法和这个差不多,只是多了一个步骤,先给大家打个预防针。之后输出结果,运用DNN调整为合适的维度,然后进行我们模型的预测。
关于双向LSTM:
stmCell_fw = tf.contrib.rnn.BasicLSTMCell(lstmUnits)
lstmCell_fw = tf.contrib.rnn.DropoutWrapper(cell=lstmCell_fw,output_keep_prob=0.75)
lstm