如何创建与 numpy 数组重叠 50% 的滑动 window?
How do I create a sliding window with a 50% overlap with a numpy array?
假设我有一个这样的数组:
array([1, 2, 3, 4, 5, 5, 7, 8, 9, 10])
我想改成
array([1, 2, 3, 4]), array([3, 4, 5, 6]), array([5, 6, 7, 8]), array([7, 8, 9, 10])
此处 window 大小为 4
,步长为 2
。
如何在 Python 函数中执行此操作?
你想要numpy.lib.stride_tricks.as_strided
def window(a, w = 4, o = 2, copy = False):
sh = (a.size - w + 1, w)
st = a.strides * 2
view = np.lib.stride_tricks.as_strided(a, strides = st, shape = sh)[0::o]
if copy:
return view.copy()
else:
return view
Out[]:
array([[ 1, 2, 3, 4],
[ 3, 4, 5, 6],
[ 5, 6, 7, 8],
[ 7, 8, 9, 10]])
如果你想写入窗口数组,一定要设置copy = True
它,否则它是一个内存共享视图。
假设我有一个这样的数组:
array([1, 2, 3, 4, 5, 5, 7, 8, 9, 10])
我想改成
array([1, 2, 3, 4]), array([3, 4, 5, 6]), array([5, 6, 7, 8]), array([7, 8, 9, 10])
此处 window 大小为 4
,步长为 2
。
如何在 Python 函数中执行此操作?
你想要numpy.lib.stride_tricks.as_strided
def window(a, w = 4, o = 2, copy = False):
sh = (a.size - w + 1, w)
st = a.strides * 2
view = np.lib.stride_tricks.as_strided(a, strides = st, shape = sh)[0::o]
if copy:
return view.copy()
else:
return view
Out[]:
array([[ 1, 2, 3, 4],
[ 3, 4, 5, 6],
[ 5, 6, 7, 8],
[ 7, 8, 9, 10]])
如果你想写入窗口数组,一定要设置copy = True
它,否则它是一个内存共享视图。