You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tensorflow/Keras与Keras-cv YOLO模型保存重载后预测报错求助

问题根源

加载后的模型中,prediction_decoder属性被反序列化为不可调用的_DictWrapper对象,而非原本的YOLOV8PredictionDecoder实例,导致调用predict()时触发TypeError。

解决方法

方法1:加载时指定自定义对象(推荐)

加载模型时,显式传入Keras CV的自定义对象,确保prediction_decoder正确恢复为可调用实例:

from keras_cv.models.object_detection.yolo_v8 import YOLOV8PredictionDecoder

yolo_load = tf.keras.models.load_model(
    'my_yolo_mdl.keras',
    custom_objects={'YOLOV8PredictionDecoder': YOLOV8PredictionDecoder}
)

之后再按训练时的配置重新编译模型:

optimizer = tf.keras.optimizers.legacy.Adam(
    learning_rate=LEARNING_RATE,
    global_clipnorm=GLOBAL_CLIPNORM,
)

yolo_load.compile(
    optimizer=optimizer, classification_loss="binary_crossentropy", box_loss="ciou"
)

方法2:手动重置prediction_decoder

如果方法1无效,可手动创建与原模型参数一致的YOLOV8PredictionDecoder实例并赋值给加载后的模型:

from keras_cv.models.object_detection.yolo_v8 import YOLOV8PredictionDecoder

# 替换为你训练时的实际参数:类别数量、置信度阈值、NMS阈值等
prediction_decoder = YOLOV8PredictionDecoder(
    classes=YOUR_CLASS_COUNT,
    confidence_threshold=0.25,
    iou_threshold=0.7
)

yolo_load.prediction_decoder = prediction_decoder

完成后即可正常调用yolo_load.predict(img)。

额外说明
  • Keras CV的自定义组件(如YOLOV8PredictionDecoder)无法被TensorFlow默认加载机制自动识别,必须显式声明自定义对象才能正确反序列化。
  • 原模型可正常运行是因为其prediction_decoder是完整的可调用实例,而加载时未指定自定义对象导致该属性被错误序列化。

内容的提问来源于stack exchange,提问作者Ben Howey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 02:23:13