在scipy中删除/设置稀疏矩阵的非零对角元素

Mid*_*ter 6 python scipy sparse-matrix diagonal

说我想从a中删除对角线scipy.sparse.csr_matrix.这样做有效吗?我在sparsetools模块中看到有C返回对角线的功能.

基于其他SO答案在这里这里我目前的方法如下:

def csr_setdiag_val(csr, value=0):
    """Set all diagonal nonzero elements
    (elements currently in the sparsity pattern)
    to the given value. Useful to set to 0 mostly.
    """
    if csr.format != "csr":
        raise ValueError('Matrix given must be of CSR format.')
    csr.sort_indices()
    pointer = csr.indptr
    indices = csr.indices
    data = csr.data
    for i in range(min(csr.shape)):
        ind = indices[pointer[i]: pointer[i + 1]]
        j =  ind.searchsorted(i)
        # matrix has only elements up until diagonal (in row i)
        if j == len(ind):
            continue
        j += pointer[i]
        # in case matrix has only elements after diagonal (in row i)
        if indices[j] == i:
            data[j] = value
Run Code Online (Sandbox Code Playgroud)

然后我跟着它

csr.eliminate_zeros()
Run Code Online (Sandbox Code Playgroud)

如果不编写自己的Cython代码,这是我能做的最好的吗?

Mid*_*ter 3

根据 @hpaulj 的评论,我创建了一个 IPython Notebook,可以在 nbviewer 上看到。这表明在提到的所有方法中,以下方法是最快的(假设是mat稀疏 CSR 矩阵):

mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))
Run Code Online (Sandbox Code Playgroud)