How to convert "SciPy sparse matrix" to "NumPy matrix"?

I am using a python function called "incidence_matrix (G)" which returns the incidence matrix of the plot. This is from the Networkx package. The problem I am facing is the return type of this function is "Scipy Sparse Matrix". I need to have an incidents matrix in numpy matrix or array format. I was wondering if there is any easy way to do this or not? Or is there a built-in function that can do this conversion for me or not?

thank

+14


source to share


3 answers


scipy.sparse.*_matrix

Has several useful methods, for example if a

, for example scipy.sparse.csr_matrix

:



  • a.toarray()

    or aA

    - returns a dense ndarray representation of this matrix. ( numpy.array

    , recommended)
  • a.todense()

    or aM

    - returns a dense matrix representation of this matrix. ( numpy.matrix

    )
+24


source


The easiest way is to call the todense () method on the data:



In [1]: import networkx as nx

In [2]: G = nx.Graph([(1,2)])

In [3]: nx.incidence_matrix(G)
Out[3]: 
<2x1 sparse matrix of type '<type 'numpy.float64'>'
    with 2 stored elements in Compressed Sparse Column format>

In [4]: nx.incidence_matrix(G).todense()
Out[4]: 
matrix([[ 1.],
        [ 1.]])

In [5]: nx.incidence_matrix(G).todense().A
Out[5]: 
array([[ 1.],
       [ 1.]])

      

+1


source


I found that in the case of csr matrices todense()

and are toarray()

just wrapping tuples rather than creating a formatted version of the data in the form of an ndarray matrix. This is not applicable for the skmultilearn classifiers that I am training.

I translated it to lil matrix - the numpy format can parse exactly and then run toarray()

on that:

sparse.lil_matrix(<my-sparse_matrix>).toarray()

      

0


source







All Articles