给定一个训练有素的 LSTM 模型,我想对单个时间步执行推理,即以下示例中的 seq_length = 1
。在每个时间步之后,需要为下一个“批处理”记住内部 LSTM(内存和隐藏)状态。在推理的最开始,在给定输入的情况下计算内部 LSTM 状态 init_c, init_h
。然后将它们存储在传递给 LSTM 的 LSTMStateTuple
对象中。在训练期间,每个时间步都会更新此状态。但是,对于推理,我希望 state
保存在批处理之间,即初始状态只需要在最开始时计算,之后 LSTM 状态应该在每个“批处理”之后保存(n =1)。
我发现了这个相关的 StackOverflow 问题:Tensorflow, best way to save state in RNNs? .然而,这只适用于 state_is_tuple=False
,但这种行为很快就会被 TensorFlow 弃用(参见 rnn_cell.py)。 Keras 似乎有一个很好的包装器可以使 stateful LSTMs 成为可能,但我不知道在 TensorFlow 中实现这一点的最佳方法。 TensorFlow GitHub上的这个issue也和我的问题有关:https://github.com/tensorflow/tensorflow/issues/2838
对于构建有状态 LSTM 模型有什么好的建议吗?
inputs = tf.placeholder(tf.float32, shape=[None, seq_length, 84, 84], name="inputs")
targets = tf.placeholder(tf.float32, shape=[None, seq_length], name="targets")
num_lstm_layers = 2
with tf.variable_scope("LSTM") as scope:
lstm_cell = tf.nn.rnn_cell.LSTMCell(512, initializer=initializer, state_is_tuple=True)
self.lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * num_lstm_layers, state_is_tuple=True)
init_c = # compute initial LSTM memory state using contents in placeholder 'inputs'
init_h = # compute initial LSTM hidden state using contents in placeholder 'inputs'
self.state = [tf.nn.rnn_cell.LSTMStateTuple(init_c, init_h)] * num_lstm_layers
outputs = []
for step in range(seq_length):
if step != 0:
scope.reuse_variables()
# CNN features, as input for LSTM
x_t = # ...
# LSTM step through time
output, self.state = self.lstm(x_t, self.state)
outputs.append(output)
最佳答案
我发现将所有图层的整个状态保存在占位符中是最简单的方法。
init_state = np.zeros((num_layers, 2, batch_size, state_size))
...
state_placeholder = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size])
然后解压并创建一个 LSTMStateTuples 元组,然后再使用原生 tensorflow RNN Api。
l = tf.unpack(state_placeholder, axis=0)
rnn_tuple_state = tuple(
[tf.nn.rnn_cell.LSTMStateTuple(l[idx][0], l[idx][1])
for idx in range(num_layers)]
)
RNN 传入 API:
cell = tf.nn.rnn_cell.LSTMCell(state_size, state_is_tuple=True)
cell = tf.nn.rnn_cell.MultiRNNCell([cell]*num_layers, state_is_tuple=True)
outputs, state = tf.nn.dynamic_rnn(cell, x_input_batch, initial_state=rnn_tuple_state)
state
- 变量将作为占位符提供给下一批。
关于python - TensorFlow:为下一批记住 LSTM 状态(有状态 LSTM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38241410/