加载具有自定义损失 + keras 的模型 [英] Loading model with custom loss + keras
问题描述
在 Keras 中,如果您需要使用附加参数自定义损失,我们可以像 https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-parameter-in-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屋!