TF2.0中如何计算两个张量的余弦相似度和欧氏距离?

How to calculate Cosine similarity and Euclidean distance between two tensors in TF2.0?

我有两个张量(OQ、OA),在我的模型的最后一层的末尾具有如下形状。

OQ 形状:(1, 600)

OA 形状:(1, 600)

这些张量的类型是'tensorflow.python.framework.ops.Tensor'

  1. 我们如何在 Tensorflow 2.0 中计算这些张量的余弦相似度和欧氏距离?
  2. 我们是再次得到张量还是[0,1]之间的单个分值?请帮忙。

我试过了,但无法查看分数。

score_cosine = tf.losses.cosine_similarity(tf.nn.l2_normalize(OQ, 0), tf.nn.l2_normalize(OA, 0))
print (score_cosine)

输出:Tensor("Neg_1:0", shape=(1,), dtype=float32)

您可以在 tensorflow 2.X 中计算欧氏距离和余弦相似度,如下所示。返回的输出也将是一个张量。

import tensorflow as tf

# It should be tf 2.0 or greater
print("Tensorflow Version:",tf.__version__)

#Create Tensors
x1 = tf.constant([1.0, 112332.0, 89889.0], shape=(1,3))
print("x1 tensor shape:",x1.shape)
y1 = tf.constant([1.0, -2.0, -8.0], shape=(1,3))
print("y1 tensor shape:",y1.shape)

#Cosine Similarity
s = tf.keras.losses.cosine_similarity(x1,y1)
print("Cosine Similarity:",s)

#Normalized Euclidean Distance
s = tf.norm(tf.nn.l2_normalize(x1, 0)-tf.nn.l2_normalize(y1, 0),ord='euclidean')
print("Normalized Euclidean Distance:",s)

#Euclidean Distance
s = tf.norm(x1-y1,ord='euclidean')
print("Euclidean Distance:",s)

以上代码的输出为-

Tensorflow Version: 2.1.0
x1 tensor shape: (1, 3)
y1 tensor shape: (1, 3)
Cosine Similarity: tf.Tensor([0.7897223], shape=(1,), dtype=float32)
Normalized Euclidean Distance: tf.Tensor(2.828427, shape=(), dtype=float32)
Euclidean Distance: tf.Tensor(143876.33, shape=(), dtype=float32)