如何从张量流中的向量构造成对差平方?

时间:2018-06-25 02:24:16

标签: python tensorflow vectorization tensor pairwise

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

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

示例

输入向量
expect: does"\r\n\u001b[r\u001b[m\u001b[2J\u001b[H\u001b[?7h\u001b[?1;4;6l \u001b[?1049h\u001b[4l\u001b[?1h\u001b=\u001b[0m\u001b(B\u001b[1;70r\u001b[H \u001b[2J\u001b[H\u001b[2J"(spawn_id exp5) match glob pattern "poplar login"? no "root@poplar"? no " send "\r" ; exp_continue "? no expect: timed out login success! send: sending "reboot\r" to { exp5 }
输出 [1,2,3]
计算为

6

如果我将输入作为N维矢量l,则输出应为sigma_ {i,j}((l_i-l_j)^ 2)。

添加的问题:如果我有一个二维矩阵,并且希望对矩阵的每一行执行相同的过程,然后对所有行的结果求平均值,该怎么办?非常感谢!

2 个答案:

答案 0 :(得分:2)

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

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

然后您可以平方和求和。

代码:

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

答案 1 :(得分:0)

使用tf.subtract吗?然后是np.sum。莱姆知道这对你有什么作用。

相关问题