Tensorflow中RNN/LSTM内部具体是如何处理数据的,batch、num_steps是如何被丢尽网络里,训练的流程
在学习Tensorflow的源码时发现一个很重要的现象,就是tensorflow在训练RNN/LSTM的机制,因为这两种网络被常常用于NLP方面,所以这里就拿NLP举例子。
承接上一篇:Tensorflow中的词向量
我提到了Tensorflow中的词向量的表达方式,那么在LSTM中,一句话比如5个单词,按照词向量,就是一个3维的矩阵
[[词1对应的词向量],[词2对应的词向量],[词3对应的词向量],[词4对应的词向量],[词5对应的词向量]],其中每一个词向量又是一个
list,那么这样的3维矩阵,进入网络,在Tensorflow中的具体是这样的,先看代码:
with tf.variable_scope("RNN"):
for time_step in range(num_steps):#num_steps表示一个句子的长度
if time_step > 0:
tf.get_variable_scope().reuse_variables() (cell_output, state) = cell(inputs[:, time_step, :], state) #inputs[:, time_step, :]的shape是(batch_size, size)
outputs.append(cell_output)
进去的流程是这样的,如下图所示:
那么上面的代码表达的就是图中的意思,所以batch就是训练数据中句子的长度,num_steps就是句子的长度
因为就是记录一下,所以写的不是很好看,说明白道理就行。