Save or Load SciPy Sparse CSR Matrix in Portable Data Format

In this tutorial, we will learn how to save/load SciPy sparse CSR matrix in portable data format. By Pranit Sharma Last updated : June 07, 2023

What is Sparse CSR Matrix in SciPy?

Sparse CSR Matrix is a row-oriented matrix (or, Compressed Sparse Row matrix) and it can be used for arithmetic operations. The Sparse CSR matrix supports addition, subtraction, multiplication, division, and matrix power. A Sparse CSR matrix can be created by using the scipy.sparse.csr_matrix() method.

Here, we will learn how can we save/load a Sparse CSR matrix in portable data format. Let's understand with a Python program how can we achieve this task.

How to Save/Load SciPy Sparse CSR Matrix in Portable Data Format?

To save/load a Scipy sparse CSR matrix in a portable data format, you can use scipy.sparse.save_npz() and scipy.sparse.load_npz() methods respectively. These methods are defined in sparse module and allow us to store/load the matrix in the compressed NPZ format, which is compatible as well as portable format.

To use these methods, you need to import the sparse module first. Consider the below-given statement:

from scipy import sparse

Let us understand with the help of an example,

Example

In this below program, we are defining data and indices for the matrix, then creating a CSR matrix. That CSR matrix is being saved in compressed NPZ format. And then, we are loading the compressed CSR matrix in the matrix variable and printing it.

# Import sparse from scipy
from scipy import sparse

# Define data from CSR matrix
data = [1, 2, 3, 4, 5]
row_indices = [0, 0, 1, 2, 2]
col_indices = [1, 2, 0, 1, 3]

# Creating a sparse CSR matrix
matrix = sparse.csr_matrix((data, (row_indices, col_indices)), shape=(3, 4))

# Printing CSR Matrix
print("CSR Matrix is:")
print(matrix)

# Saving matrix
sparse.save_npz("matrix_file.npz", matrix)

print("Matrix is saved with the name matrix_file.npz\n")

# Loading matrix
print("Loading matrix....")
matrix = sparse.load_npz("matrix_file.npz")

# Display matrix_file.npz
print("Matrix (matrix_file.npz) is:")
print(matrix)

Output

CSR Matrix is:
  (0, 1)        1
  (0, 2)        2
  (1, 0)        3
  (2, 1)        4
  (2, 3)        5
Matrix is saved with the name matrix_file.npz

Loading matrix....
Matrix (matrix_file.npz) is:
  (0, 1)        1
  (0, 2)        2
  (1, 0)        3
  (2, 1)        4
  (2, 3)        5

Python SciPy Programs »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.