繁体   English   中英

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

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

我有一个巨大的空数组(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]

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跨越 tarr 的列,它步进 24 个字节,或 3 个元素 - 从 0 到 3,从 1 到 4 等。

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

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

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

暂无
暂无

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

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