Keras使用自定义对象进行load_model时无法正常工作。

12

设置

如标题中所述,当我尝试加载保存的模型时,我的自定义损失函数出现了问题。我的损失函数如下:

def weighted_cross_entropy(weights):

    weights = K.variable(weights)

    def loss(y_true, y_pred):
        y_pred = K.clip(y_pred, K.epsilon(), 1-K.epsilon())

        loss = y_true * K.log(y_pred) * weights
        loss = -K.sum(loss, -1)
        return loss

    return loss

weighted_loss = weighted_cross_entropy([0.1,0.9])

训练时,我使用了weighted_loss函数作为损失函数,一切顺利。当训练结束后,我使用keras API中的标准model.save函数将模型保存为.h5文件。

问题

当我尝试通过以下方式加载模型时:

model = load_model(path,custom_objects={"weighted_loss":weighted_loss})

我收到一个 ValueError 错误,错误信息显示损失函数未知。

错误

错误信息如下所示:

File "...\predict.py", line 29, in my_script
"weighted_loss": weighted_loss})
File "...\Continuum\anaconda3\envs\processing\lib\site-packages\keras\engine\saving.py", line 419, in load_model
model = _deserialize_model(f, custom_objects, compile)
File "...\Continuum\anaconda3\envs\processing\lib\site-packages\keras\engine\saving.py", line 312, in _deserialize_model
sample_weight_mode=sample_weight_mode)
File "...\Continuum\anaconda3\envs\processing\lib\site-packages\keras\engine\training.py", line 139, in compile
loss_function = losses.get(loss)
File "...\Continuum\anaconda3\envs\processing\lib\site-packages\keras\losses.py", line 133, in get
return deserialize(identifier)
File "...\Continuum\anaconda3\envs\processing\lib\site-packages\keras\losses.py", line 114, in deserialize
printable_module_name='loss function')
File "...\Continuum\anaconda3\envs\processing\lib\site-packages\keras\utils\generic_utils.py", line 165, in deserialize_keras_object
':' + function_name)
ValueError: Unknown loss function:loss

问题

我如何解决这个问题?可能是我的包装的损失定义导致了这个问题吗?因此,Keras不知道如何处理weights变量?


请问您能否提供完整的错误日志/堆栈跟踪信息? - today
当然。我添加了完整的消息。 - pafi
2个回答

14

您的损失函数名称为loss(即def loss(y_true, y_pred):)。因此,在加载模型时,您需要指定'loss'作为其名称:

model = load_model(path, custom_objects={'loss': weighted_loss})

-1

为了演示如何使用自定义损失函数或模型保存和加载Keras模型的完整示例,请查看以下GitHub代码片段文件:

使用包装器定义的自定义损失函数: https://gist.github.com/ashkan-abbasi66/a81fe4c4d588e2c187180d5bae734fde

通过子类化定义的自定义损失函数: https://gist.github.com/ashkan-abbasi66/327efe2dffcf9788847d26de934ef7bd

自定义模型: https://gist.github.com/ashkan-abbasi66/d5a525d33600b220fa7b095f7762cb5b

注意: 我在Python 3.8和Tensorflow 2.5上测试了以上示例。

请避免仅提供链接的方式回答。它们可能会失效。 - pafi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接