我试图将现有训练有素的PyTorch模型移植到Keras .
在移植过程中,我陷入了LSTM层 .
LSTM网络的Keras实现似乎有三种状态矩阵,而Pytorch实现有四种 .
例如,对于具有hidden_layers = 64的双向LSTM,input_size = 512&output size = 128状态参数,如下所示
State params of 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>]
State params of 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组状态参数
1 回答
他们真的没那么不同 . 如果在PyTorch中总结两个偏置向量,则方程将与Keras中实现的方程相同 .
这是PyTorch documentation上的LSTM公式:
PyTorch使用两个单独的偏置向量进行输入转换(下标以
i
开头)和循环转换(下标以h
开头) .在Keras
LSTMCell
:输入转换中只添加了一个偏差 . 但是,如果我们总结PyTorch中的两个偏差,则方程式将是等价的 .
双偏置LSTM是在cuDNN中实现的(参见developer guide) . 我'm really not that familiar with PyTorch, but I guess that'为什么他们使用两个偏差参数 . 在Keras中,
CuDNNLSTM
层也有两个偏置权重向量 .