重量在Keras的名称 [英] Weights by name in Keras
问题描述
使用Keras训练模型后,我可以使用以下方法获得权重数组的列表:
After training a model using Keras, I can get a list of weight arrays using:
myModel.get_weights()
或
myLayer.get_weights()
我想知道与每个权重数组相对应的名称.我知道如何通过保存模型并解析HDF5文件来间接执行此操作,但是肯定有直接的方法可以做到这一点?
I'd like to know the names corresponding to each weight array. I know how to do this indirectly by saving the model and parsing the HDF5 file but surely there must be a direct way to accomplish this?
推荐答案
函数get_weights
返回不包含名称信息的numpy数组的列表.
Function get_weights
returns a list of numpy arrays with no name information in them.
对于Model.get_weights()
,它只是[flattened]每一层的Layer.get_weights()
的串联.
As for Model.get_weights()
, it's just the concatenation of Layer.get_weights()
for each one of the [flattened] layers.
但是,Layer.weights
可以直接访问后端变量,可以,这些变量都有名称.然后,解决方案是遍历每层的每个权重,以获取其name
属性.
However, Layer.weights
gives direct access to the backend variables, and these, yes, may have a name. The solution then is to iterate through each weight of each layer, retrieving its name
attribute.
使用VGG16的示例:
An example with 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,)
这篇关于重量在Keras的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!