The Scipy.sparse test for a sparse matrix returns False for the diagonal matrix. What for?

I am learning how to use Scipy.sparse. The first thing I tried was to check the diagonal matrix for sparseness. However, Scipi claims that he is not sparse. Is it correct?

The following code returns "False":

import numpy as np
import scipy.sparse as sps
A = np.diag(range(1000))
print sps.issparse(A)
+3
source share
1 answer

issparsedoes not check if the matrix has a density less than some arbitrary number, it checks if the argument is an instance spmatrix.

np.diag(range(1000))returns standard ndarray:

>>> type(A)
<type 'numpy.ndarray'>

You can make a small matrix from it in several ways. Randomly select one:

>>> 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
+5

All Articles