如何使用自定义损失函数加载Keras模型? [英] How load a Keras model with custom loss function?

查看:703
本文介绍了如何使用自定义损失函数加载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)

这篇关于如何使用自定义损失函数加载Keras模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆