Numpy是否有反向广播?

huangapple go评论56阅读模式
英文:

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
英文:

Still two steps, but you can first sum on all 3 axes, then 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

huangapple
  • 本文由 发表于 2023年4月13日 15:56:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定