我不确定我是否做错了什么,但无论出于何种原因,当我按照这里的 tf 2.4.1 示例操作时
我得到的结果与示例中的结果不同,实际上,我得到的是示例结果的负值。
这是我所做的
import tensorflow as tffrom tensorflow.keras.losses import cosine_similarityy_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)
并在我的模型中使用它来解决这个问题。如果有人知道我不应该这样做,任何建议都将不胜感激!
回答:
这不是你的错,由于一些历史原因,tf.keras.losses.cosine_similarity
在 tf v1.15
中只会返回余弦值,但在 tf v2.4.1
中会返回负余弦值。
tf.keras.losses.cosine_similarity
在 tf v1.15 源代码:
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.keras.losses.cosine_similarity
在 tf v2.4.1 源代码:
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 v2.4.1
中一样使用 tf.keras.losses.cosine_similarity
,只需在其输出前加上负号即可