我在使用 Keras 加载预训练的权重时遇到了一些问题。假设我有一个 keras 模型model,并且我的权重存储在my_weights.h5.
我尝试按如下方式加载我的重量:
model.load_weights("my_weights.h5", by_name=True)
但这给了我以下错误:
Layer #1 (named "conv2d_1"), weight <tf.Variable 'conv2d_1/kernel:0' shape=(3, 3, 32, 64) dtype=float32> has shape (3, 3, 32, 64), but the saved weight has shape (32, 3, 3, 3).
所以我试着看看我的重量和模型结构的形状是什么:
for layer in model_body.layers :
print(layer.name+" : input ("+str(layer.input_shape)+") output ("+str(layer.output_shape)+")")
print("__")
with h5py.File(weights_filepath, 'r') as f:
for k in f.keys():
for l in f[k].keys():
for m in f[k][l].keys():
print(k+ " : " + m + " : " + str(f[k][l][m].shape))
conv2d_1 : input ((None, None, None, 32)) output ((None, None, None, 64))
__
conv2d_1 : kernel:0 : (3, 3, 3, 32)
(我只保留了错误中出现的图层)
通过看到这一点,我不明白为什么形状不匹配,以及(3, 3, 32, 64)错误中的形状来自哪里)。我错过了什么吗?