TExcelTAD
Home › Numerical Methods › The Conjugate Gradient Method

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 nn steps. It is the core of solvers for elliptic PDEs, finite element models and large least-squares problems.

Minimization view

For SPD AA, solving Ax=bA\mathbf{x} = \mathbf{b} is equivalent to minimizing the quadratic

ϕ(x)=12xTAx−bTx,∇ϕ=Ax−b=−r.\phi(\mathbf{x}) = \tfrac{1}{2}\mathbf{x}^TA\mathbf{x} - \mathbf{b}^T\mathbf{x}, \qquad \nabla\phi = A\mathbf{x} - \mathbf{b} = -\mathbf{r}.

Steepest descent moves along the residual r\mathbf{r}, but zigzags when AA is ill-conditioned. CG chooses search directions that are AA-conjugate (piTApj=0\mathbf{p}_i^TA\mathbf{p}_j = 0 for i≠ji \ne j), so that minimizing along a new direction never undoes the progress made along earlier ones. After kk steps, xk\mathbf{x}_k minimizes the AA-norm of the error over the Krylov subspace span⁡{b,Ab,…,Ak−1b}\operatorname{span}\{\mathbf{b}, A\mathbf{b}, \ldots, A^{k-1}\mathbf{b}\}.

The algorithm

python · try it yourself
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 kk iterations satisfies

∥ek∥A∥e0∥A≤2(κ−1κ+1)k,\frac{\lVert\mathbf{e}_k\rVert_A}{\lVert\mathbf{e}_0\rVert_A} \le 2\left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^k,

so the number of iterations for a fixed accuracy grows like κ\sqrt{\kappa}, compared with κ\kappa for steepest descent and Jacobi. For the 2D Laplacian κ≈4π2h2\kappa \approx \frac{4}{\pi^2h^2}, so CG needs O(h−1)=O(N)O(h^{-1}) = O(N) iterations.

python · try it yourself
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 NN doubles, proportional to κ\sqrt{\kappa}.

Eigenvalue clustering

The bound uses only κ\kappa, 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).

python · try it yourself
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); A may be a LinearOperator defined only by its action v↦Av\mathbf{v} \mapsto A\mathbf{v}, 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 κ=104\kappa = 10^4. Using the bound, roughly how many CG iterations reduce the error by 10−610^{-6}?

Answer

About 730.

Solution

κ−1κ+1=99101\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1} = \frac{99}{101}; 2(99101)k=10−62\left(\frac{99}{101}\right)^k = 10^{-6} gives k=ln⁡(5×10−7)ln⁡(99/101)≈725k = \frac{\ln(5 \times 10^{-7})}{\ln(99/101)} \approx 725. Steepest descent would need about κ2ln⁡(106)≈69,000\frac{\kappa}{2}\ln(10^6) \approx 69{,}000.

Exercise 2: Storage

What does CG store besides AA?

Answer

Four vectors: x\mathbf{x}, r\mathbf{r}, p\mathbf{p} and ApA\mathbf{p}.

Solution

Plus a few scalars. That is O(n)O(n) memory, independent of the number of iterations (unlike GMRES).

Exercise 3: Finite termination (code)

Run the lesson's CG on a random 20×2020 \times 20 SPD matrix (BTB+IB^TB + I, 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 1.3×10−51.3 \times 10^{-5}; by 25 iterations it is at rounding level.

Solution
python · try it yourself
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…

  1. any square matrix
  2. symmetric positive definite
  3. triangular
  4. diagonal only

The number of CG iterations for a fixed accuracy grows like…

  1. κ\kappa
  2. κ\sqrt{\kappa}
  3. log⁡κ\log\kappa
  4. n2n^2

Each CG iteration needs…

  1. a matrix factorization
  2. one matrix-vector product and a few vector operations
  3. the inverse of AA
  4. all previous search directions