How to construct square of pairwise difference fro

2019-08-10 01:54发布

I have a 1D vector having N dimension in TensorFlow,

how to construct sum of a pairwise squared difference?

Example

Input Vector
[1,2,3]
Output 6
Computed As

(1-2)^2+(1-3)^2+(2-3)^2.

if I have input as an N-dim vector l, the output should be sigma_{i,j}((l_i-l_j)^2).

Added question: if I have a 2d matrix and want to perform the same process for each row of the matrix, and then average the results from all the rows, how can I do it? Many thanks!

2条回答
对你真心纯属浪费
2楼-- · 2019-08-10 02:15

For pair-wise difference, subtract the input and the transpose of input and take only the upper triangular part, like:

pair_diff = tf.matrix_band_part(a[...,None] - 
                      tf.transpose(a[...,None]), 0, -1)

Then you can square and sum the differences.

Code:

a = tf.constant([1,2,3])
pair_diff = tf.matrix_band_part(a[...,None] - 
                      tf.transpose(a[...,None]), 0, -1)
output = tf.reduce_sum(tf.square(pair_diff))

with tf.Session() as sess:
  print(sess.run(output))
  # 6
查看更多
smile是对你的礼貌
3楼-- · 2019-08-10 02:20

use tf.subtract ? Then np.sum. Lemme know how that works out for ye.

查看更多
登录 后发表回答