【问题标题】:Scipy.sparse test for sparse matrix returns False for a diagonal matrix. Why?稀疏矩阵的 Scipy.sparse 测试对对角矩阵返回 False。为什么?
【发布时间】:2014-02-11 12:57:17
【问题描述】:
我正在学习如何使用 Scipy.sparse。我尝试的第一件事是检查对角矩阵的稀疏性。然而,Scipy 声称它并不稀疏。这是正确的行为吗?
以下代码返回“False”:
import numpy as np
import scipy.sparse as sps
A = np.diag(range(1000))
print sps.issparse(A)
【问题讨论】:
标签:
python
scipy
sparse-matrix
【解决方案1】:
issparse 不检查矩阵的密度是否小于某个任意数字,它检查参数是否为 spmatrix 的实例。
np.diag(range(1000)) 返回一个标准的ndarray:
>>> type(A)
<type 'numpy.ndarray'>
您可以通过多种方式从中创建稀疏矩阵。随机选择一个:
>>> sps.coo_matrix(A)
<1000x1000 sparse matrix of type '<type 'numpy.int32'>'
with 999 stored elements in COOrdinate format>
>>> m = sps.coo_matrix(A)
>>> sps.issparse(m)
True
但同样,请注意issparse 并不关心对象的密度,只关心它是否是特定稀疏矩阵类型的实例。例如:
>>> m2 = sps.coo_matrix(np.ones((1000,1000)))
>>> m2
<1000x1000 sparse matrix of type '<type 'numpy.float64'>'
with 1000000 stored elements in COOrdinate format>
>>> sps.issparse(m2)
True