Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Sparse Linear Algebra

Open in Colab

So far, we have seen how sparse matrices and linear operators can be used to speed up basic matrix-vector and matrix-matrix operations, and decrease the memory footprint of the representation of a linear map.

Just as there are special data types for sparse and structured matrices, there are specialized linear algebra routines which allow you to take advantage of sparsity and fast matrix-vector products.

Routines for sparse linear algebra are found in scipy.sparse.linalg, which we’ll import as sla

Sparse Direct Methods

This typically refers to producing a factorization of a sparse matrix for use in solving linear systems.

The thing to keep in mind is that many factorizations will generally be dense, even if the original matrix is sparse. E.g. eigenvalue decompositions, QR decomposition, SVD, etc. This means that if we compute a factorization, we are going to lose all the advantages we had from sparsity.

What we really want is a factorization where if A is sparse, the terms in the factorization are also sparse. The factorization where this is easiest to achieve is the LU decomposition. In general, the L and U terms will be more dense than A, and sometimes much more dense. However, we can seek a permuted version of the matrix A which will minimize the amount of “fill-in” which occurs. This is often done using “nested disection” algorithm, which is outside the scope of this course. If you ever need to do this explicitly, the METIS package is commonly used.

We’ll just use the function sla.splu (SParse LU) at a high level, which produces a factorization object that can be used to solve linear systems.

The resulting object stores the factors necessary to compute A = PLUQ (P permutes rows, and Q permutes columns). It is computed using the SuperLU library. Typically, you will just use the solve method on this object.

you can also use the sla.spsolve function, which wraps this factorization.

Sparse Iterative Methods

Sparse iterative methods are another class of methods you can use for solving linear systems built on Krylov subspaces. They only require matrix-vector products, and are ideally used with sparse matrices and fast linear operators. You can typically learn the theory behind these methods in a numerical linear algebra course - we’ll just talk about how to use them.

All these methods are meant to solve linear systems: find x so that A @ x = b, or least squares problems minimizing norm(A @ x - b)

You can find a list of options in the documentation for scipy.sparse.linalg. Here are some common options:

  • Conjugate Gradient: sla.cg for A symmetric and positive-definite

  • MINRES: sla.minres for A symmetric

  • GMRES: sla.gmres for general square A

  • LSQR: sla.lsqr for solving least squares problems

For example, we can use gmres with the same matrix we used for splu:

Sparse Direct vs. Iterative Methods

There are a couple of trade offs to consider when deciding whether to use sparse direct or iterative algorithms.

  1. Are you going to be solving many linear systems with the same matrix A? If so, you can produce a single factorization object using splu, and use it to solve many right-hand sides. Sparse direct probably makes more sense.

  2. Are you solving a single linear system? If so, then a single call to an iterative method probably makes mores sense.

  3. Are you using a fast linear operator that could be expressed as a dense matrix (e.g. sparse plus low-rank)? Alternatively, would the sparse LU decomposition turn dense because of fill-in? If so, then iterative methods probably make more sense.

  4. Do you have a really good preconditioner (see below)? Then iterative methods probably make more sense.

Preconditioning

The speed/effectiveness of iterative methods is often dependent on the existence of a good preconditioner. A preconditioner M for a matrix A is an “approximate inverse” i.e. M @ A is close to the identity. Note if we had an exact inverse, we’ve solved our problem already. What we want is to have a matrix M which is fast to apply (i.e. also sparse like A), which generally isn’t possible with an exact inverse.

Finding a good preconditioner is a huge field of research, and can be very domain-dependent. A general-purpose method to obtain a preconditioner is to use an Incomplete LU decomposition (this is an LU factorization that stops when the fill-in gets too large). You can obtain one using sla.spilu.

You can construct a preconditioner using a LinearOperator around the ILU object’s solve method

We get a higher-precision answer in about the same amount of time.

Eigenvalues and Eigenvectors

Computing a full eigenvalue decomposition of a sparse matrix or fast linear operator doesn’t typically make sense (see the the discussion for sparse direct methods). However, there are a lot of situations in which we want to compute the eigenvalue-eigenvector pairs for a handful of the largest (or smallest) eigenvalues.

scipy.sparse.linalg wraps ARPACK (ARnoldi PACKage), which uses Krylov subspace techniques (like the iterative methods) to compute eigenvalues/eigenvectors using matrix-vector multiplications. The relevant methods are sla.eigs (for general square matrices) and sla.eigsh (for symmetric/Hermitian matrices). There is also a sla.svds function for the SVD.

Let’s look at an example for a linear operator which acts as the matrix of all ones.

This operator is Hermitian, so we’ll use eigsh. By default, eigsh will compute the largest magnitude eigenvalues. You can change which eigenvalues you’re looking for using the which keyword argument, and the number of eigenvalues using the k argument. See the documentation for details.

we see there is one eigenvalue with a numerically non-zero value (10). Let’s take a look at the eigenvector

this is the vector with constant entries. This agrees with our understanding of the operator A, which can be expressed as the symmetric rank-1 outer product of the vector with 1s in every entry.

Randomized Linear Algebra

Over the past couple of decades, randomized linear algebra has matured into a practical toolkit with lots of applications. The standard reference is the survey by Halko, Martinsson, and Tropp (HMT), Finding Structure with Randomness (SIAM Review, 2011; preprint 2009): Link.

The core algorithm is only a few lines long, so we’ll implement it ourselves. (Library versions exist too: scipy.linalg.interpolative has randomized low-rank decompositions, and scikit-learn has sklearn.utils.extmath.randomized_svd.)

The goal

For simplicity, we’ll assume A is an n x n symmetric matrix, so it has an orthonormal basis of eigenvectors. The best rank-k approximation of A keeps the k largest-magnitude eigenvalues (and their eigenvectors) and sets the rest to 0. As in the previous section, we don’t want to compute a full eigendecomposition just to find those k eigenvectors. Instead, we want an algorithm that only uses products with A, so that A can be sparse or a LinearOperator.

The idea

Write a random vector xx in the eigenvector basis of AA: x=c1v1+c2v2+⋯+cnvnx = c_1 v_1 + c_2 v_2 + \dots + c_n v_n. Because x is Gaussian, the coefficients cic_i are themselves iid standard normal, so no direction is favored to start with. Multiplying by AA scales each coefficient by its eigenvalue:

Ax=λ1c1v1+λ2c2v2+⋯+λncnvnA x = \lambda_1 c_1 v_1 + \lambda_2 c_2 v_2 + \dots + \lambda_n c_n v_n

so AxAx leans toward the eigenvectors with large ∣λi∣|\lambda_i|. If we do this to several random vectors at once, i.e. compute Y = A @ X where X is a random n x (k+p) matrix, the span of the columns of Y approximately contains the top-k eigenvectors. The p extra columns (the oversampling parameter, typically 5 or 10) make it extremely unlikely that the random vectors happen to miss part of the top-k eigenspace.

Applying A ** q more than once strengthens the effect: after qq more multiplications, the coefficient of viv_i is λiq+1ci\lambda_i^{q+1} c_i, so the ratio between the coefficients of a large and a small eigenvalue gets raised to the power q+1q+1. This is the power method, applied to a whole subspace at once. In the code below, the power argument plays the role of qq.

The algorithm (randomized range finder)

  1. Draw a random n x (k+p) matrix X with iid standard normal entries.

  2. Compute Y = A @ X.

  3. Compute a matrix Q whose columns are an orthonormal basis for the span of the columns of Y.

  4. (Optional power iteration) Repeat power times: replace Q with an orthonormal basis for the columns of A @ Q.

The output Q is n x (k+p). It’s a basis for a slightly larger subspace that approximately contains the top-k eigenvectors. At the end of this section we’ll see how to use Q to get the k eigenvalues and eigenvectors themselves.

How good is the answer?

The guarantees are probabilistic. If you ran the algorithm once a second, you’d expect to wait around 50 years to see this bound fail even once.

Step 3 just needs some orthonormal basis for the columns of Y. Two options are the SVD (the left singular vectors U) and the QR factorization (the factor Q). The SVD also computes singular values and right singular vectors, which we don’t need, so QR is cheaper. Here are both:

The range finder itself is short. The orth argument lets us swap in either method for step 3.

Let’s test this on a diagonal n×nn\times n matrix with entries 0,1,…,n−11,2(n−10),2(n−9),…,2(n−1)0, 1, \dots, n-11, 2(n-10), 2(n-9),\dots, 2(n-1) along the main diagonal. The eigenvectors are the standard basis vectors e0,…,en−1e_0, \dots, e_{n-1}, so we know the top-k eigenvectors are the last k standard basis vectors.

Both versions of orth produce an orthonormal basis for the same subspace, but the QR version is faster:

Checking the subspace

To see how well the span of Q captures an eigenvector viv_i, we look at the length of the projection of viv_i onto that span, which is ∥QTvi∥\|Q^T v_i\|. This is 1 if viv_i lies in the span of Q, and 0 if viv_i is orthogonal to it. We can compute it for every eigenvector at once as the row norms of V.T @ Q. For our diagonal D, V is the identity, so this is just the norm of the ith row of Q.

The span of Q captures the large eigenvectors better than the small ones, but not by much. The curve rises gradually with i, because the coefficient of eie_i in D @ x is scaled by λi=i\lambda_i = i, and none of the top 5 eigenvectors is close to fully captured.

Power iterations

Now let’s add power iterations using the power keyword. Each one costs k+p more products with A (plus a QR factorization) and scales the coefficient of each eigenvector by its eigenvalue once more.

From the subspace to eigenvalues

Q is only a basis for a subspace. To finish, we find the best approximate eigenpairs inside that subspace (this is called the Rayleigh-Ritz method). If the span of Q contains the top eigenvectors, then A is well approximated by Q @ B @ Q.T, where B = Q.T @ A @ Q is a small (k+p) x (k+p) symmetric matrix.

  1. Form B = Q.T @ (A @ Q). This costs k+p more products with A.

  2. Compute the eigendecomposition B = W @ diag(theta) @ W.T with a dense solver. This is cheap because B is small.

  3. Then A ≈ (Q @ W) @ diag(theta) @ (Q @ W).T, so the theta are approximate eigenvalues of A, and the columns of Q @ W are approximate eigenvectors. Keep the k with the largest |theta|.

Keeping only those k eigenpairs gives a rank-k approximation of A.

With no power iterations, the eigenvalue estimates for this matrix are poor. They converge to the exact values as power grows, matching what we saw in the plot. In practice, you choose p and power based on how quickly the eigenvalues of your matrix decay and how much accuracy you need.

Exercises

Download a couple of test matrices from the UFlorida Sparse Matrix collection Link For, example, use mnist_test_norm_10NN Link which would probably be too large to store on your computer as a dense matrix.

For each square matrix:

  1. Solve a random linear system using splu

  2. Solve a random linear system using either minres or gmres (which one should you use?)

  3. Compute the largest magnitude eigenvector using eigs or eigsh (which one should you use?)

Find a non-square matrix and

  1. Solve a random least squares problem using lsqr

  2. Compute the largest singular vectors using svds

Notebook Cell
Notebook Cell

Direct method

Notebook Cell
Notebook Cell
Notebook Cell

Iterative method. matrix is not symmetric, so use GMRES

Notebook Cell
Notebook Cell

GMRES is very imprecise here, try preconditioning

Notebook Cell