如何计算一个矩阵中向量之间的欧式距离?

时间:2018-11-20 01:26:27

标签: python tensorflow

我想计算特征中向量的欧几里得距离,这是从网络获得的tf.Tensor。

我以以下方式尝试过,但失败并显示错误:

'Tensor' object is not iterable

所以我想仅通过矩阵来计算一个矩阵中行之间的距离,而不必每行都进行迭代。

features, _ = mnist_net(images)
feature_matrix = np.zeros(shape=(FLAGS.batch_size,FLAGS.batch_size))
for i in range (FLAGS.batch_size):
   for j in range (FLAGS.batch_size):
      aa = tf.slice(features,[i,0],[1,50])
      bb = tf.slice(features,[j,0],[1,50])
      feature_matrix[i,j] = tf.sqrt(sum((aa-bb)**2))  

1 个答案:

答案 0 :(得分:2)

您可以简单地通过tf.norm / tf.linalg.norm来实现:

feature_matrix = tf.linalg.norm(features[:, tf.newaxis] - features, axis=-1)

例如:

import tensorflow as tf

with tf.Session() as sess:
    features = tf.placeholder(tf.float32, [None, None])
    feature_matrix = tf.linalg.norm(features[:, tf.newaxis] - features, axis=-1)
    print(sess.run(feature_matrix, feed_dict={features: [[ 1,  2,  3],
                                                         [ 4,  5,  6],
                                                         [ 7,  8,  9],
                                                         [10, 11, 12]]}))

输出:

[[ 0.        5.196152 10.392304 15.588457]
 [ 5.196152  0.        5.196152 10.392304]
 [10.392304  5.196152  0.        5.196152]
 [15.588457 10.392304  5.196152  0.      ]]

编辑:

如果您不能使用tf.norm,则以下是等效的实现:

sqdiff = tf.squared_difference(features[:, tf.newaxis], features)
feature_matrix = tf.sqrt(tf.reduce_sum(sqdiff, axis=-1))