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
source to share
scipy.sparse.*_matrix
Has several useful methods, for example if a
, for example scipy.sparse.csr_matrix
:
-
a.toarray()
oraA
- returns a dense ndarray representation of this matrix. (numpy.array
, recommended) -
a.todense()
oraM
- returns a dense matrix representation of this matrix. (numpy.matrix
)
source to share
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.]])
source to share
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()
source to share