如何获取Keras中训练后RNN的权重及理解权重数组含义
Understanding SimpleRNN Weights in Keras
Hey there! Let's clear up the confusion around the weights returned by model.get_weights() for your SimpleRNN layer, and address why you're not seeing the extra arrays you expected.
First, recap your layer setup
You defined a SimpleRNN layer with:
- 27 units
- Input shape
(None, 27)(27 input features per time step) return_sequences=True(this only affects the output shape, not the number of weights)
What each weight array represents
When you call model.get_weights(), the three arrays correspond to the core components of a standard unidirectional RNN:
- First (27,27) array: This is the input-to-hidden weight matrix (often denoted
Wxh). Each column maps your 27 input features to one of the 27 RNN units. - Second (27,27) array: This is the hidden-to-hidden recurrent weight matrix (often denoted
Whh). Each column connects the previous time step's 27 hidden states to one of the current time step's 27 units—this is what gives the RNN its "memory" capability. - Third (27,1) array: This is the hidden layer bias vector (often denoted
bh). Depending on your Keras/backend version, it might show as(27,1)instead of a 1D(27,)shape, but each element is the bias value for one of the 27 RNN units.
Why you don't see two extra arrays
You mentioned expecting two more arrays—this is likely a mix-up with one of these scenarios:
- Bidirectional RNNs: If you used
Bidirectional(SimpleRNN(...)), you'd get two full sets of weights (one for the forward pass, one for the backward pass), totaling 6 arrays. But your model uses a standard unidirectional SimpleRNN, so only one set exists. - Additional output layers: If you added a
Denselayer after the SimpleRNN, you'd get extra weights for that layer (a weight matrix and bias vector). But your current model only has the SimpleRNN layer, so no output layer weights are present.
Since your model only contains a single unidirectional SimpleRNN layer, the three arrays you're seeing are exactly all the trainable weights for that layer.
内容的提问来源于stack exchange,提问作者Karan Bhatia
相关产品推荐
相关产品推荐

