cle*_*116 3 python vectorization tensorflow tensor pairwise
我在 TensorFlow 中有一个 N 维的一维向量,
如何构造成对平方差的总和?
输入向量
[1,2,3]
输出
6
计算为
(1-2)^2+(1-3)^2+(2-3)^2.
Run Code Online (Sandbox Code Playgroud)
如果我将输入作为 N-dim 向量 l,则输出应为 sigma_{i,j}((l_i-l_j)^2)。
添加的问题:如果我有一个 2d 矩阵并且想对矩阵的每一行执行相同的过程,然后对所有行的结果求平均值,我该怎么做?非常感谢!
对于成对差异,减去input和 的转置input并仅取上三角部分,例如:
pair_diff = tf.matrix_band_part(a[...,None] -
tf.transpose(a[...,None]), 0, -1)
Run Code Online (Sandbox Code Playgroud)
然后,您可以对差异进行平方和求和。
代码:
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
Run Code Online (Sandbox Code Playgroud)