python - scipy::crs_matrix 的棋盘子矩阵

标签 python scipy sparse-matrix submatrix

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

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

即,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

关于python - scipy::crs_matrix 的棋盘子矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17929707/

相关文章:

Matlab - 稀疏矩阵系统分辨率

python - 在 Python wunderlist API 任务中获取 {"error":"bad_request"}

python - 在 Python 中调用类方法会引发 TypeError

python - NumPy 快速傅立叶变换 (FFT) 对 Audacity 中生成的正弦波不起作用

python - 绘制文档 tfidf 二维图

c++ - 在 C/C++ 中为有限差分法创建五对角稀疏矩阵的最佳方法是什么?

python - VS Code - 解释器清理列表

python - 如何防止 pandas 仅将一个 df 的值分配给另一行的另一列?

python - Scipy curve_fit似乎没有改变初始参数

python - for-loop + numpy.where 的向量化版本