个人笔记 感谢指正
LSTM_tensorflow
1.导入包
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
2.导入mnist手写数据集
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
3.设置相应的参数
n_inputs = 28 #单个LSTM神经元接受的向量维度
max_time = 28 #一次输入的时间跨度
lstm_size = 100 #隐藏层数
n_classes = 10 #输出种类数
batch_size = 50 #批次的大小
n_batch = mnist.train.num_examples // batch_size #计算批次数
4.定义占位变量
#None表示这一个维度值可以为任意值
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
5.初始化权重与偏置
#初始化权重
weights = tf.Variable(tf.truncated_normal([lstm_size,n_classes],stddev=0.1))
#初始化偏置
biases = tf.Variable(tf.constant(0.1,shape=[n_classes]))
#注意:单个LSTM神经元输出的都是标量,只有多个LSTM神经元组成的LSTMCell输出的才是标量,而且这里的weights是LSTMCell与最后全连接层之间的参数,LSTMCell中的参数不需要我们去设置
6.定义RNN网络(包括最后的全连接层)
def RNN(X,weights,biases):
inputs = tf.reshape(X,[-1,max_time,n_inputs])
lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_size)
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32)
results = tf.nn.softmax(tf.matmul(final_state[1],weights) + biases)
return results
#tf.contrib.rnn.BasicLSTMCell(hidden_units)函数:其实就是定义一个LSTM神经元组成的一层,但是我们只需要传入该层的units的大小,至于该层的权重与偏置并不需要我们去设置
#tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32): Creates a recurrent neural network specified by RNNCell cell
7.代价函数与优化器设置
prediction = RNN(x,weights,biases)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
init = tf.global_variables_initializer() #return An Op that initializes global variables in the graph.
8.会话编写
with tf.Session() as sess:
sess.run(init)
for epoch in range(6):
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print('Iter' + str(epoch) + ',Testing Accuracy' + str(acc))
9.LSTM原理分析
参考来源:https://blog.csdn.net/mch2869253130/article/details/89150043
注意:下述公式中的乘法都是元素乘法不是矩阵乘法
1.忘记门
第一步是决定从细胞状态里扔掉什么信息(也就是保留多少信息)。将上一步细胞状态中的信息选择性的遗忘 。
实现方式:通过sigmoid层实现的“忘记门”。以上一步的 h t − 1 h_{t-1} ht−1和本次的输 入 x t 入x_{t} 入xt,然后为 C t − 1 C_{t-1} Ct−1的每一个数字输出一个0-1的值,记为 f t f_{t} ft
2.输入层门
第二步是决定在细胞状态里存什么。将新的信息选择性的记录到细胞状态中。
实现方式:
sigmoid层(输入门层)决定我们要更新什么值,这个概率表示为 i t i_{t} it
tanh层创建一个候选值向量 C ~ \widetilde{C} C
将会被增加到细胞状态中。 我们将会在下一步把这两个结合起来更新细胞状态。
3.更新细胞状态(细胞状态)
更新旧的细胞状态实现方式: f t f_{t} ft表示忘记上一次信息 C t − 1 C_{t-1} Ct