numpy 滑动窗口取数据
import numpy as np
a1 = np.arange(0,10)
print(a1)
[0 1 2 3 4 5 6 7 8 9]
要做成以下形式
for循环方式(数组大的时候,超级慢)
total_length = a1.shape[0] # 数组总长度
win_length = 3 # 窗口长度
step_length = 2 # 步长
frequency = (total_length - win_length)//step_length + 1 # 频率
print(frequency)
4
list_arr = []
start_index = 0 # 切片开始下标
for i in range(frequency):
stop_index = start_index + win_length # 切片结束下标
a2 = a1[start_index:stop_index] # 切片数组
start_index += step_length # 下一次切片开始下标
a2 = np.expand_dims(a2, axis=0) # 维度增加一维
list_arr.append(a2) # 追加进列表
print(list_arr)
[array([[0, 1, 2]]), array([[2, 3, 4]]), array([[4, 5, 6]]), array([[6, 7, 8]])]
slide_arr = np.concatenate(list_arr, axis=0) # 滑动窗口后的数组
print(slide_arr)
[[0 1 2]
[2 3 4]
[4 5 6]
[6 7 8]]
numpy的方式(numpy的版本要在1.20.0及以上)
print(a1)
[0 1 2 3 4 5 6 7 8 9]
strides = (1, step_length)
# 步长为1步的滑动窗口
slide_arr1 = np.lib.stride_tricks.sliding_window_view(
a1, # 原数组
3 # 窗口大小,也可以是元组,如(2,2)
)
print(slide_arr1)
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]
[5 6 7]
[6 7 8]
[7 8 9]]
slide_arr2 = slide_arr1[::2,] # 步长为2步的滑动窗口
print(slide_arr2)
[[0 1 2]
[2 3 4]
[4 5 6]
[6 7 8]]