Skip to main content
 首页 » 编程设计

python之计算 TensorFlow 中每对两个输入集合之间的成对距离

2024年08月20日41findumars

我有两个收藏。一个包含m1 个k 维度的点,另一个包含m2 个维度k 个维度的点。我需要计算两个集合中每一对之间的成对距离。

基本上有两个矩阵 Am1, k 和 Bm2 , k 我需要得到一个矩阵 Cm1, m2 .

我可以通过使用 distance.sdist 在 scipy 中轻松地做到这一点并选择许多距离度量中的一个,我也可以在 TF 中循环执行此操作,但即使对于欧几里得距离,我也无法弄清楚如何使用矩阵操作来执行此操作。

请您参考如下方法:

几个小时后,我终于找到了如何在 Tensorflow 中执行此操作。我的解决方案仅适用于欧几里得距离并且非常冗长。我也没有数学证明(只是手忙脚乱,希望更严谨):

import tensorflow as tf 
import numpy as np 
from scipy.spatial.distance import cdist 
 
M1, M2, K = 3, 4, 2 
 
# Scipy calculation 
a = np.random.rand(M1, K).astype(np.float32) 
b = np.random.rand(M2, K).astype(np.float32) 
print cdist(a, b, 'euclidean'), '\n' 
 
# TF calculation 
A = tf.Variable(a) 
B = tf.Variable(b) 
 
p1 = tf.matmul( 
    tf.expand_dims(tf.reduce_sum(tf.square(A), 1), 1), 
    tf.ones(shape=(1, M2)) 
) 
p2 = tf.transpose(tf.matmul( 
    tf.reshape(tf.reduce_sum(tf.square(B), 1), shape=[-1, 1]), 
    tf.ones(shape=(M1, 1)), 
    transpose_b=True 
)) 
 
res = tf.sqrt(tf.add(p1, p2) - 2 * tf.matmul(A, B, transpose_b=True)) 
 
with tf.Session() as sess: 
    sess.run(tf.global_variables_initializer()) 
    print sess.run(res)