Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a SciPy sparse matrix to a dictionary

Tags:

I am looking for an efficient way to transform a sparse matrix (scipy.sparse.csr.csr_matrix) to a Python dictionary.

As far as I understand the sparse matrix internally holds the data in a form similar to a dictionary, so it seems like such a conversion should be trivial and quick.

However, I couldn't find any method that does this.

like image 617
Doron Gold Avatar asked Mar 27 '19 09:03

Doron Gold


People also ask

How do you read a sparse matrix in python?

One way to visualize sparse matrix is to use 2d plot. Python's matplotlib has a special function called Spy for visualizing sparse matrix. Spy is very similar to matplotlib's imshow, which is great for plotting a matrix or an array as an image. imshow works with dense matrix, while Spy works with sparse matrix.


1 Answers

I think you can convert your matrix to the dictionary of keys based sparsed matrix format (compare scipy's documentation), and then access the underlying dictionary properties via the items method:

import numpy as np
from scipy.sparse import csr_matrix

c = csr_matrix(np.array([[1,2,3],
                         [4,5,6],
                         [7,8,9]])) # construct an example matrix
d = c.todok() # convert to dictionary of keys format
print(dict(d.items()))

This prints out

{(0, 0): 1, (1, 0): 4, (2, 0): 7, (0, 1): 2, (1, 1): 5, (2, 1): 8, (0, 2): 3, (1, 2): 6, (2, 2): 9}

like image 176
jdamp Avatar answered Oct 11 '22 16:10

jdamp