7

假设我想从 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

然后我跟着

csr.eliminate_zeros()

在不编写自己的Cython代码的情况下,这是我能做的最好的事情吗?

4

1 回答 1

3

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

mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))
于 2014-04-05T13:48:15.993 回答