设置
正如标题中已经提到的,当我尝试加载保存的模型时,我的自定义丢失功能出现了问题。我的损失如下:
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
weightes_loss = weighted_cross_entropy([0.1,0.9])
所以在训练期间,我使用weighted_loss
函数作为损失函数,一切运行良好。训练结束后,我将模型保存为.h5
file,使用keras API的标准model.save
函数。
问题
当我试图加载模型时
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
变量?
你的损失函数的名字是loss
(即def loss(y_true, y_pred):
)。因此,在加载模型时,您需要指定'loss'
作为其名称:
model = load_model(path, custom_objects={'loss': weighted_loss})