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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With