Keras 中 LSTM 的数学公式?

The mathematical formulation of LSTM in Keras?

根据wikipedia-lstm-math-equation的数学公式,如下所示,

应该只有隐藏状态 h_t 和细胞状态 c_t。但是,当我尝试在 Keras 上编写 RNN 代码时,有三个:lstm_outputstate_hstate_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 进行重复激活,这些应在文档中明确注明。