AttributeError using scipy.sparse.toarray()

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



AttributeError using scipy.sparse.toarray()


import scipy as sp
import numpy as np

a=sp.sparse.coo_matrix(np.random.randint(0,9,[4,5]))
b=sp.sparse.coo_matrix(np.random.randint(0,9,[4,2]))
sp.hstack([a,b]).toarray()



is giving me


AttributeError: 'numpy.ndarray' object has no attribute 'toarray'



could you help me with my silly mistake here?




1 Answer
1



sp.hstack (i.e. numpy.hstack) is the ordinary, dense hstack, which won't combine the sparse arrays correctly. It builds a 1D numpy array already (of object dtype; in other words, it just wraps the Python-level objects and crams them in there.) You want scipy.sparse.hstack:


sp.hstack


numpy.hstack


scipy.sparse.hstack


In [332]: sp.hstack([a, b])
Out[332]:
array([<4x5 sparse matrix of type '<class 'numpy.int64'>'
with 17 stored elements in COOrdinate format>,
<4x2 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in COOrdinate format>], dtype=object)

In [333]: sp.hstack([a, b]).toarray()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-333-4f469eb98b12> in <module>()
----> 1 sp.hstack([a, b]).toarray()

AttributeError: 'numpy.ndarray' object has no attribute 'toarray'

In [334]: sp.sparse.hstack([a, b])
Out[334]:
<4x7 sparse matrix of type '<class 'numpy.int64'>'
with 24 stored elements in COOrdinate format>

In [335]: sp.sparse.hstack([a, b]).toarray()
Out[335]:
array([[3, 2, 7, 0, 5, 5, 1],
[7, 1, 2, 1, 7, 0, 8],
[6, 1, 6, 1, 8, 6, 2],
[7, 6, 0, 5, 0, 8, 8]], dtype=int64)





😠 .... thanks!!!
– Kam
Aug 6 at 1:27






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard