我有一个包含多行的巨大矩阵。实际上,我想将每3行添加到一起以形成新的矩阵。
为了更好地理解这个问题,下面是一个说明所需输出的例子:
input = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
output = [[9, 12], [27, 30]]
我想使用tensorflow内置操作来保持图表的可微性。
答案 0 :(得分:2)
你可以重塑你的张量,以便在一个新的维度中隔离三元组,然后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]]