简体   繁体   中英

how to calculate the euclidean distance between the vectors in one matrix?

I want to calculate the Euclidean distance of the vectors in the features, which is a tf.Tensor got from the network.

I tried it in the following way, but failed with error:

'Tensor' object is not iterable

So I want to calculate the distance between the rows in one matrix just through matrix,without iteration of every rows.

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

You can achieve that simply with tf.norm / tf.linalg.norm :

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

For example:

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

Output:

[[ 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.      ]]

EDIT:

If you cannot use tf.norm , the following is an equivalent implementation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM