Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transform a "SciPy sparse matrix" to a "NumPy matrix"?

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

Thanks

like image 209
Mr.Boy Avatar asked Oct 26 '14 18:10

Mr.Boy


People also ask

Does Numpy use sparse matrix?

Sparse Matrices in PythonA dense matrix stored in a NumPy array can be converted into a sparse matrix using the CSR representation by calling the csr_matrix() function.

How do you create a Numpy matrix?

We can create a matrix in Numpy using functions like array(), ndarray() or matrix(). Matrix function by default creates a specialized 2D array from the given input. The input should be in the form of a string or an array object-like.


3 Answers

The scipy.sparse.*_matrix has several useful methods, for example, if a is e.g. scipy.sparse.csr_matrix:

  • a.toarray() or a.A - Return a dense ndarray representation of this matrix. (numpy.array, recommended)
  • a.todense() or a.M - Return a dense matrix representation of this matrix. (numpy.matrix)
like image 139
sebix Avatar answered Oct 19 '22 17:10

sebix


I found that in the case of csr matrices, todense() and toarray() simply wrapped the tuples rather than producing a ndarray formatted version of the data in matrix form. This was unusable for the skmultilearn classifiers I'm training.

I translated it to a lil matrix- a format numpy can parse accurately, and then ran toarray() on that:

sparse.lil_matrix(<my-sparse_matrix>).toarray()
like image 3
user108569 Avatar answered Oct 19 '22 17:10

user108569


The simplest 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.]])
like image 1
Aric Avatar answered Oct 19 '22 19:10

Aric