计算2张量所有元素之间的距离

时间:2019-03-15 09:37:26

标签: python tensorflow

我想计算tensor1和tensor2的所有元素之间的距离。张量1和张量2具有各种大小。有没有现成的方法,最有效的方法是什么?

tensor1   tensor2
[1 2 3]   [11 12]
[4 5 6]   [13 14]
[7 8 9]   [15 16]

我想找到tensor1 [0,0]与tensor2的所有元素之间的距离,并且对所有索引而言都相同。

2 个答案:

答案 0 :(得分:1)

我认为这可以满足您的要求

import tensorflow as tf

def all_distances(a, b):
    dists = tf.expand_dims(tf.reshape(a, [-1]), 1) - tf.reshape(b, [-1])
    return tf.reshape(dists, tf.concat([tf.shape(a), tf.shape(b)], axis=0))

with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    b = tf.constant([[11, 12], [13, 14], [15, 16]])
    dists = all_distances(a, b)
    print(sess.run(dists))

输出:

[[[[-10 -11]
   [-12 -13]
   [-14 -15]]

  [[ -9 -10]
   [-11 -12]
   [-13 -14]]

  [[ -8  -9]
   [-10 -11]
   [-12 -13]]]


 [[[ -7  -8]
   [ -9 -10]
   [-11 -12]]

  [[ -6  -7]
   [ -8  -9]
   [-10 -11]]

  [[ -5  -6]
   [ -7  -8]
   [ -9 -10]]]


 [[[ -4  -5]
   [ -6  -7]
   [ -8  -9]]

  [[ -3  -4]
   [ -5  -6]
   [ -7  -8]]

  [[ -2  -3]
   [ -4  -5]
   [ -6  -7]]]]

结果是一个张量,dists[i1, .., in, j1, .., jm]a[i1, .., in] - b[j1, .., jm],其中nma和{{1}的维数}。

答案 1 :(得分:0)

您也可以使用tf.meshgrid来实现。

import tensorflow as tf
import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([[11,12],[13,14],[15,16]])

a_tf = tf.placeholder(shape=(None,None),dtype=tf.float32)
b_tf = tf.placeholder(shape=(None,None),dtype=tf.float32)

A,B = tf.meshgrid(a_tf,b_tf)
result = tf.transpose(A-B) # two dimension
result = tf.reshape(result,shape=(-1,tf.shape(b_tf)[0],tf.shape(b_tf)[1]))  # three dimension

with tf.Session() as sess:
    print(sess.run(result, feed_dict={a_tf: a, b_tf: b}))

[[[-10. -11.]
  [-12. -13.]
  [-14. -15.]]

 [[ -9. -10.]
  [-11. -12.]
  [-13. -14.]]

 [[ -8.  -9.]
  [-10. -11.]
  [-12. -13.]]

 [[ -7.  -8.]
  [ -9. -10.]
  [-11. -12.]]

 [[ -6.  -7.]
  [ -8.  -9.]
  [-10. -11.]]

 [[ -5.  -6.]
  [ -7.  -8.]
  [ -9. -10.]]

 [[ -4.  -5.]
  [ -6.  -7.]
  [ -8.  -9.]]

 [[ -3.  -4.]
  [ -5.  -6.]
  [ -7.  -8.]]

 [[ -2.  -3.]
  [ -4.  -5.]
  [ -6.  -7.]]]