Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: Transform sparse matrix to ndarray

I really couldn't google it. How to transform sparse matrix to ndarray?

Assume, I have sparse matrix t of zeros. Then

g = t.todense()
g[:10] 

matrix([[0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0]])

instead of [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Solution:

t.toarray().flatten()

like image 981
doubts Avatar asked Oct 21 '22 05:10

doubts


1 Answers

Use np.asarray:

>>> a = np.asarray(g)
>>> a
array([[0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0]])

Where g is your dense matrix in the example (after calling t.todense()).

You specifically asked for the output of

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

which has only one dimension. To get that, you'll want to flatten the array:

>>> flat_array = np.asarray(g).flatten()
>>> flat_array
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Edit:

You can skip straight to the array from the sparse matrix with:

a = t.toarray()
like image 144
ford Avatar answered Oct 24 '22 11:10

ford