如何加载具有自定义损失函数的 Keras 模型?

How to load a Keras model with a custom loss function?

我创建了以下自定义损失函数:

RMSE = function(y_true,y_pred) {
         k_sqrt(k_mean(k_square(y_pred - y_true))) 
    }

保存模型时效果很好。但是,当我使用以下方式加载模型时:

load_model_hdf5(filepath= "modelpath") 

我收到以下错误:

#Error in py_call_impl(callable, dots$args, dots$keywords):
#      valueError: Unknown loss function:RMSE

也许这个问题和我之前做的这个one有共同点。我应该怎么做才能停止收到此错误?

由于您在模型中使用了 自定义 损失函数,因此在将模型保存在磁盘上时不会保存损失函数,而只会将其名称包含在模型文件。然后,当你稍后想要加载回模型时,你需要将存储的名称对应的损失函数通知模型。要提供该映射,您可以使用 load_model_hdf5 函数的 custom_objects 参数:

load_model_hdf5(filepath = "modelpath", custom_objects = list(RMSE = RMSE))

或者,在训练完成后,如果您只想使用模型进行预测,您可以将 compile = False 参数传递给 load_model_hdf5 函数(因此,不需要损失函数,并且加载):

load_model_hdf5(filepath = "modelpath", compile = False)