<p>如果您使用的是<strong>Keras 2.2.0</strong></p>
<p>当你打印时</p>
<blockquote>
<pre><code>print(model.layers[0].trainable_weights)
</code></pre>
</blockquote>
<p>你应该看到三个张量:<code>lstm_1/kernel, lstm_1/recurrent_kernel, lstm_1/bias:0</code>
每个张量的一个维数应该是</p>
<blockquote>
<p>4 * number_of_units</p>
</blockquote>
<p>其中<em>单位数</em>是你的神经元数。尝试:</p>
<pre><code>units = int(int(model.layers[0].trainable_weights[0].shape[1])/4)
print("No units: ", units)
</code></pre>
<p>这是因为每个张量包含四个LSTM单位的权重(按顺序排列):</p>
<blockquote>
<p><em>i (input), f (forget), c (cell state) and o (output)</em></p>
</blockquote>
<p>因此,为了提取权重,您可以简单地使用slice操作符:</p>
<pre><code>W = model.layers[0].get_weights()[0]
U = model.layers[0].get_weights()[1]
b = model.layers[0].get_weights()[2]
W_i = W[:, :units]
W_f = W[:, units: units * 2]
W_c = W[:, units * 2: units * 3]
W_o = W[:, units * 3:]
U_i = U[:, :units]
U_f = U[:, units: units * 2]
U_c = U[:, units * 2: units * 3]
U_o = U[:, units * 3:]
b_i = b[:units]
b_f = b[units: units * 2]
b_c = b[units * 2: units * 3]
b_o = b[units * 3:]
</code></pre>
<p>来源:<a href="https://github.com/keras-team/keras/blob/master/keras/layers/recurrent.py#L1863" rel="noreferrer">keras code</a></p>