首页 > 解决方案 > 如何计算一个矩阵中向量之间的欧式距离?

问题描述

我想计算特征中向量的欧几里得距离,这是从网络得到的一个 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))  

标签: pythontensorflow

解决方案


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))

推荐阅读