How to do it…

Converting a matrix into its sparse form

Sparse matrices are built using the functions available in scipy.sparse.

In the following example, we will be using the function named csr_matrix to convert a given matrix into its sparse form.

  1. Import the relevant packages:
import numpy as np
from scipy import sparse
  1. Initialize a matrix:
A = np.array([[1,2,0],[0,0,3],[1,0,4]]) 
  1. Convert the initialized matrix into a sparse matrix:
sA = sparse.csr_matrix(A) 
  1. Check the output of the preceding sparse matrix initialization:
sA
<3x3 sparse matrix of type '<class 'numpy.int32'>' with 5 stored elements in Compressed Sparse Row format>

Note that the preceding output mentions that there are five stored elements, which is the same as having five non-zero elements within the initialized matrix. 

  1. Print the output of sA:
print(sA)
(0, 0) 1
(0, 1) 2
(1, 2) 3
(2, 0) 1
(2, 2) 4

The left-hand side of the preceding output indicates the row and column indices of the original matrix, where there is a non-zero element. The right-hand side of the preceding matrix provides the values of the elements located in the given indices. 

Thus, storing elements in this way would require much less space when the matrix is huge and a majority of the elements are zero.

Different ways of creating a sparse matrix

In the previous section, we looked into a function that creates sparse matrices, called, csr_matrix. csr_matrix stands for compressed sparse row matrix. Similar to a csr matrix, there are multiple other formats of sparse matrices. The following table gives a list of all the multiple formats of sparse matrices:

Bsr_matrix Block sparse row matrix
Coo_matrix Sparse matrix in coordinate format
Csc_matrix Compressed sparse column matrix
Csr_matrix Compressed sparse row matrix
Dia_matrix Sparse matrix with diagonal storage
Dok_matrix Dictionary of keys based sparse matrix
Lil_matrix Row-based linked list sparse matrix
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset