【发布时间】:2014-05-04 19:38:35
【问题描述】:
假设我想从scipy.sparse.csr_matrix 中删除对角线。有没有一种有效的方法呢?我看到在sparsetools 模块中有C 函数可以返回对角线。
基于其他 SO 答案 here 和 here 我目前的方法如下:
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 代码,这是我能做到的最好的事情吗?
【问题讨论】:
-
scr_matrix.setdiag还不够吗? -
setdiag接受一个数组并设置以前不在矩阵中的元素。所以向矩阵添加新元素的成本很高,但我没有比较它们。 -
如何使用要删除的对角线创建一个新的稀疏矩阵,然后减去它?您可能需要运行“压缩”功能才能完全删除条目。
-
好主意!你可以see the results in this IPython Notebook。对上面的函数进行 Cythonizing 可能会稍微提高速度,但目前减法是最简单的。
标签: python scipy sparse-matrix diagonal