使用自定义损失函数加载模型:ValueError:keras中的“未知损失函数”

时间:2018-09-27 09:06:58

标签: keras

编译模型然后保存。 然后在加载模型时会出现错误。

def triplet_loss(y_true, y_pred, alpha = 0.3):
    anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
    pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), axis=-1)
    basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
    loss = tf.reduce_sum(tf.maximum(basic_loss, 0.0))

    return loss

FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = 
['accuracy'])
FRmodel.save('model.h5')




`FRmodel = load_model('model.h5')`

ValueError: Unknown loss function:triplet_loss

1 个答案:

答案 0 :(得分:0)

在加载模型时使用custom_objects:

def def triplet_loss(y_true, y_pred, alpha = 0.3):
    anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
    pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1)
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), axis=-1)
    basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
    loss = tf.reduce_sum(tf.maximum(basic_loss, 0.0))

    return loss

FRmodel = load_model('model.h5',custom_objects={'triplet_loss':triplet_loss})

您要加载暹罗还是base_model?