如何从张量流中的向量构造成对差异的平方? [英] How to construct square of pairwise difference from a vector in tensorflow?

查看:30
本文介绍了如何从张量流中的向量构造成对差异的平方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 TensorFlow 中有一个 N 维的一维向量,

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

如何构造成对平方差之和?

how to construct sum of a pairwise squared difference?

输入向量
[1,2,3]
输出6
计算为

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

如果我输入一个 N-dim 向量 l,输出应该是 sigma_{i,j}((l_i-l_j)^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!

推荐答案

对于成对差异,减去 inputinput 的转置,只取上三角形部分,如:

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.

代码:

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

这篇关于如何从张量流中的向量构造成对差异的平方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆