【发布时间】:2018-06-29 21:23:45
【问题描述】:
我试图将现有的经过训练的 PyTorch 模型移植到 Keras。
在移植过程中,我卡在了 LSTM 层。
LSTM 网络的 Keras 实现似乎有三种状态类型的状态矩阵,而 Pytorch 实现有四种。
例如,对于具有 hidden_layers=64、input_size=512 & output size=128 状态参数的双向 LSTM,如下所示
Keras LSTM 的状态参数
[<tf.Variable 'bidirectional_1/forward_lstm_1/kernel:0' shape=(512, 256) dtype=float32_ref>,
<tf.Variable 'bidirectional_1/forward_lstm_1/recurrent_kernel:0' shape=(64, 256) dtype=float32_ref>,
<tf.Variable 'bidirectional_1/forward_lstm_1/bias:0' shape=(256,) dtype=float32_ref>,
<tf.Variable 'bidirectional_1/backward_lstm_1/kernel:0' shape=(512, 256) dtype=float32_ref>,
<tf.Variable 'bidirectional_1/backward_lstm_1/recurrent_kernel:0' shape=(64, 256) dtype=float32_ref>,
<tf.Variable 'bidirectional_1/backward_lstm_1/bias:0' shape=(256,) dtype=float32_ref>]
PyTorch LSTM 的状态参数
['rnn.0.rnn.weight_ih_l0', torch.Size([256, 512])],
['rnn.0.rnn.weight_hh_l0', torch.Size([256, 64])],
['rnn.0.rnn.bias_ih_l0', torch.Size([256])],
['rnn.0.rnn.bias_hh_l0', torch.Size([256])],
['rnn.0.rnn.weight_ih_l0_reverse', torch.Size([256, 512])],
['rnn.0.rnn.weight_hh_l0_reverse', torch.Size([256, 64])],
['rnn.0.rnn.bias_ih_l0_reverse', torch.Size([256])],
['rnn.0.rnn.bias_hh_l0_reverse', torch.Size([256])],
我试图查看这两种实现的代码,但不能理解太多。
有人可以帮我将 PyTorch 中的 4 组状态参数转换为 Keras 中的 3 组状态参数
【问题讨论】:
-
奇怪的是 Torch 在 LSTM 中有 4 个状态矩阵,考虑到模型应该有 3 个设计。
-
是的,LSTM 的 PyTorch 实现略有不同:pytorch.org/docs/0.3.0/nn.html?highlight=lstm#torch.nn.LSTM。有两组偏置参数。如果你想将 PyTorch 参数转换为 Keras,我的建议是关闭偏置参数。