基于VGG19的预训练模型加载预测时出现Graph disconnected错误求助
问题原因分析
你遇到的Graph disconnected错误完全是预测代码里的错误操作导致的:
- 加载好的模型
m已经是完整的9分类模型,你却在预测后试图重新构建新模型,还用到了未定义的x变量——这个变量和加载的模型图没有任何关联,直接导致张量连接断裂。 - 错误使用
decode_predictions函数,它是专门解析ImageNet 1000分类结果的,你的模型是自定义9分类,完全不适用。 - 代码里的argparse参数定义后完全没用到,属于冗余代码。
修复步骤
- 删除冗余的模型重构代码:加载的
m就是训练好的完整模型,直接用它做预测即可,不需要重新添加Dense层或构建新Model。 - 替换分类结果解析逻辑:去掉
decode_predictions,换成你自己的9分类标签映射逻辑。 - 清理冗余代码:删除没用的argparse部分,或者实际用上它。
- 修正OpenCV显示代码:
cv2.imshow需要传入窗口名称参数。
修正后的完整预测代码
import os import cv2 import numpy as np from keras.preprocessing import image as image_utils from keras.applications.imagenet_utils import preprocess_input from tensorflow.keras.models import load_model # 加载训练好的模型 m = load_model('model_he.h5') # 替换成你自己的9分类标签,顺序要和训练时的class_count对应 class_labels = ["类别1", "类别2", "类别3", "类别4", "类别5", "类别6", "类别7", "类别8", "类别9"] # 测试图片路径 img_path = "val/" files = os.listdir(img_path) print("[INFO] loading and processing images...") for filename in files: file = os.path.join(img_path, filename) # 加载原始图片用于显示 original = cv2.imread(file) if original is None: print(f"[WARNING] 无法读取图片 {file},跳过") continue # 预处理图片,和训练时保持一致 image = image_utils.load_img(file, target_size=(224, 224)) image = image_utils.img_to_array(image) image = np.expand_dims(image, axis=0) image = preprocess_input(image) print(f"[INFO] 分类图片 {filename}...") # 直接用加载好的模型预测 predictions = m.predict(image, verbose=0) # 获取预测结果:概率最大的类别索引和概率值 pred_idx = np.argmax(predictions[0]) pred_label = class_labels[pred_idx] pred_prob = predictions[0][pred_idx] * 100 # 打印所有类别概率 print("所有类别预测概率:") for idx, (label, prob) in enumerate(zip(class_labels, predictions[0])): print("{}. {}: {:.2f}%".format(idx + 1, label, prob * 100)) # 在图片上绘制预测结果 cv2.putText(original, f"Label: {pred_label}, {pred_prob:.2f}%", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2) # 修正imshow参数:窗口名 + 图片 cv2.imshow("Prediction Result", original) # 按任意键关闭窗口,继续下一张 cv2.waitKey(0) cv2.destroyWindow("Prediction Result") # 最后关闭所有窗口 cv2.destroyAllWindows()
额外注意事项
- 确保
class_labels的顺序和你训练时的类别顺序完全一致,否则预测标签会对应错误。 - 如果训练时用了其他预处理方式(比如自定义归一化),要保证预测时的预处理和训练完全相同。
- 加载模型时如果遇到自定义正则化等问题,可以在
load_model里添加custom_objects参数,比如:
from keras import regularizers m = load_model('model_he.h5', custom_objects={"l2": regularizers.l2, "l1": regularizers.l1})
内容的提问来源于stack exchange,提问作者user979974
相关产品推荐
相关产品推荐

