如何使用numpy.reforme交换阵列的轴

2024-09-27 02:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的空数组(300000,80,80),我想使用numpy.reshape交换它的轴。我试过numpy.rollaxisnumpy.swapaxesnumpy.transpose。他们工作得很有魅力,但他们放慢了前进的步伐

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

那么,我如何使用numpy.reshape来改变轴的顺序呢

(300000,80,80)——>;(80,80300000)而不使用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]

Tags: imagenumpypt顺序npsome数组patch
1条回答
网友
1楼 · 发布于 2024-09-27 02:21:51

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等等

因为它是一个viewtranspose很快。但后续操作通常需要一个拷贝,这对于大型阵列来说要慢得多

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

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]行已被拆分

相关问题 更多 >

    热门问题