python - 从 scipy 中的稀疏矩阵中删除对角线元素

标签 python scipy sparse-matrix

我想从稀疏矩阵中删除对角线元素。由于矩阵是稀疏的,这些元素一旦被移除就不应该被存储。

Scipy 提供了一种设置对角线元素值的方法:setdiag

如果我尝试使用 lil_matrix,它会起作用:

>>> a = np.ones((2,2))
>>> c = lil_matrix(a)
>>> c.setdiag(0)
>>> c
<2x2 sparse matrix of type '<type 'numpy.float64'>'
    with 2 stored elements in LInked List format>

但是对于 csr_matrix,似乎对角线元素并没有从存储中移除:

>>> b = csr_matrix(a)
>>> b
<2x2 sparse matrix of type '<type 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

>>> b.setdiag(0)
>>> b
<2x2 sparse matrix of type '<type 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

>>> b.toarray()
array([[ 0.,  1.],
       [ 1.,  0.]])

通过密集数组,我们当然有:

>>> csr_matrix(b.toarray())
<2x2 sparse matrix of type '<type 'numpy.float64'>'
    with 2 stored elements in Compressed Sparse Row format>

这是故意的吗?如果是这样,是否是由于 csr 矩阵的压缩格式?除了从稀疏到密集再到稀疏之外,还有其他解决方法吗?

最佳答案

简单地将元素设置为 0 不会改变 csr 矩阵的稀疏性。您必须应用 eliminate_zeros

In [807]: a=sparse.csr_matrix(np.ones((2,2)))
In [808]: a
Out[808]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>
In [809]: a.setdiag(0)
In [810]: a
Out[810]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>
In [811]: a.eliminate_zeros()
In [812]: a
Out[812]: 
<2x2 sparse matrix of type '<class 'numpy.float64'>'
    with 2 stored elements in Compressed Sparse Row format>

由于更改 csr 矩阵的稀疏度相对昂贵,因此您可以在不更改稀疏度的情况下将值更改为 0。

In [829]: %%timeit a=sparse.csr_matrix(np.ones((1000,1000)))
     ...: a.setdiag(0)
100 loops, best of 3: 3.86 ms per loop

In [830]: %%timeit a=sparse.csr_matrix(np.ones((1000,1000)))
     ...: a.setdiag(0)
     ...: a.eliminate_zeros()
SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
10 loops, best of 3: 133 ms per loop

In [831]: %%timeit a=sparse.lil_matrix(np.ones((1000,1000)))
     ...: a.setdiag(0)
100 loops, best of 3: 14.1 ms per loop

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

相关文章:

complexity-theory - 稀疏对称矩阵预乘全向量最低阶复杂度引用

c++ - 一行全为零的稀疏矩阵的 CSR 格式

python - 创建单行 python pandas 数据框

python - 在一组元组中找到最小值时如何忽略负数?

python - 如何在 Python 中从 SXS 加载 C DLL?

c# - 如何在数据库中存储稀疏 bool 向量?

python - 无法加载 CIFAR-10 数据集 : Invalid load key '\x1f'

python - Scipy:通过阈值的稀疏相似性计算 epsilon 邻域

Python:np.linalg.eigvalsh返回负特征值

python - 用 Scipy (Python) 将经验分布拟合到理论分布?