说我想从scipy.sparse.csr_matrix
删除对角线。这样做有效吗?我在sparsetools
模块中看到有C
函数返回对角线。
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
代码,这是我能做的最好的吗?
答案 0 :(得分:2)
根据@ hpaulj的评论,我创建了一个can be seen on nbviewer的IPython笔记本。这表明在提到的所有方法中,以下是最快的(假设mat
是一个稀疏的CSR矩阵):
mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))