P.E*_*ido 3 python scipy sparse-matrix
我正在学习如何使用Scipy.sparse.我尝试的第一件事是检查对角矩阵的稀疏性.然而,Scipy声称它并不稀疏.这是正确的行为吗?
以下代码返回'False':
import numpy as np
import scipy.sparse as sps
A = np.diag(range(1000))
print sps.issparse(A)
Run Code Online (Sandbox Code Playgroud)
issparse不检查矩阵的密度是否小于某个任意数,它检查参数是否是实例spmatrix.
np.diag(range(1000))返回标准ndarray:
>>> type(A)
<type 'numpy.ndarray'>
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式从中制作稀疏矩阵.随机选择一个:
>>> 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
Run Code Online (Sandbox Code Playgroud)
但同样,请注意,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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1763 次 |
| 最近记录: |