gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:05:39 30 4
gpt4 key购买 nike

各位 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com