【问题标题】:Numpy reduce array to a given shapeNumpy将数组减少到给定的形状
【发布时间】: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


    【解决方案1】:

    目前尚不清楚这是“非广播”。

    进行计算的直接方法是使用sum 的axis 参数:

    In [124]: np.array([1,2,3,4,5]).sum()
    Out[124]: 15
    In [125]: np.array([[1,2],[1,2]]).sum(axis=0)
    Out[125]: array([2, 4])
    In [126]: np.array([[1,2],[1,2]]).sum(axis=(0,1))
    Out[126]: 6
    In [128]: np.array([[[1,2], [1,2]], [[1,2], [1,2]]]).sum(axis=0)
    Out[128]: 
    array([[2, 4],
           [2, 4]])
    

    我不经常使用reduce,但看起来axis也一样:

    In [130]: np.add.reduce(np.array([1,2,3,4,5]))
    Out[130]: 15
    In [132]: np.add.reduce(np.array([[[1,2], [1,2]], [[1,2], [1,2]]]),axis=0)
    Out[132]: 
    array([[2, 4],
           [2, 4]])
    

    但我还没有弄清楚从您的reduced_shape 到必要的axis 值的逻辑。对于像 (2,) 和 (2,2,2) 这样的形状,当您说将形状缩小到 (2,2) 时可能会产生歧义。如果您使用像 np.arange(24).reshape(2,3,4) 这样的示例数组,可能会更清楚

    【讨论】:

      猜你喜欢
      • 2016-02-14
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      相关资源
      最近更新 更多