Keras/TensorFlow复用分割模型遇dice_loss未知错误,求解决
解决Keras加载segmentation_models模型时的
dice_loss未识别问题 错误原因
Keras保存.h5模型时,仅会记录损失函数/指标的名称,不会保存其具体实现逻辑。dice_loss和iou_score属于segmentation_models库提供的自定义对象,加载模型时Keras无法自动识别,必须手动传入这些对象的定义。
修复步骤
确保安装并导入segmentation_models库
在Colab中先安装依赖(如果未安装):!pip install segmentation_models然后导入库:
import segmentation_models as sm修改模型加载代码,传入
custom_objects参数
将原来的加载代码替换为:from tensorflow.keras.models import load_model # 注册自定义损失和指标 custom_objects = { 'dice_loss': sm.losses.dice_loss, 'iou_score': sm.metrics.iou_score } # 加载模型时传入custom_objects model = load_model("./drive/MyDrive/RetinaNeurons/RetinaNeuroneCounter.h5", custom_objects=custom_objects)
补充说明
- 如果模型训练时还使用了其他自定义对象(比如自定义优化器、层),也需要将它们一并加入
custom_objects字典中。 - 确保
segmentation_models的版本和训练模型时的版本一致,避免因版本差异导致的兼容性问题。
内容的提问来源于stack exchange,提问作者Vincent Gigot
相关产品推荐
相关产品推荐

