2013-07-29 27 views
1

給定一個scipy.sparse.crs_matrix,我想提取子矩陣,在與NumPy的密集代數將被表示爲爲SciPy的棋盤子矩陣:: crs_matrix

A[0::2, 0::2] 

A_{new}(i,j) = A(2*i,2*j)(「棋盤黑方塊矩陣」)。

+0

可能重複(http://stackoverflow.com/questions/7609108/切片稀疏-SciPy的矩陣) –

回答

1

如果第一轉換矩陣以COO格式化是一塊蛋糕:[切片稀疏(SciPy的)矩陣]的

def sps_black_squares(a): 
    a = a.tocoo() 
    idx = (a.row % 2 == 0) & (a.col % 2 == 0) 
    new_shape = tuple((j-1) // 2 + 1 for j in a.shape) 
    return sps.csr_matrix((a.data[idx], (a.row[idx]//2, a.col[idx]//2)), 
          shape=new_shape) 

%timeit sps_black_squares(a) 
1000 loops, best of 3: 315 us per loop 

%timeit sps.csr_matrix(a.toarray()[::2, ::2]) 
100 loops, best of 3: 6.55 ms per loop 

np.allclose(sps_black_squares(a).toarray(), a.toarray()[::2, ::2]) 
Out[119]: True