用deepctr搭建网络时,自定义focal loss,再用普通load_model
会报错如下:
ValueError: Unknown loss function:binary_focal_loss_fixed
ValueError: Unknown loss function:binary_focal_loss_fixed
参考文章如下,要load_model
的时候指定custom_objects
https://blog.csdn.net/liushuijingying2/article/details/87695593
代码如下:
model = load_model(save_path, custom_objects={
'binary_focal_loss_fixed': binary_focal_loss})
''' focal loss '''
def binary_focal_loss(gamma=2, alpha=0.25):
alpha = tf.constant(alpha, dtype=tf.float32)
gamma = tf.constant(gamma, dtype=tf.float32)
def binary_focal_loss_fixed(y_true, y_pred):
"""
y_true shape need be (None,1)
y_pred need be compute after sigmoid
"""
y_true = tf.cast(y_true, tf.float32)
alpha_t = y_true * alpha + (K.ones_like(y_true) - y_true) * (1 - alpha)
p_t = y_true * y_pred + (K.ones_like(y_true) - y_true) * (K.ones_like(y_true) - y_pred) + K.epsilon()
focal_loss = - alpha_t * K.pow((K.ones_like(y_true) - p_t), gamma) * K.log(p_t)
return K.mean(focal_loss)
return binary_focal_loss_fixed
但是又出现了:
ValueError: Unknown layer: NoMask
ValueError: Unknown layer: NoMask
报错说我们没有NoMask
层,解决办法如下:
from deepctr.layers import custom_objects
custom = custom_objects
custom.update({
'binary_focal_loss_fixed': binary_focal_loss})
model = load_model(save_path, custom_objects=custom)
点进custom_objects
去看,这个字典里确实有NoMask