删除/设置scipy中稀疏矩阵的非零对角元素 [英] Remove/set the non-zero diagonal elements of a sparse matrix in scipy
问题描述
假设我想从 scipy.sparse.csr_matrix
中删除对角线.有没有一种有效的方法呢?我看到在 sparsetools
模块中有 C
函数可以返回对角线.
Say I would like to remove the diagonal from a scipy.sparse.csr_matrix
. Is there an efficient way of doing so? I saw that in the sparsetools
module there are C
functions to return the diagonal.
Based on other SO answers here and here my current approach is the following:
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
代码,这是我能做的最好的事情吗?
Is that the best I can do without writing my own Cython
code?
推荐答案
基于@hpaulj 的评论,我创建了一个 IPython Notebook,它 可以在 nbviewer 上看到.这表明在所有提到的方法中,以下是最快的(假设 mat
是一个稀疏的 CSR 矩阵):
Based on @hpaulj's comment, I created an IPython Notebook which can be seen on nbviewer. This shows that out of all methods mentioned the following is the fastest (assume that mat
is a sparse CSR matrix):
mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))
这篇关于删除/设置scipy中稀疏矩阵的非零对角元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!