【问题标题】:model.layers[i].get_weights() returns empty listmodel.layers[i].get_weights() 返回空列表
【发布时间】:2021-02-20 06:31:43
【问题描述】:

您好,我有以下代码,我正在将预先保存的自定义权重从 .cpkt 文件加载到 resnet 模型中。

'''

def resnet_model():
    input_tensor = Input(shape=(224,224,3))
    base_model = keras.applications.ResNet50(input_tensor=input_tensor,weights = 'imagenet', include_top = False)
    for layer in base_model.layers:
        layer.trainable = True
    x = base_model.output
    x = GlobalAveragePooling2D(data_format='channels_last')(x)
    x = Dense(256)(x)
    l2_norm_final = Lambda(lambda x: K.l2_normalize(x,axis=1))(x)
    final_model = Model(inputs=base_model.input, outputs = l2_norm_final)

    return final_model

model = resnet_model()
model.load_weights(weights_file_orig)


#this works i.e., W has the model's weights
W = model.get_weights()

#this does not work i.e., w,b have []
all_weights = [], all_biases = []
for layer in model.layers:
    w,b = layer.get_weights()
    all_weights.append(w)
    all_biases.append(b)

'''

如何从保存的 .cpkt 文件中逐层获取权重和偏差?

非常感谢!

【问题讨论】:

  • 哪一层不返回权重?您应该考虑到并非所有层都有权重。
  • 没有层。它们都返回空列表。

标签: keras keras-layer


【解决方案1】:

第一次更正:

你没有正确使用多重赋值,下面提到了更正:

all_weights = [], all_biases = [] # wrong
all_weights, all_biases = [], [] # correct way to use multi-assignment in python

第二次更正:

并非所有层都具有权重,例如:InputDropout 等,因此当您尝试获取这些层的节点权重和偏置权重时,您将遇到错误,表明很少要解压的值,下面的代码应该可以完成工作。

for layer in model.layers:
  try:      
    w,b = layer.get_weights()
    all_weights.append(w)
    all_biases.append(b)
  except:
    pass # not all layers have weights !

如果你想只获得预训练模型(res-net)的权重,那么在运行上面的代码之前定义 model 变量如下:

model = keras.applications.ResNet50(input_tensor=input_tensor,weights = 'imagenet', include_top = False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2021-03-11
    • 2015-10-27
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多