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
有没有一个函数可以做到这一点?
1条答案
按热度按时间8iwquhpp1#
仍然是两个步骤,但您可以首先在所有3个轴上
sum
,然后reshape
: