keras - 加载具有自定义损失函数的模型 : ValueError: 'Unknown loss function' in keras

标签 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

最佳答案

加载模型时使用 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})

你加载的是 siamese 还是 base_model?

关于keras - 加载具有自定义损失函数的模型 : ValueError: 'Unknown loss function' in keras,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52533340/

相关文章:

python - 全连接层大小

python - Levenberg-Marquardt 优化算法的 keras 实现作为自定义优化器

python - “Tensor”对象不能使用 Keras 和 seq2seq 模型调用

python - 通过 Keras 模型可视化地 block 决策边界

python - 我尝试在数据集上微调 VGG16,但遇到了有关加载 VGG16 权重的 OSError

tensorflow - 在 Keras 分类神经网络中以精度换取更好的召回率

python - Keras LSTM 从 CSV "expected ndim=3, found ndim=2. Full shape received: (None, 150)"加载数据

python - 在加载 Keras 保存模型时,是否有人得到 "AttributeError: ' str' 对象没有属性 'decode'"

c++ - 将 Keras 模型转换为 C++

python - 多元时间序列的 Keras 递归神经网络