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

查看:84
本文介绍了如何使用自定义损失函数加载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 saved the model. However, when I loaded 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. What should I do to stop 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天全站免登陆