Numpy有反向广播吗?

7xllpg7q  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(108)
import numpy as np
x0 = np.random.randn(7, 8, 9, 10, 11)
x1 = np.random.randn(9, 1, 11)
y = x0 + x1
print(y.shape)
# (7, 8, 9, 10, 11)

如上所示,numpy中的广播允许添加不同形状的数组。我想知道是否有反向操作,即对y中的轴求和,以便输出与x1相同的形状。目前我需要使用两个add.reduce

interm = np.add.reduce(y, axis=(0, 1)) # sum all leading axes
result = np.add.reduce(interm, axis=-2, keepdims=True) # sum remaining singleton axes
print(result.shape == x1.shape)
# True

有没有一个函数可以做到这一点?

8iwquhpp

8iwquhpp1#

仍然是两个步骤,但您可以首先在所有3个轴上sum,然后reshape

out = np.sum(y, axis=(0, 1, 3)).reshape(x1.shape)
# or
# out = np.add.reduce(y, axis=(0, 1, 3)).reshape(x1.shape)

out.shape
# (9, 1, 11)

np.allclose(out, result)
# True

相关问题