从2D阵列滑动窗口沿轴= 0或行滑动以提供3D阵列 [英] Sliding windows from 2D array that slides along axis=0 or rows to give a 3D array
本文介绍了从2D阵列滑动窗口沿轴= 0或行滑动以提供3D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这种形式的二维numpy数组:
I have a 2-d numpy array of this form:
[[ 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.]]
我想构造一个数组视图,将其元素分组到一个移动窗口中(在我的示例中,大小为4).我的结果应该为(6, 4, 5)
的形状,并且可以按以下方式构造它:
I want to construct a view of the array, grouping its elements in a moving window (of size 4 in my example). My result should be of shape (6, 4, 5)
and I can construct it as follows:
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
我想避免重新分配,所以我想知道是否可以构造一个视图以给出此结果,例如as_strided.
I want to avoid reallocation, so I wonder if I can construct a view to give this result, with as_strided for example.
非常欢迎对此过程进行解释.
An explanation of the process is very welcome.
谢谢
推荐答案
以下是请求的方法 np.lib.stride_tricks.as_strided
-
Here's an approach with requested 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))
样品运行-
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]]])
这篇关于从2D阵列滑动窗口沿轴= 0或行滑动以提供3D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文