您的位置:首页 > 其它

Tensorflow实现基于Bidirectional LSTM Classifier

2018-01-16 14:38 435 查看
数据集是在mnist上进行测试。先载入 Tensorflow、Numpy,以及Tensorflow自带的MNIST数据读取器。我们直接使用input_data.read_data_sets下载并读取mnist数据集。

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('/tmp/data',one_hot=True)
然后设为训练参数,我们设置学习速率为0.01(因为优化器将选择Adam,所以学习速率较低),最大训练样本数为40万,batch_size为128,同时设置每间隔10次训练就展示一次训练情况。

learning_rate=0.01
max_samples=400000
batch_size=128
display_step=10
因为mnist的图像尺寸为28x28,因此输入n_input为28(图像的宽),同时n_steps即LSTM的展开部署(unrolled steps of LSTM),也设置为28(图像的宽),这样图像的全部信息就都是用上了。这里是一次读取一行像素(28个像素点),然后下一个时间点再传入下一行像素点。这里n_hidden(LSTM的隐藏节点数)设为256,而n_classes(MNIST数据集的分类数目)则设为10。

n_input=28
n_steps=28
n_hidden=256
n_classes=10


我们创建输入x和学习目标y的place_holder。和使用卷积神经网络做分类时类似,这里输入x中每一个样本可直接使用二维的结构,而不必像MLP那样需要转为一维结构。和卷积网络中空间的二维不同,我们的样本被理解为一个时间序列,第一个维度是时间点n_steps,第二个维度是每个时间点的数据n_input。同时,我们设创建最后的SOFTMAX层的weights和biases,这里直接使用tf.random_normal初始化这些参数。因为是双向LSTM,有forward和backward两个LSTM的cell,所以weights的参数量也翻倍,变为2*n_hidden

x=tf.placeholder('float',[None,n_steps,n_input])
y=tf.placeholder('float',[None,n_classes])

weights=tf.Variable(tf.random_normal([2*n_hidden,n_classes]))
biases=tf.Variable(tf.random_normal([n_classes]))
下面电仪Bidirectional LSTM网络的生成函数。我们先对数据进行一些处理,把形状为(batch_size,n_steps,n_input)的输入编程长度为n_steps的列表,而其中元素形状为(batch_size,n_input)。然后输入进行转置,使用tf.transpose(x,[1,0,2])将第一个维度batch_size和第二个维度n_steps进行交换。接着使用tf.reshape将输入x变为(n_steps*batch_size,n_input)的形状,再使用tf.split将x拆为长度为n_steps的列表,列表中每个tensor的尺寸都是(batch_size,n_input),这样符合LSTM单元的输入格式。下面使用tf.contrib.rnn.BasicLSTMCell分别创建forward和backward的LSTM单元,它们的隐藏节点数都设为n_hidden,而forget_bias都设为1.然后直接将正向的lstm_fw_cell和反向的lstm_bw_cell传入Bi-RNN界都tf.nn.bidirectional_rnn中,生成双向LSTM,并传入x作为输入。最后对双向LSTM的输出结果outputs做一个矩阵乘法并加上偏置,这里的参数即为前面定义的weights和biases。

def BiRNN(x,weights,biases):
x=tf.transpose(x,[1,0,2])
x=tf.reshape(x,[-1,n_input])
x=tf.split(x,n_steps)

lstm_fw_cell=tf.contrib.rnn.BasicLSTMCell(n_hidden,forget_bias=1.0)
lstm_bw_cell=tf.contrib.rnn.BasicLSTMCell(n_hidden,forget_bias=1.0)

outputs,_,_=tf.contrib.rnn.static_bidirectional_rnn(lstm_fw_cell,lstm_bw_cell,x,dtype=tf.float32)
return tf.matmul(outputs[-1],weights)+biases
~
我们使用定义好的函数生成我们的Bidirectional LSTM网络,对最后输出的结果使用tf.nn.softmax_cross_entropy_with_logits进行Softmax处理并计算损失,然后使用tf.reduce_mean计算平均cost。我们定义优化器为Adam,学习速率即为前面定义的learning_rate。再使用tf.argmax得到模型预测的类别,然后用tf.equal判断是否预测准确。最后用tf.reduce_mean求得平均准确率。
pred=BiRNN(x,weights,biases)

cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))

optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

corrected_pred=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32))

init=tf.global_variables_initializer()


下面开始执行训练和测试操作。第一步是执行初始化参数,然后定义一个训练的循环,保持总训练样本数(迭代次数*batch_size)小于之前设定的值。在每一轮训练迭代中,我们使用mnist.train.next_batch拿到一个batch的数据并使用reshape改变其形状。接着,将包含输入x和训练目标y的feed_dict传入,执行一次训练操作并更新模型参数。每当迭代数为display_step的整数倍时,我们计算一次当前batch数据的预测准确率和loss并展示出来。

with tf.Session() as sess:
sess.run(init)
step=1
while step*batch_size < max_samples:
batch_x,batch_y=mnist.train.next_batch(batch_size)
batch_x=batch_x.reshape((batch_size,n_steps,n_input))
sess.run(optimizer,feed_dict={x:batch_x,y:batch_y})
if step % display_step==0:
acc=sess.run(accuracy,feed_dict={x:batch_x,y:batch_y})
loss=sess.run(cost,feed_dict={x:batch_x,y:batch_y})
print 'Iter '+str(step*batch_size)+ ',Minibatch Loss='+'{:.6f}'.format(loss)+',Training Accuracy= '+ '{:.5f}'.format(acc)
step+=1
print 'Optimizatin Finished!'

全部训练迭代结束后,我们使用训练好的模型,对mnist.test.images中全部的测试数据进行预测,并将准确率展示出来。

test_len=10000
test_data=mnist.test.images[:test_len].reshape((-1,n_steps,n_input))
test_label=mnist.test.labels[:test_len]
print 'Testing Accuracy:',sess.run(accuracy,feed_dict={x;test_data,y:test_label})
~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: