Conjugate Gradients
For symmetric positive definite systems, the conjugate gradient method (CG) is the iterative method of choice. It needs one matrix-vector product per iteration and a few vectors of storage, converges far faster than Jacobi or Gauss-Seidel, and in exact arithmetic would even terminate in at most steps. It is the core of solvers for elliptic PDEs, finite element models and large least-squares problems.
Minimization view
For SPD , solving is equivalent to minimizing the quadratic
Steepest descent moves along the residual , but zigzags when is ill-conditioned. CG chooses search directions that are -conjugate ( for ), so that minimizing along a new direction never undoes the progress made along earlier ones. After steps, minimizes the -norm of the error over the Krylov subspace .
The algorithm
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import cg
def conjugate_gradient(A, b, tol=1e-10, maxit=1000):
x = np.zeros_like(b)
r = b.copy(); p = r.copy(); rr = r @ r
history = [np.sqrt(rr)]
for k in range(maxit):
Ap = A @ p
alpha = rr / (p @ Ap) # exact line search along p
x += alpha * p
r -= alpha * Ap
rr_new = r @ r
history.append(np.sqrt(rr_new))
if np.sqrt(rr_new) < tol * np.linalg.norm(b):
break
p = r + (rr_new / rr) * p # next direction, A-conjugate to the previous ones
rr = rr_new
return x, history
N = 50 # 2500 unknowns, 2D Poisson
T = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N))
A = (sp.kron(sp.identity(N), T) + sp.kron(T, sp.identity(N))).tocsr()
b = np.ones(N * N)
x, hist = conjugate_gradient(A, b)
print(f"CG iterations: {len(hist) - 1}, final relative residual {hist[-1] / hist[0]:.1e}")
x_scipy, info = cg(A, b, rtol=1e-10)
print("matches scipy cg:", np.allclose(x, x_scipy, atol=1e-6), "| info:", info)CG iterations: 103, final relative residual 8.3e-11
matches scipy cg: True | info: 0
Convergence and conditioning
The error after iterations satisfies
so the number of iterations for a fixed accuracy grows like , compared with for steepest descent and Jacobi. For the 2D Laplacian , so CG needs iterations.
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import cg
for N in (25, 50, 100, 200):
T = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N))
A = (sp.kron(sp.identity(N), T) + sp.kron(T, sp.identity(N))).tocsr()
count = [0]
x, info = cg(A, np.ones(N * N), rtol=1e-8, callback=lambda xk: count.__setitem__(0, count[0] + 1))
kappa = (1 + np.cos(np.pi / (N + 1))) / (1 - np.cos(np.pi / (N + 1)))
print(f"N = {N:3d}: unknowns {N * N:6d}, kappa {kappa:9.0f}, CG iterations {count[0]:4d}")N = 25: unknowns 625, kappa 273, CG iterations 47
N = 50: unknowns 2500, kappa 1053, CG iterations 93
N = 100: unknowns 10000, kappa 4134, CG iterations 187
N = 200: unknowns 40000, kappa 16373, CG iterations 369
The iterations roughly double when doubles, proportional to .
Eigenvalue clustering
The bound uses only , but CG is often much faster: it effectively fits a polynomial to the eigenvalues. If the eigenvalues fall into a few tight clusters, CG converges in about as many iterations as there are clusters. Preconditioning aims to produce exactly that (Preconditioning and GMRES).
import numpy as np
from scipy.sparse.linalg import cg
rng = np.random.default_rng(111)
Q, _ = np.linalg.qr(rng.normal(size=(300, 300)))
spread = np.linspace(1, 1000, 300)
clustered = np.r_[np.full(100, 1.0), np.full(100, 10.0), np.full(100, 1000.0)] * (1 + 1e-6 * rng.normal(size=300))
b = rng.normal(size=300)
for name, ev in (("spread over [1, 1000]", spread), ("three tight clusters", clustered)):
A = Q @ np.diag(ev) @ Q.T
count = [0]
cg(A, b, rtol=1e-10, callback=lambda xk: count.__setitem__(0, count[0] + 1))
print(f"{name:22s}: kappa {ev.max() / ev.min():.0f}, CG iterations {count[0]}")spread over [1, 1000] : kappa 1000, CG iterations 116
three tight clusters : kappa 1000, CG iterations 8
In software
scipy.sparse.linalg.cg(A, b, rtol=..., M=preconditioner);Amay be aLinearOperatordefined only by its action , so the matrix need never be stored.- CG on the normal equations (CGLS, LSQR:
scipy.sparse.linalg.lsqr) solves large sparse least-squares problems; CG is also the inner solver of Newton-CG optimization.
Exercises
Exercise 1: Iteration estimate
A system has . Using the bound, roughly how many CG iterations reduce the error by ?
Answer
About 730.
Solution
; gives . Steepest descent would need about .
Exercise 2: Storage
What does CG store besides ?
Answer
Four vectors: , , and .
Solution
Plus a few scalars. That is memory, independent of the number of iterations (unlike GMRES).
Exercise 3: Finite termination (code)
Run the lesson's CG on a random SPD matrix (, seed 112) without a tolerance. In exact arithmetic it would finish in 20 iterations. How small is the residual after 20, and after a few more?
Answer
After 20 iterations the relative residual is only ; by 25 iterations it is at rounding level.
Solution
import numpy as np
rng = np.random.default_rng(112)
B = rng.normal(size=(20, 20)); A = B.T @ B + np.eye(20); b = rng.normal(size=20)
print(f"cond(A) = {np.linalg.cond(A):.1e}")
x = np.zeros(20); r = b.copy(); p = r.copy()
for k in range(1, 31):
Ap = A @ p; alpha = (r @ r) / (p @ Ap)
x += alpha * p; r_new = r - alpha * Ap
p = r_new + (r_new @ r_new) / (r @ r) * p; r = r_new
if k in (10, 20, 25, 30):
print(f"after {k} iterations: relative residual {np.linalg.norm(b - A @ x) / np.linalg.norm(b):.1e}")cond(A) = 7.2e+01
after 10 iterations: relative residual 4.5e-02
after 20 iterations: relative residual 1.3e-05
after 25 iterations: relative residual 1.3e-15
after 30 iterations: relative residual 1.2e-15
In floating point the conjugacy is gradually lost, so for large ill-conditioned problems CG is treated as an iterative method, not a direct one.
Test yourself
Conjugate gradients applies to matrices that are…
- any square matrix
- symmetric positive definite
- triangular
- diagonal only
The number of CG iterations for a fixed accuracy grows like…
Each CG iteration needs…
- a matrix factorization
- one matrix-vector product and a few vector operations
- the inverse of
- all previous search directions