从2D阵列滑动窗口沿轴= 0或行滑动以提供3D阵列

vol*_*ile 3 python numpy

我有这种形式的二维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.]]
Run Code Online (Sandbox Code Playgroud)

我想构造一个数组视图,将它的元素分组在一个移动窗口中(在我的示例中大小为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
Run Code Online (Sandbox Code Playgroud)

我想避免重新分配,所以我想知道是否可以构造一个视图以给出此结果,例如使用as_strided。

欢迎对此过程进行解释。

谢谢

Div*_*kar 5

这是要求的方法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))
Run Code Online (Sandbox Code Playgroud)

样品运行-

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]]])
Run Code Online (Sandbox Code Playgroud)

  • @FrancescoPegoraro将[view_as_windows`](http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows)与`step`参数一起使用。 (2认同)