根据 wikipedia-lstm-math-equation 中的数学公式, 如下所示,
应该只有隐藏状态h_t
和单元格状态c_t
。但是,当我尝试在 Keras 上编写 RNN 代码时,存在三个:lstm_output
、state_h
和 state_c
。
我现在想知道 lstm_output
的数学公式是什么?
这是我的代码:
from keras.layers import Input, LSTM
lstm_input = Input(shape=(28, 10))
lstm_output, state_h, state_c = LSTM(units=32,
return_sequences=True,
return_state=True,
unroll=True)(lstm_input)
print(lstm_output, state_h, state_c)
它给了
Using TensorFlow backend.
(<tf.Tensor 'lstm_1/transpose_1:0' shape=(?, 28, 32) dtype=float32>, <tf.Tensor 'lstm_1/mul_167:0' shape=(?, 32) dtype=float32>, <tf.Tensor 'lstm_1/add_221:0' shape=(?, 32) dtype=float32>)
最佳答案
让我们分解一下,看看this line来自源代码 - return h, [h, c]
:
- lstm_output:是每个时间步长的
h
。所以它的形状是(batch_size, sequence_length, hidden_size)
,在你的例子中是(?, 28, 32)
。作为documentation说,它作为一个序列返回,因为你设置了return_sequences=True
。 - state_h: 是last 时间步长的
h
,如果您可以检查,它应该等于lstm_output[:,- 1]
。请注意为什么它的形状是(?, 32)
,因为它是最后一个时间步的输出,而不是每个时间步的输出。 - state_c: 是最后时间步长的
c
。
这些方程通常以不同的方式实现以优化某些特征,但它们都遵循 original paper .请注意,激活可能会有变化,例如使用 hard_sigmoid
进行循环激活,这些应该在文档中明确注明。
关于keras - Keras 中 LSTM 的数学公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809242/