[英]Remove/set the non-zero diagonal elements of a sparse matrix in scipy
Say I would like to remove the diagonal from a scipy.sparse.csr_matrix
. 假设我想从
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. 我在
sparsetools
模块中看到有C
函数返回对角线。
Based on other SO answers here and here my current approach is the following: 基于其他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
which I then follow with 然后我跟着它
csr.eliminate_zeros()
Is that the best I can do without writing my own Cython
code? 如果不编写我自己的
Cython
代码,这是我能做的最好的吗?
Based on @hpaulj's comment, I created an IPython Notebook which can be seen on nbviewer . 根据@ hpaulj的评论,我创建了一个可以在nbviewer上看到的IPython Notebook。 This shows that out of all methods mentioned the following is the fastest (assume that
mat
is a sparse CSR matrix): 这表明在提到的所有方法中,以下是最快的(假设
mat
是一个稀疏的CSR矩阵):
mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.