Sim*_*mbi 1 python cosine-similarity tensorflow
嗨,Stackoverflow 用户,
我目前正在努力解决这个问题:
我有 2 个二维张量:
a = Tensor(shape=[600,52]) # 600 vectors of length 52
b = Tensor(shape=[16000,52]) # 1600 vectors of length 52
Run Code Online (Sandbox Code Playgroud)
我正在尝试计算所有向量组合的余弦相似度并将它们存储在第三张量中。
similarity = Tensor(shape=[600, 16000])
Run Code Online (Sandbox Code Playgroud)
我现在的问题如下
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |