gpt4 book ai didi

python - 从 2D 数组中沿 axis=0 滑动的滑动窗口给出具有动态重叠的 3D 数组

转载 作者:行者123 更新时间:2023-12-01 01:32:03 26 4
gpt4 key购买 nike

使用此question中的答案,我能够沿着步长 = 1 的行获得矩阵的窗口版本(每个窗口除了一行之外都是相同的):

def strided_axis0(a, L): 
nd0 = a.shape[0] - L + 1
m,n = a.shape
s0,s1 = a.strides
return np.lib.stride_tricks.as_strided(a, shape=(nd0,L,n), strides=(s0,s0,s1))

我想在函数中添加一个参数来获得不同的重叠。

例如:

In [49]: X
Out[49]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]])

In [50]: strided_axis0(X, L=4, ov = 2)

Out[50]:
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],

[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]],


[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]]])

最佳答案

您可以尝试:

def get_strides(a, L, ov):
out = []
for i in range(0, a.shape[0]-L+1, L-ov):
out.append(a[i:i+L, :])

return np.array(out)

基本上,它生成从第 0 行开始向下移动 L-ov 行的所有数组。当距数组末尾 L 行时停止。将数组作为输入,它会生成:

> print(get_strides(a, 4, 2))
> [[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]

[[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]

[[20 21 22 23 24]
[25 26 27 28 29]
[30 31 32 33 34]
[35 36 37 38 39]]]

关于python - 从 2D 数组中沿 axis=0 滑动的滑动窗口给出具有动态重叠的 3D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52770301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com