1

I have a 2D tensor having K*N dimension in TensorFlow,

For each row vector in the tensor, having N dimension, I can calculate the square of pairwise difference using the approach in How to construct square of pairwise difference from a vector in tensorflow?

However, I need to average the results of the K row vectors: performing each vector's square of pairwise difference and averaging the results.

How can I do? Need your help, many thanks!!!

clement116
  • 317
  • 2
  • 11
  • Perhaps you should add the [tag:numpy] tag to your question for increased exposure (if it applies). – Dev-iL Jun 25 '18 at 07:44

2 Answers2

0

The code and then the run results:

a = tf.constant([[1,2,3],[2,5,6]])
a = tf.expand_dims(a,1)
at = tf.transpose(a, [0,2,1])
pair_diff = tf.matrix_band_part( a - at, 0, -1)
output = tf.reduce_sum(tf.square(pair_diff), axis=[1,2])
final = tf.reduce_mean(output)

with tf.Session() as sess:
    print(sess.run(a - at))
    print(sess.run(output))
    print(sess.run(final))

Give this results:

1) a - at (computes the same thing of the link you posted but rowise)

 [[[ 0  1  2]
   [-1  0  1]
   [-2 -1  0]]

 [[ 0  3  4]
  [-3  0  1]
  [-4 -1  0]]]

2) output (take the matrix band part and sum all dimensions apart from rows, i.e. you have the result of the code you posted for each row)

[ 6 26]

3) final Average among rows

16
Giuseppe Marra
  • 1,094
  • 7
  • 16
0

Similar logic to How to construct square of pairwise difference from a vector in tensorflow? but some changes required to handle 2d:

a = tf.constant([[1,2,3], [4, 6, 8]])
pair_diff = tf.transpose(a[...,None, None,] - tf.transpose(a[...,None,None,]), [0,3,1,2])

reshape_diff = tf.reshape(tf.matrix_band_part(pair_diff, 0, -1), [-1, tf.shape(a)[1]*tf.shape(a)[1]])
output = tf.reduce_sum(tf.square(reshape_diff),1)[::tf.shape(a)[0]+1]

with tf.Session() as sess:
   print(sess.run(output))
#[ 6 24]
Vijay Mariappan
  • 16,921
  • 3
  • 40
  • 59