Python scipy::crs_矩阵的棋盘子矩阵

Python scipy::crs_矩阵的棋盘子矩阵,python,scipy,sparse-matrix,submatrix,Python,Scipy,Sparse Matrix,Submatrix,给定一个scipy.sparse.crs_矩阵,我想提取在Numpy稠密代数中表示为的子矩阵 A[0::2, 0::2] i、 例如,A_{new}(i,j)=A(2*i,2*j)(“棋盘黑方矩阵”)。如果您首先将矩阵转换为COO格式,这是小菜一碟: def sps_black_squares(a): a = a.tocoo() idx = (a.row % 2 == 0) & (a.col % 2 == 0) new_shape = tuple((j-1)

给定一个
scipy.sparse.crs_矩阵
,我想提取在Numpy稠密代数中表示为的子矩阵

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

i、 例如,
A_{new}(i,j)=A(2*i,2*j)
(“棋盘黑方矩阵”)。

如果您首先将矩阵转换为COO格式,这是小菜一碟:

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

如果您首先将矩阵转换为COO格式,这是小菜一碟:

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
可能的重复可能的重复