The Conjugate Gradient Method
The conjugate gradient (CG) method minimizes a convex quadratic , which is the same as solving for symmetric positive definite . It needs only matrix-vector products, stores a few vectors, and in exact arithmetic finishes in at most steps. It is the workhorse for large sparse systems and the inner solver of Newton-CG.
Conjugate directions
Two nonzero vectors are -conjugate if . If you minimize exactly along mutually conjugate directions, one after another, you reach the minimum: each line search fixes one "coordinate" of the solution in the conjugate basis without disturbing the others. Gradient descent lacks this property, so its later steps undo earlier progress (the zig-zag).
The algorithm
CG builds each new direction from the current residual and the previous direction, and a short recurrence makes it conjugate to all previous directions:
import numpy as np
def cg(matvec, b, tol=1e-10, max_iter=None):
x = np.zeros_like(b); r = b.copy(); p = r.copy(); rr = r @ r
for k in range(max_iter or len(b)):
Ap = matvec(p)
alpha = rr / (p @ Ap)
x += alpha * p; r -= alpha * Ap
rr_new = r @ r
if np.sqrt(rr_new) < tol * np.linalg.norm(b):
return x, k + 1
p = r + (rr_new / rr) * p; rr = rr_new
return x, max_iter or len(b)
rng = np.random.default_rng(0)
M = rng.normal(size=(6, 6)); A = M @ M.T + 6 * np.eye(6); b = rng.normal(size=6)
x, k = cg(lambda v: A @ v, b)
print("iterations:", k, " residual below 1e-10:", bool(np.linalg.norm(A @ x - b) < 1e-10))
print("matches solve:", np.allclose(x, np.linalg.solve(A, b)))iterations: 6 residual below 1e-10: True
matches solve: True
Convergence depends on the spectrum
In practice CG is used as an iterative method and stopped long before steps. Its error shrinks at least like , which depends on instead of as for gradient descent. Even better, if has only a few distinct eigenvalue clusters, CG converges in about that many steps.
import numpy as np
def iterations_to(tol, A, b, method):
x = np.zeros_like(b); r = b - A @ x; p = r.copy()
for k in range(1, 100000):
if method == "gd":
x += (r @ r) / (r @ (A @ r)) * r # steepest descent, exact step
r = b - A @ x
else:
Ap = A @ p
a = (r @ r) / (p @ Ap); x += a * p; r_new = r - a * Ap
p = r_new + (r_new @ r_new) / (r @ r) * p; r = r_new
if np.linalg.norm(r) < tol * np.linalg.norm(b):
return k
n = 400
rng = np.random.default_rng(1)
b = rng.normal(size=n)
for kappa in (10, 100, 1000):
A = np.diag(np.linspace(1, kappa, n))
print(f"kappa={kappa:5d}: steepest descent {iterations_to(1e-6, A, b, 'gd'):6d} iters, CG {iterations_to(1e-6, A, b, 'cg'):4d} iters")kappa= 10: steepest descent 57 iters, CG 21 iters
kappa= 100: steepest descent 512 iters, CG 63 iters
kappa= 1000: steepest descent 5096 iters, CG 103 iters
Preconditioning
Solving with a matrix that is cheap to invert lowers the effective condition number. The simplest choice is the diagonal of (Jacobi); incomplete Cholesky and multigrid are stronger. Preconditioned CG is the standard way to solve the huge sparse SPD systems of finite-element simulations, graph Laplacians and Newton steps.
CG inside Newton
Newton's system can be solved approximately with CG using only Hessian-vector products, which automatic differentiation provides without forming the Hessian. Stopping CG early (truncated Newton) still gives a descent direction, and if CG meets negative curvature () it stops and returns the current direction. This is Newton-CG.
In software
scipy.sparse.linalg.cg(with an optional preconditionerM), andminimize(method="Newton-CG")/"trust-ncg".- Hessian-free optimization for neural networks and the natural-gradient solvers in RL (TRPO) use CG on Hessian- or Fisher-vector products.
Exercises
Exercise 1: Conjugacy
With , are and -conjugate?
Answer
Yes.
Solution
, and . They are not orthogonal in the usual sense (), but they are orthogonal in the inner product.
Exercise 2: Two clusters
A SPD matrix has only two distinct eigenvalues. In exact arithmetic, how many CG iterations solve ?
Answer
At most 2.
Solution
After steps CG's error is the smallest achievable with a degree- polynomial with , applied to . The polynomial vanishes at both eigenvalues, so the error is zero after 2 steps.
Exercise 3: Jacobi preconditioning (code)
Solve with (badly scaled) using scipy.sparse.linalg.cg with and without the Jacobi preconditioner, and count iterations.
Answer
The preconditioner cuts the iteration count substantially.
Solution
import numpy as np
from scipy.sparse.linalg import cg, LinearOperator
rng = np.random.default_rng(2)
n = 200
B = np.diag(np.full(n, 2.0)) - np.diag(np.ones(n - 1), 1) - np.diag(np.ones(n - 1), -1) + 0.1 * np.eye(n)
Ds = np.diag(np.logspace(0, 2, n)); A = Ds @ B @ Ds; b = rng.normal(size=n)
counts = {}
for name, M in [("none", None), ("jacobi", LinearOperator((n, n), matvec=lambda v: v / np.diag(A)))]:
k = [0]
cg(A, b, M=M, rtol=1e-8, maxiter=5000, callback=lambda xk: k.__setitem__(0, k[0] + 1))
counts[name] = k[0]
print(counts){'none': 1314, 'jacobi': 62}
Jacobi scaling exactly undoes the scaling here, leaving the much better conditioned .
Test yourself
In exact arithmetic, CG solves an SPD system in at most…
- 1 step
- steps
- steps
- steps
CG's convergence rate depends on…
- the starting point only
What does CG need from the matrix ?
- Its inverse
- Its LU factorization
- Only products
- Its eigenvalues