我有两个收藏。一个由米1个在点ķ尺寸和中的另一个米2在点ķ尺寸。我需要计算两个集合中每对之间的成对距离。
基本上有两个矩阵A m 1 , k和B m 2 , k我需要得到一个矩阵C m 1 , m 2。
我可以通过使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4095 次 |
| 最近记录: |