TensorFlow中使用tf.contrib.rnn.BasicLSTMCell()的方法来搭建LSTM网络,其中有一项参数为state_is_tuple,官方建议设置为True,这个参数的实际就是使LSTM的state以tuple的形式输出,shape为batch size和num_step,也就是min batch的大小和LSTM展开的步数,而state分为c与h,c为cell state,即memory的state,h为hidden state,也就是lstm的最终输出。
LSTM单元根据输入的序列长度进行展开,当前时刻得到的state又作为参数传入下一时刻。代码如下:
with tf.variable_scope("LSTM_layer"):
for time_step in range(num_step):
if time_step>0:
tf.get_variable_scope().reuse_variables()
(cell_output, state)=cell(inputs[:,time_step,:],state)
out_put.append(cell_output)