英文:
Numpy is there a reverse broadcast?
问题
interm = np.add.reduce(y, axis=(0, 1))
result = np.add.reduce(interm, axis=-2, keepdims=True)
print(result.shape == x1.shape)
# True
英文:
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)
as shown above, broadcasting in numpy allows addition of arrays with different shapes. I'd like to know if there is a reverse operation, that sum axes in y
so that the output is the same shape with x1
. Currently I need to use two 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
Is there a single function that does that?
答案1
得分: 0
仍然是两个步骤,但您可以首先对所有3个轴进行 sum
,然后进行 reshape
:
out = np.sum(y, axis=(0, 1, 3)).reshape(x1.shape)
# 或者
# out = np.add.reduce(y, axis=(0, 1, 3)).reshape(x1.shape)
out.shape
# (9, 1, 11)
np.allclose(out, result)
# True
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论