在 Tensorflow 中计算两组向量的余弦相似度

Computing the Cosine Similarity of two sets of vectors in Tensorflow

大家好 Whosebug 用户,

我目前正在努力解决这个问题:

我有 2 个二维张量:

a = Tensor(shape=[600,52]) # 600 vectors of length 52
b = Tensor(shape=[16000,52]) # 1600 vectors of length 52

我正在尝试计算所有向量组合的余弦相似度并将它们存储在第 3 个张量中。

similarity = Tensor(shape=[600, 16000])

我现在的问题如下

a) 我不太确定如何以非迭代方式实现它,我考虑过将广播语义与 tf.losses.cosine_distance 结合使用,但我无法完全理解是什么这实际上看起来像。

b) 取决于实现(如果使用 tf.losses.cosine_distance,这需要两个输入张量的匹配尺寸)内存占用可能会变得非常大,因为它需要创建两个形状为 [600 的张量, 1600, 52] 来计算所有向量组合的距离。您能想到解决这个问题的任何可能性吗?

我希望我能够以一种可以理解的方式表达我的想法,谢谢你的帮助

最佳,

你可以像这样简单地计算:

import tensorflow as tf

# Vectors
a = tf.placeholder(tf.float32, shape=[600, 52])
b = tf.placeholder(tf.float32, shape=[16000, 52])
# Cosine similarity
similarity = tf.reduce_sum(a[:, tf.newaxis] * b, axis=-1)
# Only necessary if vectors are not normalized
similarity /= tf.norm(a[:, tf.newaxis], axis=-1) * tf.norm(b, axis=-1)
# If you prefer the distance measure
distance = 1 - similarity