使用自定义损失+ keras加载模型 [英] Loading model with custom loss + keras

查看:328
本文介绍了使用自定义损失+ keras加载模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Keras中,如果您需要自定义损失以及其他参数,我们可以像

In Keras, if you need to have a custom loss with additional parameters, we can use it like mentioned on https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-parameter-in-keras

def penalized_loss(noise):
    def loss(y_true, y_pred):
        return K.mean(K.square(y_pred - y_true) - K.square(y_true - noise), axis=-1)
    return loss

当我训练模型时,上述方法有效.但是,一旦训练了模型,我将很难加载模型.当我尝试在如下所示的load_model中使用custom_objects参数

The above method works when I am training the model. However, once the model is trained I am having difficulty in loading the model. When I try to use the custom_objects parameter in load_model like below

model = load_model(modelFile, custom_objects={'penalized_loss': penalized_loss} )

它抱怨ValueError: Unknown loss function:loss

有什么方法可以将损失函数作为custom_objects中的自定义损失之一传递?据我所知,在load_model调用期间,内部函数不在名称空间中.有没有更简单的方法来加载模型或使用带有其他参数的自定义损失

Is there any way to pass in the loss function as one of the custom losses in custom_objects ? From what I can gather, the inner function is not in the namespace during load_model call. Is there any easier way to load the model or use a custom loss with additional parameters

推荐答案

是的! custom_objects期望使用与损失函数完全相同的函数(在您的情况下为内部函数):

Yes, there is! custom_objects expects the exact function that you used as loss function (the inner one in your case):

model = load_model(modelFile, custom_objects={ 'loss': penalized_loss(noise) })

不幸的是,keras不会在模型中存储噪声值,因此您需要将其手动输入到load_model函数.

Unfortunately keras won't store in the model the value of noise, so you need to feed it to the load_model function manually.

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

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