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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:45:06