问题遇到的现象和发生背景
Keras训练模型结束后想要直接使用保存好的weights来预测模型,结果遇到了标题所示的错误
问题相关代码
if __name__ == "__main__":
# Use VOC 2012 Dataset
horse_path = 'membrane'
batch_size = 2
model = FCN.get_fcn8s_model()
print('======== Start Test ===========')
model.load_weights('fcn32s.h5')
# 取val图片,测试一下效果
val_gen2 = horse_test_gen.get_horse_generator(horse_path, batch_size=1, input_hw=(256, 256, 3),
mask_hw=(256, 256, 2))
i = 0
for val_images in val_gen2:
img_np = val_images[0]
img_np = (img_np + 1.) * 128
im0 = Image.fromarray(np.uint8(img_np))
im0.save('output/{}_img.jpg'.format(i))
res = model.predict(val_images)[0]
pred_label = res.argmax(axis=2)
pred_label[pred_label == 1] = 255
im1 = Image.fromarray(np.uint8(pred_label))
im1.save('output/{}_pred.png'.format(i))
i += 1
if i == 3:
print('End test')
sys.exit(0)
运行结果及报错内容
======== Start Test ===========
Traceback (most recent call last):
File "E:/PycharmProjects/CloudInn/image_segmentation-master/main.py", line 42, in <module>
model.load_weights('fcn32s.h5')
File "E:\PycharmProjects\CloudInn\venv\lib\site-packages\keras\engine\training_v1.py", line 214, in load_weights
return super(Model, self).load_weights(filepath, by_name, skip_mismatch)
File "E:\PycharmProjects\CloudInn\venv\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "E:\PycharmProjects\CloudInn\venv\lib\site-packages\keras\saving\hdf5_format.py", line 748, in load_weights_from_hdf5_group
raise ValueError(
ValueError: Weight count mismatch for top-level weights when loading weights from file. Model expects 0 top-level weight(s). Received 1 saved top-level weight(s)
自己去网上搜索也没有找到个所以然,为什么会说“模型要求0个顶级权重。收到1个已保存的顶级权重。”,这个要怎么解决?
错误报在“model.load_weights('fcn32s.h5')”这里