Keras使用自定义root_mean_squared_error_fraction损失函数加载报错问询
问题核心原因
Keras保存模型时仅会序列化自定义损失函数的名称,不会存储函数本身的实现逻辑,因此加载已保存的包含自定义损失的模型时,必须显式告诉Keras自定义函数名称对应的实际对象。
修复方案
修改你代码中load_model的调用逻辑,新增custom_objects参数传入自定义损失的映射关系即可:
# 把原来的saved = load_model('bestmodel.h5') 替换为下面的代码 saved = load_model('bestmodel.h5', custom_objects={ 'root_mean_squared_error_fraction': root_mean_squared_error_fraction })
可选优化:全局注册自定义损失
如果不想每次加载模型都手动传入custom_objects,可以给自定义损失函数加上Keras序列化注册装饰器,Keras会自动识别该函数:
from keras import backend as K import keras @keras.saving.register_keras_serializable() def root_mean_squared_error_fraction(y_true, y_pred): return K.sqrt(K.mean(K.square((y_pred - y_true)/y_true)))
添加装饰器后,后续加载模型时无需额外传参,直接调用load_model('bestmodel.h5')即可正常运行。
注意事项
如果在其他Python脚本中加载该保存好的模型,需要保证脚本内可以访问到root_mean_squared_error_fraction函数的定义,或者提前完成函数的全局注册。
内容的提问来源于stack exchange,提问作者MikeP
相关产品推荐
相关产品推荐

