gpt4 book ai didi

python - 从 2D 数组滑动窗口,沿 axis=0 或 rows 滑动以给出 3D 数组

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:26 37 4
gpt4 key购买 nike

我有一个这种形式的二维 numpy 数组:

[[  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.]
[ 40. 41. 42. 43. 44.]
[ 45. 46. 47. 48. 49.]]

我想构建一个数组 View ,将其元素分组到一个移动窗口中(在我的示例中大小为 4)。我的结果应该是 (6, 4, 5) 的形状,我可以按如下方式构造它:

res = []
mem = 4
for i in range(mem, X.shape[0]+1):
res.append(X[i-mem:i, : ])
res = np.asarray(res)
print res.shape

我想避免重新分配,所以我想知道我是否可以构造一个 View 来给出这个结果,例如 as_strided。

非常欢迎解释该过程。

谢谢

最佳答案

这是请求 np.lib.stride_tricks.as_strided 的方法-

def strided_axis0(a, L): 
# INPUTS :
# a is array
# L is length of array along axis=0 to be cut for forming each subarray

# Length of 3D output array along its axis=0
nd0 = a.shape[0] - L + 1

# Store shape and strides info
m,n = a.shape
s0,s1 = a.strides

# Finally use strides to get the 3D array view
return np.lib.stride_tricks.as_strided(a, shape=(nd0,L,n), strides=(s0,s0,s1))

sample 运行-

In [48]: X = np.arange(35).reshape(-1,5)

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]])

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

[[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],

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

[[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34]]])

关于python - 从 2D 数组滑动窗口,沿 axis=0 或 rows 滑动以给出 3D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185589/

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