首页 文章

如何在张量流中的矩阵中构造每个行向量的成对差的平方?

提问于
浏览
1

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

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

但是,我需要平均K行向量的结果:执行每个向量的成对差的平方并对结果求平均值 .

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

2 回答

  • 0

    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]
    
  • 0

    代码然后运行结果:

    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
    

相关问题