【问题标题】:Remove/set the non-zero diagonal elements of a sparse matrix in scipy在 scipy 中删除/设置稀疏矩阵的非零对角元素
【发布时间】:2014-05-04 19:38:35
【问题描述】:

假设我想从scipy.sparse.csr_matrix 中删除对角线。有没有一种有效的方法呢?我看到在sparsetools 模块中有C 函数可以返回对角线。

基于其他 SO 答案 herehere 我目前的方法如下:

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


【解决方案1】:

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

mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2013-08-09
    相关资源
    最近更新 更多