我有一个(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
答案 0 :(得分:0)
您可以将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
)
答案 1 :(得分:0)
您必须适当地重塑形状,并在新创建的轴上进行总结:
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]]
答案 2 :(得分:0)
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)