【发布时间】:2021-03-02 18:58:23
【问题描述】:
我正在尝试编写一个函数,将 numpy ndarray 缩减为给定的形状,从而有效地“取消广播”该数组。例如,使用 add 作为通用函数,我想要以下结果:
- A = [1, 2, 3, 4, 5],reduce_shape = (1,) -> [1+2+3+4+5] = [15](轴上的总和=0)
- A = [[1,2], [1,2]], reduce_shape = (2,) -> [1+1, 2+2] = [2, 4](轴总和=0)
- A = [[1,2], [1,2]],reduce_shape = (1,) -> [1+2+1+2] = [6](轴上的总和=(0,1) )
- A = [[[1,2], [1,2]], [[1,2], [1,2]]], reduce_shape = (2,2) -> [[1+1, 2+2], [1+1, 2+2]] = [[2,4], [2,4]](轴总和=0)
这是我想出的解决方案:
def unbroadcast(A, reduced_shape):
fill = reduced_shape[-1] if reduced_shape else None
reduced_axes = tuple(i for i, (a,b) in enumerate(itertools.zip_longest(A, shape, fillvalue=fill)) if a!=b)
return np.add.reduce(A, axis=reduced_axes).reshape(shape)
但是感觉不必要的复杂,有没有办法依靠 Numpy 的公共 API 来实现?
【问题讨论】:
标签: python-3.x numpy numpy-ndarray reduction