如何使用numpy按不同起始点拆分得到重叠的(2,2)滑动窗口子数组
Numpy 实现重叠滑动窗口拆分方案
numpy.split仅支持无重叠的均等拆分,无法满足重叠滑动窗口的需求,你可以用numpy内置的滑动窗口视图工具实现,无额外内存开销,实现代码如下:
import numpy as np from numpy.lib.stride_tricks import sliding_window_view # 定义输入数组 input_arr = np.array([ [1, 2, 9, 10, 17, 18], [3, 4, 11, 12, 19, 20], [5, 6, 13, 14, 21, 22], [7, 8, 15, 16, 23, 24] ]) # 生成所有尺寸为(2,2)、默认步长为1的滑动窗口 all_windows = sliding_window_view(input_arr, window_shape=(2, 2)) # 行方向按步长2筛选,仅保留每2行作为一组的窗口序列,对应前两行、后两行分别生成结果的要求 target_result = all_windows[::2, :, :, :]
结果验证
生成的target_result维度为(2, 5, 2, 2),其中:
- 第一维
2对应两组行数据(前两行、后两行) - 第二维
5对应每组行的5个滑动窗口 - 最后两维对应(2,2)的窗口内容
你需要的前两行生成的窗口序列可通过target_result[0]获取,输出与预期完全一致:
array([[[ 1, 2], [ 3, 4]], [[ 2, 9], [ 4, 11]], [[ 9, 10], [11, 12]], [[10, 17], [12, 19]], [[17, 18], [19, 20]]])
低版本Numpy兼容方案
如果你使用的numpy版本低于1.20.0(无sliding_window_view接口),可以用as_strided实现相同效果:
from numpy.lib.stride_tricks import as_strided win_h, win_w = 2, 2 stride_h, stride_w = 2, 1 batch_num = (input_arr.shape[0] - win_h) // stride_h + 1 col_win_num = (input_arr.shape[1] - win_w) // stride_w + 1 target_result = as_strided( input_arr, shape=(batch_num, col_win_num, win_h, win_w), strides=( stride_h * input_arr.strides[0], stride_w * input_arr.strides[1], input_arr.strides[0], input_arr.strides[1] ) )
内容的提问来源于stack exchange,提问作者binaryBigInt
相关产品推荐
相关产品推荐

