我试图在我的一个作业中做一些异常检测,我试图创建滑动窗口,但我想让它们使一个窗口不与另一个重叠。例如数组= [1,2,3,4,5,6]我想得到这个结果结果= [[1,2,3],[4,5,6],6]]显然你可以使用as_strided或sliding_window_view方法,但第二个方法效果不太好,但如果有人知道解决方案,那就非常感谢了
bq3bfh9z1#
你的一维数组:
In [234]: x=np.arange(1,7)
字符串一个简单的重塑:
In [235]: x.reshape(-1,3)Out[235]: array([[1, 2, 3], [4, 5, 6]])
In [235]: x.reshape(-1,3)
Out[235]:
array([[1, 2, 3],
[4, 5, 6]])
型滑动窗口创建(3,)个窗口,完全重叠
In [236]: np.lib.stride_tricks.sliding_window_view(x,3)Out[236]: array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])
In [236]: np.lib.stride_tricks.sliding_window_view(x,3)
Out[236]:
[2, 3, 4],
[3, 4, 5],
型从那里我们可以很容易地切出不重叠的元素:
In [237]: np.lib.stride_tricks.sliding_window_view(x,3)[::3]Out[237]: array([[1, 2, 3], [4, 5, 6]])
In [237]: np.lib.stride_tricks.sliding_window_view(x,3)[::3]
Out[237]:
型要使用as_strided,我们必须理解strides。sliding_windows为我们做了这样的思考:
as_strided
strides
sliding_windows
In [238]: x.stridesOut[238]: (4,)In [239]: np.lib.stride_tricks.as_strided(x,shape=(2,3),strides=(12,4))Out[239]: array([[1, 2, 3], [4, 5, 6]])
In [238]: x.strides
Out[238]: (4,)
In [239]: np.lib.stride_tricks.as_strided(x,shape=(2,3),strides=(12,4))
Out[239]:
型12是(3*4)sliding_windows的作用:
12
(3*4)
In [240]: np.lib.stride_tricks.as_strided(x,shape=(4,3),strides=(4,4))Out[240]: array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])
In [240]: np.lib.stride_tricks.as_strided(x,shape=(4,3),strides=(4,4))
Out[240]:
型sliding_windows更容易使用,因为我们不需要知道步幅,它可以确保结果是正确的大小。
l7mqbcuq2#
import numpy as np# Your initial arrayarray = np.array([1, 2, 3, 4, 5, 6])# Reshape the array into a 2D array where each sub-array is a window# This only works if the length of the array is divisible by the window sizeresult = array.reshape(-1, 2)print(result)
import numpy as np
# Your initial array
array = np.array([1, 2, 3, 4, 5, 6])
# Reshape the array into a 2D array where each sub-array is a window
# This only works if the length of the array is divisible by the window size
result = array.reshape(-1, 2)
print(result)
字符串
2条答案
按热度按时间bq3bfh9z1#
你的一维数组:
字符串
一个简单的重塑:
型
滑动窗口创建(3,)个窗口,完全重叠
型
从那里我们可以很容易地切出不重叠的元素:
型
要使用
as_strided
,我们必须理解strides
。sliding_windows
为我们做了这样的思考:型
12
是(3*4)
sliding_windows的作用:
型
sliding_windows
更容易使用,因为我们不需要知道步幅,它可以确保结果是正确的大小。l7mqbcuq2#
字符串