代码之家  ›  专栏  ›  技术社区  ›  nairouz mrabah

通过在Tensorflow中将固定数量的行相加来减少矩阵

  •  1
  • nairouz mrabah  · 技术社区  · 7 年前

    我有一个多行的巨大矩阵。实际上,我想将每3行相加,形成一个新的矩阵。

    为了更好地理解问题,下面是一个示例,说明了所需的输出:

    input  = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
    output = [[9, 12], [27, 30]]
    

    我想使用tensorflow内置操作来保持图的可微性。

    1 回复  |  直到 7 年前
        1
  •  2
  •   benjaminplanche    7 年前

    你可以重塑你的张量,以便在一个新的维度上隔离三胞胎,然后 tf.reduce_sum 在该维度上:

    import tensorflow as tf
    
    x = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
    shape_x = tf.shape(x)
    
    # Reshaping the tensor to have triplets on dimension #1:
    new_shape_for_reduce = tf.stack([shape_x[0] // 3, 3, shape_x[1]])
    reshaped_x = tf.reshape(x, new_shape_for_reduce)
    # Sum-reducing over dimension #1:
    sum_3_rows = tf.reduce_sum(reshaped_x, axis=1)
    
    with tf.Session() as sess:
        res = sess.run(sum_3_rows)
        print(res)
        # [[9  12]
        #  [27 30]]