Remove / set nonzero diagonal sparse matrix elements in scipy

Say I would like to remove the diagonal from scipy.sparse.csr_matrix. Is there an effective way to do this? I saw that the module sparsetoolshas functions Cto return the diagonal.

Based on other SO answers here and here, my current approach is this:

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

which I then follow with

csr.eliminate_zeros()

Is this the best I can do without writing my own Cythoncode?

+4
source share
1 answer

@hpaulj IPython Notebook, nbviewer. , (, mat - CSR-):

mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))
+2

Source: https://habr.com/ru/post/1533518/


All Articles