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)
slide_arr1 = np.lib.stride_tricks.sliding_window_view(
a1,
3
)
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,]
print(slide_arr2)
[[0 1 2]
[2 3 4]
[4 5 6]
[6 7 8]]
|