[英]Create 3D array from elements of a 2D array
I'm working on a code and a question just pop up in my head.我正在编写代码,一个问题突然出现在我的脑海中。 So basically I have a 2D numpy array with shape L,W = (4, 4)
(this is just an example, the array, can be much bigger).所以基本上我有一个 2D numpy 数组,形状为L,W = (4, 4)
(这只是一个例子,数组可以更大)。
What I need is to create 3D array with elements from the 2D numpy array, where the elements in each cell of the output are: array[i:i+l, j:j+w]
(the elements of the subarray of dimension (l,w) starting from i, j position): output[i,j,:] = array[i:i+l,j:j+w].reshape(l*w,)
我需要的是使用二维 numpy 数组中的元素创建 3D 数组,其中 output 的每个单元格中的元素是: array[i:i+l, j:j+w]
(维度子数组的元素 ( l,w) 从 i,j 位置开始): output[i,j,:] = array[i:i+l,j:j+w].reshape(l*w,)
I thought about non-vectorized solution:我想到了非矢量化解决方案:
import numpy as np
L = 4
W = 4
array = np.arange(16).reshape(L,W)
l= 2
w = 2
subarrays_elements = []
for i in range(L-(l-1)):
for j in range(W-(w-1)):
subarrays_elements.append(array[i:i+l,j:j+w].reshape(l*w,))
output = np.array(subarrays_elements).reshape(L-(l-1),W-(w-1),l*w)
the shape of the output is W-(w-1),L-(l-1),l*w
,because we can't get a (l, w) subarray for the last l-1
rows and for w-1
columns. output 的形状是W-(w-1),L-(l-1),l*w
,因为我们无法得到最后l-1
行和w-1
的 (l, w) 子数组w-1
列。
The expected output would be array with (3,3,4):预期的 output 将是包含 (3,3,4) 的数组:
expected_output = np.array([[[0 1 4 5],
[1 2 5 6],
[2 3 6 7]],
[[4 5 8 9],
[5 6 9 10],
[6 7 10 11]],
[[8 9 12 13],
[9 10 13 14],
[10 11 14 15]]])
I need solutions using only numpy and with vectorization, because I have a huge array, so any help will be appreciated, thank you!我需要仅使用 numpy 和矢量化的解决方案,因为我有一个巨大的数组,所以任何帮助将不胜感激,谢谢!
This kind of problem is quite similar to getting the input for a convolutional layer in a neural.network, so you can use the same tool, which is numpy.lib.stride_tricks.sliding_window_view .这种问题与在 neural.network 中获取卷积层的输入非常相似,因此您可以使用相同的工具,即numpy.lib.stride_tricks.sliding_window_view 。
Here's an example:这是一个例子:
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
L = 4
W = 4
array = np.arange(L * W).reshape(L,W)
l = 2
w = 2
new_length = L-(l-1)
new_width = W-(w-1)
output = sliding_window_view(array, window_shape=[l, w]).reshape(new_length, new_width, l*w)
In theory, a sliding window should take almost no time at all, because it's just manipulating array strides and not copying data, but in this case the reshape forces it to make a complete copy of the array.理论上,滑动 window 应该几乎不需要时间,因为它只是操纵数组步幅而不是复制数据,但在这种情况下,重塑会强制它制作数组的完整副本。 On my computer this runs at about 50 million array elements per second on large arrays.在我的计算机上,它在大型 arrays 上以每秒大约 5000 万个数组元素的速度运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.