【问题标题】:How to construct square of pairwise difference for each row vector in a matrix in tensorflow?如何在张量流中为矩阵中的每个行向量构造成对差异的平方?
【发布时间】:2018-12-03 17:16:36
【问题描述】:

我在 TensorFlow 中有一个具有 K*N 维度的二维张量,

对于张量中的每个行向量,具有 N 维,我可以使用 How to construct square of pairwise difference from a vector in tensorflow? 中的方法计算成对差异的平方

但是,我需要对 K 行向量的结果进行平均:执行每个向量的两两差平方并对结果进行平均。

我该怎么办?需要你的帮助,非常感谢!!!

【问题讨论】:

  • 也许您应该在您的问题中添加numpy 标签以增加曝光率(如果适用)。

标签: python numpy tensorflow matrix


【解决方案1】:

代码及运行结果:

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))

给出这个结果:

1) a - at(计算与您发布的链接相同的内容,但行数相同)

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

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

2) output(取矩阵带部分并将除行之外的所有维度相加,即您拥有为每一行发布的代码的结果)

[ 6 26]

3) final 行间平均值

16

【讨论】:

  • 嗨吉塞佩,谢谢。我已经测试了 x 与 mu 相同的结果 [[1.,2.,3.],[2.,3.,5.],[3.,4.,5.]],这里 K== N==3,但是结果不是26,这里有什么问题吗?
  • 已编辑。看看现在是否适合你
【解决方案2】:

How to construct square of pairwise difference from a vector in tensorflow? 类似的逻辑,但需要进行一些更改来处理 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,非常感谢,但这对我来说似乎很复杂,代码可以推广到 K 维吗?
  • 是的,我测试的时间比上面显示的要长。你可以自己测试一下。尝试打印每一步的输出,你会得到它。
猜你喜欢
  • 2018-12-03
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 2019-12-03
  • 2017-11-18
  • 1970-01-01
相关资源
最近更新 更多