2017-12-18 68 views
1

我有一个正方形阵列的子阵列x,形状(N, N),我想检索这是在主对角线的x居中形状的方形子阵列。例如,N = 3 & n = 2,并使用numpy的as_strided检索中心的主对角线

操作
x = np.arange(9).reshape((3, 3)) 

应该产生

array([[[0, 1], 
     [3, 4]], 
     [[4, 5], 
     [7, 8]]]) 

一种方法是使用make_windows

def make_windows(a, sub_w, sub_h): 
    w, h = a.shape 
    a_strided = np.lib.stride_tricks.as_strided(
     a, shape=[w - sub_w + 1, h - sub_h + 1, 
        sub_w, sub_h], 
    strides=a.strides + a.strides) 
    return a_strided 

,并完成类似np.einsum('ii...->i...', make_windows(x, 2, 2)),但它会整齐地做到一步。单独使用as_strided可以吗?

回答

3

不确定:

def diag_windows(x, n): 
    if x.ndim != 2 or x.shape[0] != x.shape[1] or x.shape[0] < n: 
     raise ValueError("Invalid input") 
    w = as_strided(x, shape=(x.shape[0] - n + 1, n, n), 
        strides=(x.strides[0]+x.strides[1], x.strides[0], x.strides[1])) 
    return w 

例如:

In [14]: x 
Out[14]: 
array([[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 10, 11], 
     [12, 13, 14, 15]]) 

In [15]: diag_windows(x, 2) 
Out[15]: 
array([[[ 0, 1], 
     [ 4, 5]], 

     [[ 5, 6], 
     [ 9, 10]], 

     [[10, 11], 
     [14, 15]]]) 

In [16]: diag_windows(x, 3) 
Out[16]: 
array([[[ 0, 1, 2], 
     [ 4, 5, 6], 
     [ 8, 9, 10]], 

     [[ 5, 6, 7], 
     [ 9, 10, 11], 
     [13, 14, 15]]]) 

In [17]: diag_windows(x, 4) 
Out[17]: 
array([[[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 10, 11], 
     [12, 13, 14, 15]]]) 
相关问题