python - 在 scipy 中删除/设置稀疏矩阵的非零对角线元素

标签 python scipy sparse-matrix diagonal

假设我想从 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 代码,这是我能做的最好的事情吗?

最佳答案

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

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

关于python - 在 scipy 中删除/设置稀疏矩阵的非零对角线元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22660374/

相关文章:

python - 如何将数据帧转换为具有混合列类型的稀疏矩阵?

python - OverflowError 无法将 'int' 放入索引大小的整数中

python - 为什么 ndimage.label(image) 在考虑的形状中标记额外的形状?

python - SciPy构建/安装Mac Osx

python - Scipy 标签扩张

r - 具有 0 值的 R 矩阵单元格需要多少空间?以及如何处理大矩阵计算

c++ - 访问 boost sparse_matrix 的元素似乎会拖延程序

python - 是否可以在 Python 中将 RabbitMQ 直接回复功能与 Pika 生成器使用者一起使用?

python - Pandas datetime64 到字符串

python - Python 中的文字游戏服务器,设计优缺点?