Reputation: 3553
I am learning how to use Scipy.sparse. The first thing I tried was checking a diagonal matrix for sparsity. However, Scipy claims it is not sparse. Is this a correct behavior?
The following code returns 'False':
import numpy as np
import scipy.sparse as sps
A = np.diag(range(1000))
print sps.issparse(A)
Upvotes: 3
Views: 2088
Reputation: 353179
issparse
doesn't check to see whether a matrix has a density less than some arbitrary number, it checks to see whether the argument is an instance of spmatrix
.
np.diag(range(1000))
returns a standard ndarray
:
>>> type(A)
<type 'numpy.ndarray'>
You can make a sparse matrix from it in several ways. Choosing one at random:
>>> 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
but again, note that issparse
couldn't care less about the density of the object, only about whether or not it's an instance of a specific sparse matrix type. For example:
>>> 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
Upvotes: 5