keras使用自定义损失函数加载模型时报错ValueError: Unknown loss function: focal_loss_fixed.

自定义的损失函数和加载模型

def focal_loss(gamma=2., alpha=.25):
    def focal_loss_fixed(y_true, y_pred):
        pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
        pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
        facal_loss = -K.sum(alpha * K.pow(1. - pt_1, gamma) * \
                    K.log(K.epsilon()+pt_1))-K.sum((1-alpha) * \
                    K.pow( pt_0, gamma) * K.log(1. - pt_0 + K.epsilon()))
        return facal_loss
    return focal_loss_fixed

#加载模型
model = load_model('./vgg16')

出现报错:ValueError: Unknown loss function: focal_loss_fixed. Please ensure this object is passed to the `custom_objects` argument.

解决方法:报错提示缺少“focal_loss_fixed”这个函数,需要将字典{'focal_loss_fixed':focal_loss}传入load_model中的custom_objects

model = load_model('./vgg16',
                 custom_objects={'focal_loss_fixed': focal_loss})

你可能感兴趣的:(keras,python,深度学习)