我有一个形状(1, 4, 3)
的张量,我想对每两行连续行的列求和以将形状减少到(1, 2, 3)
。
例:
# Input
1 2 3
3 4 5
6 7 8
9 10 11
# Output
4 6 8
15 17 19
您可以将
tf.reshape
与tf.reduce_sum
一起使用,以便将每个连续的行放置在新维度中,然后对其进行求和:
x = tf.placeholder(shape=[1, 4, 3], dtype=tf.float32)
y = tf.reduce_sum(
tf.reshape(x, (1, 2, 2, 3)),
axis=2
)
你必须正确地重塑它,并总结新创建的轴:
import tensorflow as tf
tf.enable_eager_execution()
# Input
A = [[1, 2, 3],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]]
A = tf.reshape(A, [4//2, 2, 3])
A = tf.reduce_sum(A, axis=1)
A = tf.reshape(A, [4//2, 3])
print(A.numpy())
# output:
# [[ 4 6 8]
# [15 17 19]]
import tensorflow as tf
t = tf.constant([[[1, 1, 1], [2, 2, 2],[3, 3, 3], [4, 4, 4],[5, 5, 5], [6, 6, 6],[7, 7, 7], [8, 8, 8]],
[[3, 3, 3], [4, 4, 4],[3, 3, 3], [4, 4, 4],[3, 3, 3], [4, 4, 4],[3, 3, 3], [4, 5, 4]]])
print(t.shape)
nt = tf.concat([tf.concat([tf.reduce_sum(tf.slice(t, [j, i, 0], [1, 2, 3]),axis=1) for i in list(range(0,8,2))],axis=0) for j in range(2)],axis=0)
sess = tf.Session()
sess.run(nt)
(2, 8, 3)
array([[ 3, 3, 3],
[ 7, 7, 7],
[11, 11, 11],
[15, 15, 15],
[ 7, 7, 7],
[ 7, 7, 7],
[ 7, 7, 7],
[ 7, 8, 7]], dtype=int32)