使用Keras训练模型后,我可以使用以下方法获得权重数组列表:
myModel.get_weights()
或
myLayer.get_weights()
我想知道每个重量阵列对应的名字。我知道如何通过保存模型和解析HDF5文件来间接地做到这一点,但肯定必须有直接的方法来实现这一目标吗?
答案 0 :(得分:9)
函数get_weights
返回一个numpy数组列表,其中没有名称信息。
至于Model.get_weights()
,它只是每个[展平]图层Layer.get_weights()
的串联。
但是,Layer.weights
可以直接访问后端变量,这些,是的,可能有一个名称。然后解决方案是遍历每个图层的每个权重,检索其name
属性。
VGG16的一个例子:
from keras.applications.vgg16 import VGG16
model = VGG16()
names = [weight.name for layer in model.layers for weight in layer.weights]
weights = model.get_weights()
for name, weight in zip(names, weights):
print(name, weight.shape)
输出:
block1_conv1_W_6:0 (3, 3, 3, 64)
block1_conv1_b_6:0 (64,)
block1_conv2_W_6:0 (3, 3, 64, 64)
block1_conv2_b_6:0 (64,)
block2_conv1_W_6:0 (3, 3, 64, 128)
block2_conv1_b_6:0 (128,)
block2_conv2_W_6:0 (3, 3, 128, 128)
block2_conv2_b_6:0 (128,)
block3_conv1_W_6:0 (3, 3, 128, 256)
block3_conv1_b_6:0 (256,)
block3_conv2_W_6:0 (3, 3, 256, 256)
block3_conv2_b_6:0 (256,)
block3_conv3_W_6:0 (3, 3, 256, 256)
block3_conv3_b_6:0 (256,)
block4_conv1_W_6:0 (3, 3, 256, 512)
block4_conv1_b_6:0 (512,)
block4_conv2_W_6:0 (3, 3, 512, 512)
block4_conv2_b_6:0 (512,)
block4_conv3_W_6:0 (3, 3, 512, 512)
block4_conv3_b_6:0 (512,)
block5_conv1_W_6:0 (3, 3, 512, 512)
block5_conv1_b_6:0 (512,)
block5_conv2_W_6:0 (3, 3, 512, 512)
block5_conv2_b_6:0 (512,)
block5_conv3_W_6:0 (3, 3, 512, 512)
block5_conv3_b_6:0 (512,)
fc1_W_6:0 (25088, 4096)
fc1_b_6:0 (4096,)
fc2_W_6:0 (4096, 4096)
fc2_b_6:0 (4096,)
predictions_W_6:0 (4096, 1000)
predictions_b_6:0 (1000,)