我有以下 LSTM 模型,我训练并将其权重保存到 hdf5 文件中。 如何加载/打印/查看每一层的权重?
# define the LSTM model
model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]),return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))#change to 256
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
### Generating text ###
# load the network weights
weightsfile = "C:\\Users\\...\\weights-improvement.hdf5"
model.load_weights(weightsfile)
model.compile(loss='categorical_crossentropy', optimizer='adam')
在 pytorch 中,您可以像这样遍历模型参数:
for param in model.parameters():
print(type(param), param.size())
# <class 'torch.Tensor'> (20L,)
# <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
从那里你可以打印出图层等
在张量流中,您可以通过以下方式查看图层:
print(model.trainable_variables)
这将向您展示如下所示的内容:
[<tf.Variable 'conv2d/kernel:0' shape=(3, 3, 1, 32) dtype=float32>,
<tf.Variable 'conv2d/bias:0' shape=(32,) dtype=float32>, <tf.Variable
'dense/kernel:0' shape=(6272, 32) dtype=float32>, <tf.Variable 'dense/bias:0'
shape=(32,) dtype=float32>, <tf.Variable 'dense_1/kernel:0' shape=(32, 10)
dtype=float32>, <tf.Variable 'dense_1/bias:0' shape=(10,) dtype=float32>]
然后您可以按名称查找特定权重,如下所示:
var = [v for v in model.trainable_variables() if v.name == 'conv2d/bias:0'][0]