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
%matplotlib inline
import time
import numpy as np
import scipy.linalg as la
import scipy.sparse as sparse
import scipy.sparse.linalg as sla
from scipy.linalg import lapack
import matplotlib.pyplot as pltSparse 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.
n = 100
A = sparse.random(n, n, 0.01) + sparse.eye(n)
plt.spy(A)
plt.show()A = A.tocsc() # need to convert to CSC form first
LU = sla.splu(A)
LUThe 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.
x = np.random.randn(n)
b = A @ x
x2 = LU.solve(b)
print(np.linalg.norm(x2 - x))you can also use the sla.spsolve function, which wraps this factorization.
x2 = sla.spsolve(A, b)
print(np.linalg.norm(x2 - x))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.cgforAsymmetric and positive-definiteMINRES:
sla.minresforAsymmetricGMRES:
sla.gmresfor general squareALSQR:
sla.lsqrfor solving least squares problems
For example, we can use gmres with the same matrix we used for splu:
x2, exit = sla.gmres(A, b, atol=1e-8) # exit code: 0 if successful
print(np.linalg.norm(x2 - x))import time
x2 = np.empty_like(x)
t0 = time.time()
x2, exit = sla.gmres(A, b)
t1 = time.time()
print("Iterative: GMRES in {} sec.".format(t1 - t0))
t0 = time.time()
x2 = sla.spsolve(A, b)
t1 = time.time()
print("Direct: spsolve in {} sec.".format(t1 - t0))Sparse Direct vs. Iterative Methods¶
There are a couple of trade offs to consider when deciding whether to use sparse direct or iterative algorithms.
Are you going to be solving many linear systems with the same matrix
A? If so, you can produce a single factorization object usingsplu, and use it to solve many right-hand sides. Sparse direct probably makes more sense.Are you solving a single linear system? If so, then a single call to an iterative method probably makes mores sense.
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.
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.
ILUfact = sla.spilu(A)
ILUfactx = np.random.randn(n)
b = A @ x
x2 = LU.solve(b)
print(np.linalg.norm(x - x2))
x3 = ILUfact.solve(b)
print(np.linalg.norm(x - x3))You can construct a preconditioner using a LinearOperator around the ILU object’s solve method
M = sla.LinearOperator(
shape = A.shape,
matvec = lambda b: ILUfact.solve(b)
)x2, exit = sla.gmres(A, b, M=M) # exit code: 0 if successful
print(np.linalg.norm(x2 - x))t0 = time.time()
x2, exit = sla.gmres(A, b)
t1 = time.time()
print("GMRES in {:.3e} sec.".format(t1 - t0))
print(np.linalg.norm(x2 - x))
t0 = time.time()
x2, exit = sla.gmres(A, b, M=M)
t1 = time.time()
print("preconditioned GMRES in {:.3e} sec.".format(t1 - t0))
print(np.linalg.norm(x2 - x))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.
# works on square matrices
Afun = lambda X : np.sum(X, axis=0).reshape(1,-1).repeat(X.shape[0], axis=0)
m =10 # linear operator of size 10
A = sla.LinearOperator(
shape = (m,m),
matvec = Afun,
rmatvec = Afun,
matmat = Afun,
rmatmat = Afun,
dtype=np.float64
)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.
Lam, V = sla.eigsh(A, which='LM', k=4)Lamwe see there is one eigenvalue with a numerically non-zero value (10). Let’s take a look at the eigenvector
V[:,-1]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 in the eigenvector basis of : . Because x is Gaussian, the coefficients are themselves iid standard normal, so no direction is favored to start with. Multiplying by scales each coefficient by its eigenvalue:
so leans toward the eigenvectors with large . 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 more multiplications, the coefficient of is , so the ratio between the coefficients of a large and a small eigenvalue gets raised to the power . This is the power method, applied to a whole subspace at once. In the code below, the power argument plays the role of .
The algorithm (randomized range finder)¶
Draw a random
n x (k+p)matrixXwith iid standard normal entries.Compute
Y = A @ X.Compute a matrix
Qwhose columns are an orthonormal basis for the span of the columns ofY.(Optional power iteration) Repeat
powertimes: replaceQwith an orthonormal basis for the columns ofA @ 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:
def orth_svd(Y):
"""Orthonormal basis for the column span of Y, via the SVD."""
U, s, Vt = la.svd(Y, full_matrices=False)
return U
def orth_qr(Y):
"""
Orthonormal basis for the column span of Y, via a QR factorization.
"""
Q, R = la.qr(Y, mode='economic')
return QThe range finder itself is short. The orth argument lets us swap in either method for step 3.
def random_span_k(A, k, p=10, power=0, orth=orth_qr):
"""
Randomized range finder for a symmetric matrix A.
Returns Q, an n x (k+p) matrix with orthonormal columns whose span
approximately contains the top-k eigenvectors of A.
k : target rank
p : oversampling (number of extra random vectors)
power : number of power iterations
orth : function returning an orthonormal basis for the columns of a matrix
"""
m, n = A.shape
X = np.random.randn(n, k + p) # 1. random test matrix
Q = orth(A @ X) # 2-3. sample the range of A, then orthonormalize
for i in range(power): # 4. power iteration
Q = orth(A @ Q) # (for non-symmetric A, alternate A.T and A; see HMT Algorithm 4.4)
return QLet’s test this on a diagonal matrix with entries along the main diagonal. The eigenvectors are the standard basis vectors , so we know the top-k eigenvectors are the last k standard basis vectors.
n = 100
n_list = np.arange(n)
n_list[-10:] = 2 * n_list[-10:]
D = sparse.dia_matrix((n_list, [0]), shape=(n,n))
Dk = 5
p = 10
np.random.seed(0) # for reproducibility
Q = random_span_k(D, k, p)
Q.shape # n x (k+p)Both versions of orth produce an orthonormal basis for the same subspace, but the QR version is faster:
%timeit random_span_k(D, k, p, orth=orth_svd)
%timeit random_span_k(D, k, p, orth=orth_qr)Checking the subspace¶
To see how well the span of Q captures an eigenvector , we look at the length of the projection of onto that span, which is . This is 1 if lies in the span of Q, and 0 if 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.
lam, V = la.eigh(D.toarray()) # eigenvalues in ascending order, so the top k are the last k columns of V
def captured(Q, V):
"""Entry i is norm(Q.T @ V[:,i]): the length of the projection of eigenvector i onto span(Q)."""
return np.linalg.norm(V.T @ Q, axis=1)def format_captured_plot(ax):
ax.set_xlabel('eigenvector index $i$')
ax.set_ylabel('weight')
ax.set_ylim(0, 1.05)
ax.legend(loc='upper left')
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(captured(Q, V), label='power = 0')
format_captured_plot(ax)
plt.show()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 in D @ x is scaled by , 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.
powers = [0, 1, 4, 16, 64]
fig, ax = plt.subplots(figsize=(8, 8))
for power in powers:
Q = random_span_k(D, k, p, power=power)
ax.plot(captured(Q, V), label=f'power = {power}')
format_captured_plot(ax)
plt.show()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.
Form
B = Q.T @ (A @ Q). This costsk+pmore products withA.Compute the eigendecomposition
B = W @ diag(theta) @ W.Twith a dense solver. This is cheap becauseBis small.Then
A ≈ (Q @ W) @ diag(theta) @ (Q @ W).T, so thethetaare approximate eigenvalues ofA, and the columns ofQ @ Ware approximate eigenvectors. Keep thekwith the largest|theta|.
Keeping only those k eigenpairs gives a rank-k approximation of A.
def random_eigh_k(A, k, p=10, power=0):
"""
Approximate the k largest-magnitude eigenpairs of a symmetric matrix A.
Returns lam (shape (k,)) and V (shape (n, k)), like sla.eigsh.
"""
Q = random_span_k(A, k, p=p, power=power)
B = Q.T @ (A @ Q) # small (k+p) x (k+p) matrix
theta, W = la.eigh(B)
top = np.argsort(np.abs(theta))[-k:] # indices of the k largest |theta|, in ascending order
return theta[top], Q @ W[:, top]
print("exact :", lam[-k:])
for power in powers:
lam_k, V_k = random_eigh_k(D, k, p, power=power)
print(f"power = {power:2d}:", np.round(lam_k, 2))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:
Solve a random linear system using
spluSolve a random linear system using either
minresorgmres(which one should you use?)Compute the largest magnitude eigenvector using
eigsoreigsh(which one should you use?)
Find a non-square matrix and
Solve a random least squares problem using
lsqrCompute the largest singular vectors using
svds
## Your code here
Notebook Cell
fname = '1138_bus.mtx'
data = np.genfromtxt(fname, comments='%') # skip any rows that begin with `%`
data.shape
m, n = int(data[0,0]), int(data[0,1])
data = data[1:]
rows = data[:,0] - 1
cols = data[:,1] - 1
vals = data[:,2]
A = sparse.coo_matrix((vals, (rows, cols)), shape=(m,n))
A = A.tocsc()
ANotebook Cell
Direct method
Notebook Cell
LU = sla.splu(A)Notebook Cell
np.random.seed(0)
x = np.random.randn(n)
b = A @ x
x2 = LU.solve(b)
print(np.linalg.norm(x2 - x))Notebook Cell
Iterative method. matrix is not symmetric, so use GMRES
Notebook Cell
x3, exit_status = sla.gmres(A, b)
print(np.linalg.norm(x3 - x))Notebook Cell
GMRES is very imprecise here, try preconditioning
Notebook Cell
ILUfact = sla.spilu(A)
M = sla.LinearOperator(
shape = A.shape,
matvec = lambda b: ILUfact.solve(b)
)
x3, exit_status = sla.gmres(A, b, M=M)
print(np.linalg.norm(x3 - x))