如何使用自定义损失函数加载Keras模型?
我创建了以下自定义损失函数:
I have created the following custom loss function:
RMSE = function(y_true,y_pred) {
k_sqrt(k_mean(k_square(y_pred - y_true)))
}
当我保存模型时,它工作正常.但是,当我使用以下方法加载模型时:
And it works fine when I save the model. However, when I load the model back using:
load_model_hdf5(filepath= "modelpath")
我收到以下错误:
Error in py_call_impl(callable, dots$args, dots$keywords):
valueError: Unknown loss function:RMSE
也许这个问题与此一个我以前做过.如何避免不断出现此错误?
Maybe this question has something in common with this one I made before. How do I avoid keep getting this error?
由于您在模型中使用了 custom 损失函数,因此当将模型持久保存在磁盘上时,将不会保存损失函数,并且而是仅将其名称包含在模型文件中.然后,当您想在以后重新加载模型时,需要将存储名称对应的损失函数告知模型.要提供该映射,可以使用load_model_hdf5
函数的custom_objects
自变量:
Since you are using a custom loss function in your model, the loss function would not be saved when persisting the model on disk and instead only its name would be included in the model file. Then, when you want to load back the model at a later time, you need to inform the model of the corresponding loss function for the stored name. To provide that mapping, you can use custom_objects
argument of load_model_hdf5
function:
load_model_hdf5(filepath = "modelpath", custom_objects = list(RMSE = RMSE))
或者,在训练结束后,如果您只想使用模型进行预测,则可以将compile = FALSE
参数传递给load_model_hdf5
函数(因此,将不需要并加载损失函数):
Alternatively, after training is finished, if you just want to use the model for prediction you can just pass compile = FALSE
argument to load_model_hdf5
function (hence, the loss function would not be needed and loaded):
load_model_hdf5(filepath = "modelpath", compile = FALSE)