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

标签 python tensorflow cosine-similarity

各位 Stackoverflow 用户,大家好,

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

我有 2 个 2d 张量:

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

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

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

关于python - 在 Tensorflow 中计算两组向量的余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946993/

相关文章:

tensorflow - 在 tensorflow 中展开功能?

text - 有人可以以非常简单的图形方式举一个余弦相似度的例子吗?

linux - fcluster 包中具有余弦相似性度量的层次聚类

algorithm - 如何优化发现相似性?

python - 在列表中查找模式

python - 在 Rackspace 云数据库实例中创建用户时的主机参数

python - 在 Heroku dyno 上运行多个进程是否可行?

python - 在 TensorFlow 中梯度下降后更新权重

python - 如何使用python删除文件夹内的所有文件夹?

python - 我的 tensorflow 网络不准确