+3 votes
in Programming Languages by (56.5k points)

I saved a CSR_matrix as .npy file on the disk using np.save(), but when I load the .npy file and try to see the matrix using toarray(), it gives error.

>>> X=np.load('rr.npy')
>>> X.toarray()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'toarray'

How can I see the data in the matrix?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

np.load() converts CSR matrix to an object, so you cannot use toarray() to see the matrix. You need to first use tolist() and then toarray() to see the data.

See the value of X with and without tolist().

>>> X
array(<3x3 sparse matrix of type '<class 'numpy.int64'>'
        with 6 stored elements in Compressed Sparse Row format>, dtype=object)

Here dtype is object, so toarray() will give error.

>>> X=np.load('rr.npy').tolist()
>>> X
<3x3 sparse matrix of type '<class 'numpy.int64'>'
        with 6 stored elements in Compressed Sparse Row format>
 

Using tolist(), you can convert object to a list and then use toarray() to see the data.

>>> X.toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])


...