【问题标题】:tensorflow.keras.losses.cosine_similarity returns positive values in TensorFlow 1.15tensorflow.keras.losses.cosine_similarity 在 TensorFlow 1.15 中返回正值
【发布时间】:2021-06-03 13:35:15
【问题描述】:

不确定我是否在这里做错了什么,但无论出于何种原因,当我按照 tf 2.4.1 here987654321@ 的示例进行操作时

我没有得到相同的结果,实际上,我得到了示例中结果的否定。

这就是我正在做的事情

import tensorflow as tf
from tensorflow.keras.losses import cosine_similarity

y_true = [[0., 1.], [1., 1.], [1., 1.]]
y_pred = [[1., 0.], [1., 1.], [-1., -1.]]

loss = cosine_similarity(y_true, y_pred, axis=1) 
loss_numpy = loss.eval(session=tf.Session())

print(loss_numpy) # array([ 0.        ,  0.99999994, -0.99999994], dtype=float32)
# expected output array([-0.        , -0.99999994,  0.99999994], dtype=float32)

我假设在 tf 2+ 中不是这种情况,但这是我必须处理的已知问题,还是发生了其他事情?

附言

我已经通过定义解决了这个问题

cosine_proximity_loss = lambda y_true, y_pred: -1. * cosine_similarity(y_true, y_pred)

并在我的模型中使用它。如果有人知道我不应该这样做,任何建议将不胜感激!

【问题讨论】:

    标签: python python-3.x tensorflow machine-learning keras


    【解决方案1】:

    这不是你的错,由于某些历史原因,tf v1.15 中的 tf.keras.losses.cosine_similarity 只会返回余弦值,但 tf v2.4.1 中会返回负余弦值。

    tf v1.15 source codetf.keras.losses.cosine_similarity:

    y_true = nn.l2_normalize(y_true, axis=axis)
    y_pred = nn.l2_normalize(y_pred, axis=axis)
    return math_ops.reduce_sum(y_true * y_pred, axis=axis)
    

    tf v2.4.1 source codetf.keras.losses.cosine_similarity

    y_true = nn.l2_normalize(y_true, axis=axis)
    y_pred = nn.l2_normalize(y_pred, axis=axis)
    return -math_ops.reduce_sum(y_true * y_pred, axis=axis)
    

    所以,如果你想在 tf v1.15 中使用 tf.keras.losses.cosine_similarity,就像在 tf v2.4.1 中一样,只需在输出前添加减号

    【讨论】:

    • 嗯,这很有趣。我想 2.x 使用负相似性,因为它被用作损失函数,所以减少它应该使它“更好”。他们本可以将其重新定义为“余弦距离”......
    • @xdurch0 确实很有趣:)
    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2023-02-16
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多