列表中每个张量之间的 Tensorflow 余弦相似度

Tensorflow cosine similarity between each tensor in a list

我有 2 个带有张量的列表(数组),我想计算两个列表之间张量的余弦相似度。并获得具有相似性的输出列表(张量)。

例如:

a: [ 
[1, 2, 3], 
[4, 5, 6], 
[7, 8, 9] 
]   

b: [ 
[1, 2, 3], 
[7, 5, 6], 
[7, 4, 9] 
]

输出:

out: [
1.0,
0.84,
0.78
]

对于如何在 tensorflow 中执行此操作的任何帮助,我们将不胜感激。

现在我已经完成了这个:

a = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_a")
b = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_b")
normalize_a = tf.nn.l2_normalize(a, dim=1)
normalize_b = tf.nn.l2_normalize(b, dim=1)
cos_similarity=tf.matmul(normalize_a, normalize_b,transpose_b=True)

sess=tf.Session()
cos_sim=sess.run(cos_similarity,feed_dict={
  a: np.array([[1, 2, 3], 
               [4, 5, 6]]),

  b: np.array([[1, 2, 3], 
               [8, 7, 9]]),
})
print(cos_sim)

a = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_a")
b = tf.placeholder(tf.float32, shape=[None,3], name="input_placeholder_b")
numerator = tf.reduce_sum(tf.multiply(a, b), axis=1)
denominator = tf.multiply(tf.norm(a, axis=1), tf.norm(b, axis=1))
cos_similarity = numerator/denominator

sess=tf.Session()
cos_sim=sess.run(cos_similarity,feed_dict={
  a: np.array([[1, 2, 3], 
               [4, 5, 6]]),

  b: np.array([[1, 2, 3], 
               [8, 7, 9]]),
})
print(cos_sim)