What is returned by np.asarray() called on a sparse matrix as-it-is?

Viewed 186
> import scipy
> import numpy as np
> smat_csr = scipy.sparse.csr_matrix([[0,0,1],[0,1,0],[0,0,0]])
> print(smat_csr)

(0, 2)  1
(1, 1)  1

> print(smat_csr.shape)

(3, 3)

> smat_np = np.asarray(smat_csr)
> print(type(smat_np))

<class 'numpy.ndarray'>

So smat_np looks like a numpy's array.....

> print(smat_np.shape)

()

Uhm ... its shape property is an empty tuple!

> print(smat_np)

(0, 2)  1
(1, 1)  1

Looks like it is still sparse....

Question: What kind of object is the one returned by np.asarray when we pass a sparse matrix as-it-is as an argument?

Disclaimer: I know that I can convert the sparse matrix in a dense one using .todense()

1 Answers

To numpy a sparse matrix is just a Python object, so it returns a single element, 0d, object dtype array. It doesn't do any sort of conversion. You have to use a sparse method, such as toarray (or .A` for short) to create a numpy array.

That means you have to cautious when passing a sparse matrix to numpy functions. If the function tries to convert it to an array (as it would with a list), it won't work. If it just delegates the task to object's method(s), it might.

Related