将 4D numpy 数组重塑为 3D
Reshape 4D numpy array into 3D
我有一个 numpy 数组,尺寸如下 - (256, 128, 4, 200) - 基本上前两个可以组成图像,第三个是通道,第四个是帧 ("time instances") .如何重塑数组,使帧一个接一个 "stacked",换句话说,数组的形状为 (256, 128*200, 4)?串联是按帧进行的,这一点很重要,因此可以保留帧中值的顺序。
本质上,需要优化的是:
data_new = data[:, :, :, 0]
for i in range(1, data.shape[3]):
data_new = np.concatenate((data_new, data[:, :, :, i]), axis=1)
用 np.transpose
置换轴并重塑 -
m,n = data.shape[::2]
data_new = data.transpose(0,3,1,2).reshape(m,-1,n)
或roll-axis
并重塑-
data_new = np.rollaxis(data,3,1).reshape(m,-1,n)
运行时测试 -
In [40]: data = np.random.randint(0,9,(256,128,4,200))
In [46]: %%timeit
...: data_new = data[:, :, :, 0]
...: for i in range(1, data.shape[3]):
...: data_new = np.concatenate((data_new, data[:, :, :, i]), axis=1)
...:
1 loop, best of 3: 3.56 s per loop
In [49]: m,n = data.shape[::2]
In [50]: %timeit data.transpose(0,3,1,2).reshape(m,-1,n)
10 loops, best of 3: 47.1 ms per loop
In [51]: %timeit np.rollaxis(data,3,1).reshape(m,-1,n)
10 loops, best of 3: 46.8 ms per loop
因此,76x+
加速是向量化的利润。
我有一个 numpy 数组,尺寸如下 - (256, 128, 4, 200) - 基本上前两个可以组成图像,第三个是通道,第四个是帧 ("time instances") .如何重塑数组,使帧一个接一个 "stacked",换句话说,数组的形状为 (256, 128*200, 4)?串联是按帧进行的,这一点很重要,因此可以保留帧中值的顺序。
本质上,需要优化的是:
data_new = data[:, :, :, 0]
for i in range(1, data.shape[3]):
data_new = np.concatenate((data_new, data[:, :, :, i]), axis=1)
用 np.transpose
置换轴并重塑 -
m,n = data.shape[::2]
data_new = data.transpose(0,3,1,2).reshape(m,-1,n)
或roll-axis
并重塑-
data_new = np.rollaxis(data,3,1).reshape(m,-1,n)
运行时测试 -
In [40]: data = np.random.randint(0,9,(256,128,4,200))
In [46]: %%timeit
...: data_new = data[:, :, :, 0]
...: for i in range(1, data.shape[3]):
...: data_new = np.concatenate((data_new, data[:, :, :, i]), axis=1)
...:
1 loop, best of 3: 3.56 s per loop
In [49]: m,n = data.shape[::2]
In [50]: %timeit data.transpose(0,3,1,2).reshape(m,-1,n)
10 loops, best of 3: 47.1 ms per loop
In [51]: %timeit np.rollaxis(data,3,1).reshape(m,-1,n)
10 loops, best of 3: 46.8 ms per loop
因此,76x+
加速是向量化的利润。