【问题标题】:How to use numpy.reshape for swapping axes of an array如何使用 numpy.reshape 交换数组的轴
【发布时间】:2021-03-10 04:47:29
【问题描述】:

我有一个巨大的空数组 (300000,80,80),我想使用 numpy.reshape 交换它的轴。我试过numpy.rollaxisnumpy.swapaxesnumpy.transpose。他们的工作就像一个魅力,但他们放慢了前面花哨的索引。

我也尝试过 C 或 F 顺序来创建空数组,但没有任何改变。

所以,我怎样才能使用numpy.reshape 来改变这样的轴顺序

(300000,80,80) -> (80,80,300000) 不使用numpy.rollaxis 等。

我们将不胜感激。

这是我的代码:

patch = np.ones([3,80,80])
image = np.empty([300000,80,80], dtype='uint8', order='C')

for i in range(0,300000,3):
  image[i:i+3] = patch

# if i use np.rollaxis, next fancy indexing execute too slow.
pt = ([...], [...]) #some tuple
ij = ([...], [...]) #some tuple

transformed[pt] = image[ij]

【问题讨论】:

    标签: python arrays numpy optimization reshape


    【解决方案1】:

    reshape 不能和transpose/swapaxes 一样工作。

    我会尝试说明。

    In [1]: arr = np.arange(6).reshape(2,3)
    In [2]: arr
    Out[2]: 
    array([[0, 1, 2],
           [3, 4, 5]])
    

    arr实际上是源arangeview,共享数据缓冲区中元素的顺序为:

    In [3]: arr.ravel()
    Out[3]: array([0, 1, 2, 3, 4, 5])
    

    transpose 也是 view,但有不同的 shapestridesorder

    In [4]: tarr = np.transpose(arr)
    In [5]: tarr
    Out[5]: 
    array([[0, 3],
           [1, 4],
           [2, 5]])
    In [6]: tarr.ravel()
    Out[6]: array([0, 3, 1, 4, 2, 5])      # order C
    In [7]: tarr.ravel(order='F')
    Out[7]: array([0, 1, 2, 3, 4, 5])
    In [8]: arr.strides
    Out[8]: (24, 8)
    In [9]: tarr.strides
    Out[9]: (8, 24)
    

    要遍历 tarr 的列,它会步进 24 个字节或 3 个元素 - 从 0 到 3,从 1 到 4 等等。

    因为它是view,所以transpose 很快。但是后续的操作往往需要一个副本,对于大数组来说会慢很多。

    如果我们尝试只是重塑,我们会得到:

    In [10]: np.reshape(arr,(3,2))
    Out[10]: 
    array([[0, 1],
           [2, 3],
           [4, 5]])
    In [11]: np.reshape(arr,(3,2)).ravel()
    Out[11]: array([0, 1, 2, 3, 4, 5])
    In [12]: np.reshape(arr,(3,2)).strides
    Out[12]: (16, 8)
    

    形状与tarr 匹配,但strides 不匹配。 [0,1,2] 行已被拆分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 2019-06-29
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多