我想从稀疏矩阵中删除对角线元素。由于矩阵是稀疏的,这些元素在删除后不应存储。Scipy提供了一种设置对角线元素值的方法:setdiag。如果我使用lil_matrix尝试它,它可以工作:
然而使用csr_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矩阵的压缩格式吗?除了从稀疏到密集再到稀疏的方法,还有其他解决方法吗?