+1 vote
in Programming Languages by (60.0k points)
I want to save a CSR matrix to a file so that I can load it later for processing. Is there any Python function for saving and loading a sparse matrix?

1 Answer

+2 votes
by (353k points)
 
Best answer

From the sparse module of scipy, you can use the save_npz() function to save a sparse matrix to a file using the ".npz" format. To load a saved sparse matrix using the ".npz" format, you can use the load_npz() function.

Here is an example to show how to use these functions:

>>> import numpy as np

>>> from scipy.sparse import csr_matrix, save_npz, load_npz

>>> r = np.array([0, 0, 1, 2, 2, 3, 3, 3])

>>> c = np.array([0, 1, 2, 1, 2, 0, 2, 3])

>>> v = np.array([1, 2, 3, 4, 5, 6, 7, 8])

>>> x=csr_matrix((v, (r,c)), shape=(4,4))

>>> x

<4x4 sparse matrix of type '<class 'numpy.int64'>'

with 8 stored elements in Compressed Sparse Row format>

>>> x.toarray()

array([[1, 2, 0, 0],

       [0, 0, 3, 0],

       [0, 4, 5, 0],

       [6, 0, 7, 8]])

>>> save_npz('file1.npz', x)

>>> x1=load_npz('file1.npz')

>>> x1.toarray()

array([[1, 2, 0, 0],

       [0, 0, 3, 0],

       [0, 4, 5, 0],

       [6, 0, 7, 8]])


...