简体   繁体   English

如何使用 numpy.reshape 交换数组的轴

[英]How to use numpy.reshape for swapping axes of an array

I have a huge empty array (300000,80,80) that I want to swap its axes using numpy.reshape .我有一个巨大的空数组(300000,80,80),我想使用numpy.reshape交换它的轴。 I've tried numpy.rollaxis , numpy.swapaxes and numpy.transpose .我试过numpy.rollaxisnumpy.swapaxesnumpy.transpose they worked like a charm but they slowed down fancy indexing up ahead.他们的工作就像一个魅力,但他们放慢了前面的花哨索引。

also I've tried C or F order in creating empty array but nothing changed.我也尝试过 C 或 F 命令来创建空数组,但没有任何改变。

so, how can I use numpy.reshape in order to change axis order like this :那么,我如何使用numpy.reshape来改变轴顺序,如下所示

(300000,80,80) -> (80,80,300000) without using numpy.rollaxis or etc. (300000,80,80) -> (80,80,300000) 不使用numpy.rollaxis等。

every idea would be appreciated.每一个想法都将不胜感激。

here is my code:这是我的代码:

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]

reshape cannot work the same as transpose/swapaxes . reshape不能与transpose/swapaxes一样工作。

I'll try to illustrate.我会尽力说明。

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

arr is actually a view of the source arange , and order of elements in the shared databuffer is: arr实际上是源arangeview ,共享数据缓冲区中元素的顺序是:

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

transpose also a view , but with different shape , strides and order 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)

To go across the columns of tarr it steps 24 bytes, or 3 elements - from 0 to 3, from 1 to 4 etc.tarr跨越 tarr 的列,它步进 24 个字节,或 3 个元素 - 从 0 到 3,从 1 到 4 等。

Because it is a view the transpose is fast.因为它是一个view ,所以transpose速度很快。 But subsequent operations often require a copy, which for large arrays is much slower.但是后续操作往往需要一个副本,对于大的 arrays 来说要慢得多。

If we try to just reshape, we get:如果我们尝试仅仅重塑,我们会得到:

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)

The shape matches tarr , but the strides don't.形状匹配tarr ,但strides不匹配。 The [0,1,2] line has been split. [0,1,2]行已被拆分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM