首页 > 解决方案 > 在 Numpy 中拆分多维数组

问题描述

我正在尝试拆分多维数组(array

import numpy as np

shape = (3, 4, 4, 2)
array = np.random.randint(0,10,shape)

放入一个数组 ( new_array),(3,2,2,2,2,2)其中维度 1 已拆分为 2(维度 1 和 2),维度 2 inarray已拆分为 2(维度 3 和 4)。

到目前为止,我得到了一种工作方法:

div_x = 2
div_y = 2
new_dim_x = shape[1]//div_x
new_dim_y = shape[2]//div_y

new_array_split = np.array([np.split(each_sub, axis=2, indices_or_sections=div_y) for each_sub in np.split(array[:, :(new_dim_x*div_x), :(new_dim_y*div_y)], axis=1, indices_or_sections=div_x)]) 

我也在考虑使用reshape

new_array_reshape = array[:, :(div_x*new_dim_x), :(div_y*new_dim_y), ...].reshape(shape[0], div_x, div_y, new_dim_x, new_dim_y, shape[-1]).transpose(1,2,0,3,4,5)

reshape方法比该split方法更快:

%timeit array[:, :(div_x*new_dim_x), :(div_y*new_dim_y), ...].reshape(shape[0], div_x, div_y, new_dim_x, new_dim_y, shape[-1]).transpose(1,2,0,3,4,5)
2.16 µs ± 44.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.array([np.split(each_sub, axis=2, indices_or_sections=div_y) for each_sub in np.split(array[:, :(new_dim_x*div_x), :(new_dim_y*div_y)], axis=1, indices_or_sections=div_x)])
58.3 µs ± 2.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

但是,由于最后一个维度,我无法得到相同的结果:

print('Reshape method')
print(new_array_reshape[1,0,0,...])
print('\nSplit method')
print(new_array_split[1,0,0,...])
 
Reshape method
[[[2 2]
  [4 3]]
 [[3 5]
  [5 9]]]

Split method
[[[2 2]
  [4 3]]
 [[5 3]
  [9 8]]]

split 方法完全符合我的要求,我确实逐个检查了数字,它执行了我想要的拆分类型,但没有达到我想要的速度。

问题

有没有办法使用 reshape 或任何其他方法来实现与 split 方法相同的结果?

语境

该数组实际上是来自图像处理的数据流,其中的第一维array是时间,第二维是坐标x(4),第三维是坐标y(4),第四维(2)是幅度和相位的流量。

我想将图像(坐标 x 和 y)拆分为子图像,制作 2x2 的图片数组,以便我可以更本地地分析流,执行平均,聚类等。

这个过程(拆分)将被执行很多次,这就是为什么我正在寻找一个最佳和有效的解决方案。我相信这种方式可能是使用reshape,但我对任何其他选择持开放态度。

标签: pythonarraysnumpymultidimensional-arraysplit

解决方案


Reshape and permute axes-

array.reshape(3,2,2,2,2,2).transpose(1,3,0,2,4,5)

推荐阅读