This is a quick tutorial on how to use scipy to work with sparse matrix types in python. To get started, you need to make sure that python, the scipy package, and the numpy package are installed on your computer. All of these, plus many more useful tools for scientific computation, can be easily installed by downloading and installing anaconda. Details for doing so can be found here: https://www.anaconda.com/.
First we will create a sparse matrix with $m$ rows and $n$ columns. The code snippet below shows us how to do so.
import scipy.sparse
import numpy
import scipy.sparse.linalg
m = 3
n = 3
sparse_matrix = scipy.sparse.lil_matrix((m,n))
This creates a sparse matrix sparse_matrix,
specifically a lil_matrix type matrix. Now we will
enter a few non-zero entries into the matrix. All other entries
will be $0$ by default.
sparse_matrix[0,0] = 1
sparse_matrix[0,1] = 1
sparse_matrix[1,1] = 2
sparse_matrix[2,1] = 1
sparse_matrix[2,2] = 3
print('sparse_matrix =\n',sparse_matrix.toarray())
sparse_matrix = [[1. 1. 0.] [0. 2. 0.] [0. 1. 3.]]
There are several different types of sparse matrices, each of them
serving different purposes. The lil_matrix data type
is useful for creating a sparse matrix and populating its entries
with data values. It is not very good for doing matrix-vector
operations.
As we said earlier, the lil_matrix type is
inefficient for doing matrix-vector operations or for solving
linear systems. We need to conver our matrix to a different type
that is efficient for such operations. The
csr_matrix data type is the one we desire.
We will now show how to convert a lil_matrix to a
csr_matrix.
sparse_matrix = sparse_matrix.tocsr()
This changes the sparse_matrix from the
lil_matrix type to the csr_matrix type,
and is now in a form that can be used to do more efficient matrix
operations with. As a final example, we will show how to solve the
matrix equation $$Ax = b$$ for $x$, where $A$ is our
sparse_matrix and $b$ is a given vector. We use the
numpy package to create our vector $b$ and the scipy.sparse.linalg
package to solve the system.
b = numpy.array([0,1,1])
x = scipy.sparse.linalg.spsolve(sparse_matrix, b)
print('x =',x)
x = [-0.5 0.5 0.16666667]
To learn more about the different types of sparse matrices, as well as anything else about the content in this tutorial or the scipy.sparse package, the documentation can be found at https://docs.scipy.org/doc/scipy/reference/sparse.html.