神经网络学习小记录3——利用tensorflow构建长短时记忆网络(LSTM)

╰半夏微凉° 2021-11-02 08:50 567阅读 0赞

神经网络学习小记录3——利用tensorflow构建长短时记忆网络(LSTM)

  • 学习前言
    • LSTM简介
      • 1、RNN的梯度消失问题
      • 2、LSTM的结构
      • 3、LSTM独特的门结构
    • tensorflow中LSTM的相关函数
      • tf.contrib.rnn.BasicLSTMCell
      • tf.nn.dynamic_rnn
    • 全部代码

学习前言

又出去和女朋友快乐的玩耍了,但是不要忘了学习噢。
在这里插入图片描述

LSTM简介

1、RNN的梯度消失问题

在过去的时间里我们学习了RNN循环神经网络,其结构示意图是这样的:
在这里插入图片描述
其存在的最大问题是,当w1、w2、w3这些值小于0时,如果一句话够长,那么其在神经网络进行反向传播与前向传播时,存在梯度消失的问题。
0.925=0.07,如果一句话有20到30个字,那么第一个字的隐含层输出传递到最后,将会变为原来的0.07倍,相比于最后一个字的影响,大大降低。
其具体情况是这样的:
在这里插入图片描述
长短时记忆网络就是为了解决梯度消失的问题出现的。

2、LSTM的结构

原始RNN的隐藏层只有一个状态h,从头传递到尾,它对于短期的输入非常敏感。
如果我们再增加一个状态c,让它来保存长期的状态,问题就可以解决了。
对于RNN和LSTM而言,其两个step单元的对比如下。
在这里插入图片描述
我们把LSTM的结构按照时间维度展开:
在这里插入图片描述
我们可以看出,在n时刻,LSTM的输入有三个:
1、当前时刻网络的输入值;
2、上一时刻LSTM的输出值;
3、上一时刻的单元状态。

LSTM的输出有两个:
1、当前时刻LSTM输出值;
2、当前时刻的单元状态。

3、LSTM独特的门结构

LSTM用两个门来控制单元状态cn的内容:
1、遗忘门(forget gate),它决定了上一时刻的单元状态cn-1有多少保留到当前时刻;
2、输入门(input gate),它决定了当前时刻网络的输入c’n有多少保存到单元状态。

LSTM用一个门来控制当前输出值hn的内容:
输出门(output gate),它决定了当前时刻单元状态cn有多少输出。
在这里插入图片描述

tensorflow中LSTM的相关函数

tf.contrib.rnn.BasicLSTMCell

  1. tf.contrib.rnn.BasicLSTMCell(
  2. num_units,
  3. forget_bias=1.0,
  4. state_is_tuple=True,
  5. activation=None,
  6. reuse=None,
  7. name=None,
  8. dtype=None
  9. )
  • num_units:RNN单元中的神经元数量,即输出神经元数量。
  • forget_bias:偏置增加了忘记门。从CudnnLSTM训练的检查点(checkpoin)恢复时,必须手动设置为0.0。
  • state_is_tuple:如果为True,则接受和返回的状态是c_state和m_state的2-tuple;如果为False,则他们沿着列轴连接。False即将弃用。
  • activation:激活函数。
  • reuse:描述是否在现有范围中重用变量。如果不为True,并且现有范围已经具有给定变量,则会引发错误。
  • name:层的名称。
  • dtype:该层的数据类型。

在使用时,可以定义为:

  1. lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)

在定义完成后,可以进行状态初始化:

  1. self.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)

tf.nn.dynamic_rnn

  1. tf.nn.dynamic_rnn(
  2. cell,
  3. inputs,
  4. sequence_length=None,
  5. initial_state=None,
  6. dtype=None,
  7. parallel_iterations=None,
  8. swap_memory=False,
  9. time_major=False,
  10. scope=None
  11. )
  • cell:上文所定义的lstm_cell。
  • inputs:RNN输入。如果time_major==false(默认),则必须是如下shape的tensor:[batch_size,max_time,…]或此类元素的嵌套元组。如果time_major==true,则必须是如下形状的tensor:[max_time,batch_size,…]或此类元素的嵌套元组。
  • sequence_length:Int32/Int64矢量大小。用于在超过批处理元素的序列长度时复制通过状态和零输出。因此,它更多的是为了性能而不是正确性。
  • initial_state:上文所定义的_init_state。
  • dtype:数据类型。
  • parallel_iterations:并行运行的迭代次数。那些不具有任何时间依赖性并且可以并行运行的操作将是。这个参数用时间来交换空间。值>>1使用更多的内存,但花费的时间更少,而较小的值使用更少的内存,但计算需要更长的时间。
  • time_major:输入和输出tensor的形状格式。如果为真,这些张量的形状必须是[max_time,batch_size,depth]。如果为假,这些张量的形状必须是[batch_size,max_time,depth]。使用time_major=true会更有效率,因为它可以避免在RNN计算的开始和结束时进行换位。但是,大多数TensorFlow数据都是批处理主数据,因此默认情况下,此函数为False。
  • scope:创建的子图的可变作用域;默认为“RNN”。

在LSTM的最后,需要用该函数得出结果。

  1. self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(
  2. lstm_cell, self.l_in_y, initial_state=self.cell_init_state, time_major=False)

返回的是一个元组 (outputs, state):

outputs:LSTM的最后一层的输出,是一个tensor。如果为time_major== False,则它的shape为[batch_size,max_time,cell.output_size]。如果为time_major== True,则它的shape为[max_time,batch_size,cell.output_size]。

states:states是一个tensor。state是最终的状态,也就是序列中最后一个cell输出的状态。一般情况下states的形状为 [batch_size, cell.output_size],但当输入的cell为BasicLSTMCell时,states的形状为[2,batch_size, cell.output_size ],其中2也对应着LSTM中的cell state和hidden state。

整个LSTM的定义过程为:

  1. def add_input_layer(self,):
  2. #X最开始的形状为(256 batch,28 steps,28 inputs)
  3. #转化为(256 batch*28 steps,128 hidden)
  4. l_in_x = tf.reshape(self.xs, [-1, self.input_size], name='to_2D')
  5. #获取Ws和Bs
  6. Ws_in = self._weight_variable([self.input_size, self.cell_size])
  7. bs_in = self._bias_variable([self.cell_size])
  8. #转化为(256 batch*28 steps,256 hidden)
  9. with tf.name_scope('Wx_plus_b'):
  10. l_in_y = tf.matmul(l_in_x, Ws_in) + bs_in
  11. # (batch * n_steps, cell_size) ==> (batch, n_steps, cell_size)
  12. # (256*28,256)->(256,28,256)
  13. self.l_in_y = tf.reshape(l_in_y, [-1, self.n_steps, self.cell_size], name='to_3D')
  14. def add_cell(self):
  15. #神经元个数
  16. lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)
  17. #每一次传入的batch的大小
  18. with tf.name_scope('initial_state'):
  19. self.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
  20. #不是主列
  21. self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(
  22. lstm_cell, self.l_in_y, initial_state=self.cell_init_state, time_major=False)
  23. def add_output_layer(self):
  24. #设置Ws,Bs
  25. Ws_out = self._weight_variable([self.cell_size, self.output_size])
  26. bs_out = self._bias_variable([self.output_size])
  27. # shape = (batch,output_size)
  28. # (256,10)
  29. with tf.name_scope('Wx_plus_b'):
  30. self.pred = tf.matmul(self.cell_final_state[-1], Ws_out) + bs_out

全部代码

该例子为手写体识别例子,将手写体的28行分别作为每一个step的输入,输入维度均为28列。

  1. import tensorflow as tf
  2. from tensorflow.examples.tutorials.mnist import input_data
  3. import numpy as np
  4. mnist = input_data.read_data_sets("MNIST_data",one_hot = "true")
  5. BATCH_SIZE = 256 # 每一个batch的数据数量
  6. TIME_STEPS = 28 # 图像共28行,分为28个step进行传输
  7. INPUT_SIZE = 28 # 图像共28列
  8. OUTPUT_SIZE = 10 # 共10个输出
  9. CELL_SIZE = 256 # RNN 的 hidden unit size,隐含层神经元的个数
  10. LR = 1e-3 # learning rate,学习率
  11. def get_batch(): #获取训练的batch
  12. batch_xs,batch_ys = mnist.train.next_batch(BATCH_SIZE)
  13. batch_xs = batch_xs.reshape([BATCH_SIZE,TIME_STEPS,INPUT_SIZE])
  14. return [batch_xs,batch_ys]
  15. class LSTMRNN(object): #构建LSTM的类
  16. def __init__(self, n_steps, input_size, output_size, cell_size, batch_size):
  17. self.n_steps = n_steps
  18. self.input_size = input_size
  19. self.output_size = output_size
  20. self.cell_size = cell_size
  21. self.batch_size = batch_size
  22. #输入输出
  23. with tf.name_scope('inputs'):
  24. self.xs = tf.placeholder(tf.float32, [None, n_steps, input_size], name='xs')
  25. self.ys = tf.placeholder(tf.float32, [None, output_size], name='ys')
  26. #直接加层
  27. with tf.variable_scope('in_hidden'):
  28. self.add_input_layer()
  29. #增加LSTM的cell
  30. with tf.variable_scope('LSTM_cell'):
  31. self.add_cell()
  32. #直接加层
  33. with tf.variable_scope('out_hidden'):
  34. self.add_output_layer()
  35. #计算损失值
  36. with tf.name_scope('cost'):
  37. self.compute_cost()
  38. #训练
  39. with tf.name_scope('train'):
  40. self.train_op = tf.train.AdamOptimizer(LR).minimize(self.cost)
  41. #正确率计算
  42. self.correct_pre = tf.equal(tf.argmax(self.ys,1),tf.argmax(self.pred,1))
  43. self.accuracy = tf.reduce_mean(tf.cast(self.correct_pre,tf.float32))
  44. def add_input_layer(self,):
  45. #X最开始的形状为(256 batch,28 steps,28 inputs)
  46. #转化为(256 batch*28 steps,128 hidden)
  47. l_in_x = tf.reshape(self.xs, [-1, self.input_size], name='to_2D')
  48. #获取Ws和Bs
  49. Ws_in = self._weight_variable([self.input_size, self.cell_size])
  50. bs_in = self._bias_variable([self.cell_size])
  51. #转化为(256 batch*28 steps,256 hidden)
  52. with tf.name_scope('Wx_plus_b'):
  53. l_in_y = tf.matmul(l_in_x, Ws_in) + bs_in
  54. # (batch * n_steps, cell_size) ==> (batch, n_steps, cell_size)
  55. # (256*28,256)->(256,28,256)
  56. self.l_in_y = tf.reshape(l_in_y, [-1, self.n_steps, self.cell_size], name='to_3D')
  57. def add_cell(self):
  58. #神经元个数
  59. lstm_cell = tf.contrib.rnn.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)
  60. #每一次传入的batch的大小
  61. with tf.name_scope('initial_state'):
  62. self.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
  63. #不是主列
  64. self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(
  65. lstm_cell, self.l_in_y, initial_state=self.cell_init_state, time_major=False)
  66. def add_output_layer(self):
  67. #设置Ws,Bs
  68. Ws_out = self._weight_variable([self.cell_size, self.output_size])
  69. bs_out = self._bias_variable([self.output_size])
  70. # shape = (batch,output_size)
  71. # (256,10)
  72. with tf.name_scope('Wx_plus_b'):
  73. self.pred = tf.matmul(self.cell_final_state[-1], Ws_out) + bs_out
  74. def compute_cost(self):
  75. self.cost = tf.reduce_mean(
  76. tf.nn.softmax_cross_entropy_with_logits(logits = self.pred,labels = self.ys)
  77. )
  78. def _weight_variable(self, shape, name='weights'):
  79. initializer = np.random.normal(0.0,1.0 ,size=shape)
  80. return tf.Variable(initializer, name=name,dtype = tf.float32)
  81. def _bias_variable(self, shape, name='biases'):
  82. initializer = np.ones(shape=shape)*0.1
  83. return tf.Variable(initializer, name=name,dtype = tf.float32)
  84. if __name__ == '__main__':
  85. #搭建 LSTMRNN 模型
  86. model = LSTMRNN(TIME_STEPS, INPUT_SIZE, OUTPUT_SIZE, CELL_SIZE, BATCH_SIZE)
  87. sess = tf.Session()
  88. sess.run(tf.global_variables_initializer())
  89. #训练10000次
  90. for i in range(10000):
  91. xs, ys = get_batch() #提取 batch data
  92. if i == 0:
  93. #初始化data
  94. feed_dict = {
  95. model.xs: xs,
  96. model.ys: ys,
  97. }
  98. else:
  99. feed_dict = {
  100. model.xs: xs,
  101. model.ys: ys,
  102. model.cell_init_state: state #保持 state 的连续性
  103. }
  104. #训练
  105. _, cost, state, pred = sess.run(
  106. [model.train_op, model.cost, model.cell_final_state, model.pred],
  107. feed_dict=feed_dict)
  108. #打印精确度结果
  109. if i % 20 == 0:
  110. print(sess.run(model.accuracy,feed_dict = {
  111. model.xs: xs,
  112. model.ys: ys,
  113. model.cell_init_state: state #保持 state 的连续性
  114. }))

希望得到朋友们的喜欢。

有不懂的朋友可以评论询问噢。

发表评论

表情:
评论列表 (有 0 条评论,567人围观)

还没有评论,来说两句吧...

相关阅读