TExcelTAD
Home › Optimization › The Conjugate Gradient Method

The Conjugate Gradient Method

The conjugate gradient (CG) method minimizes a convex quadratic f(x)=12xTAx−bTxf(\mathbf{x}) = \frac{1}{2}\mathbf{x}^TA\mathbf{x} - \mathbf{b}^T\mathbf{x}, which is the same as solving Ax=bA\mathbf{x} = \mathbf{b} for symmetric positive definite AA. It needs only matrix-vector products, stores a few vectors, and in exact arithmetic finishes in at most nn steps. It is the workhorse for large sparse systems and the inner solver of Newton-CG.

Conjugate directions

Two nonzero vectors are AA-conjugate if piTApj=0\mathbf{p}_i^TA\mathbf{p}_j = 0. If you minimize ff exactly along nn 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 rk=b−Axk=−∇f(xk)\mathbf{r}_k = \mathbf{b} - A\mathbf{x}_k = -\nabla f(\mathbf{x}_k) and the previous direction, and a short recurrence makes it conjugate to all previous directions:

αk=rkTrkpkTApk,xk+1=xk+αkpk,rk+1=rk−αkApkβk=rk+1Trk+1rkTrk,pk+1=rk+1+βkpk\begin{aligned} \alpha_k &= \frac{\mathbf{r}_k^T\mathbf{r}_k}{\mathbf{p}_k^TA\mathbf{p}_k}, & \mathbf{x}_{k+1} &= \mathbf{x}_k + \alpha_k\mathbf{p}_k, & \mathbf{r}_{k+1} &= \mathbf{r}_k - \alpha_kA\mathbf{p}_k \\ \beta_k &= \frac{\mathbf{r}_{k+1}^T\mathbf{r}_{k+1}}{\mathbf{r}_k^T\mathbf{r}_k}, & \mathbf{p}_{k+1} &= \mathbf{r}_{k+1} + \beta_k\mathbf{p}_k \end{aligned}
python · try it yourself
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 nn steps. Its error shrinks at least like (κ−1κ+1)k\left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^k, which depends on κ\sqrt{\kappa} instead of κ\kappa as for gradient descent. Even better, if AA has only a few distinct eigenvalue clusters, CG converges in about that many steps.

python · try it yourself
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 M−1Ax=M−1bM^{-1}A\mathbf{x} = M^{-1}\mathbf{b} with a matrix M≈AM \approx A that is cheap to invert lowers the effective condition number. The simplest choice is the diagonal of AA (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 ∇2f p=−∇f\nabla^2 f\,\mathbf{p} = -\nabla f 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 (pT∇2f p≤0\mathbf{p}^T\nabla^2 f\,\mathbf{p} \le 0) it stops and returns the current direction. This is Newton-CG.

In software

  • scipy.sparse.linalg.cg (with an optional preconditioner M), and minimize(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 A=[2001]A = \begin{bmatrix} 2 & 0 \\ 0 & 1 \end{bmatrix}, are (1,1)(1, 1) and (1,−2)(1, -2) AA-conjugate?

Answer

Yes.

Solution

A(1,−2)T=(2,−2)A(1, -2)^T = (2, -2), and (1,1)⋅(2,−2)=0(1, 1) \cdot (2, -2) = 0. They are not orthogonal in the usual sense (1−2=−1≠01 - 2 = -1 \ne 0), but they are orthogonal in the AA inner product.

Exercise 2: Two clusters

A 1000×10001000 \times 1000 SPD matrix has only two distinct eigenvalues. In exact arithmetic, how many CG iterations solve Ax=bA\mathbf{x} = \mathbf{b}?

Answer

At most 2.

Solution

After kk steps CG's error is the smallest achievable with a degree-kk polynomial pp with p(0)=1p(0) = 1, applied to AA. The polynomial p(λ)=(1−λ/λ1)(1−λ/λ2)p(\lambda) = (1 - \lambda/\lambda_1)(1 - \lambda/\lambda_2) vanishes at both eigenvalues, so the error is zero after 2 steps.

Exercise 3: Jacobi preconditioning (code)

Solve Ax=bA\mathbf{x} = \mathbf{b} with A=DsBDsA = D_s B D_s (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
python · try it yourself
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 DsD_s scaling here, leaving the much better conditioned BB.

Test yourself

In exact arithmetic, CG solves an n×nn \times n SPD system in at most…

  1. 1 step
  2. nn steps
  3. n2n^2 steps
  4. κ\kappa steps

CG's convergence rate depends on…

  1. κ\kappa
  2. κ\sqrt{\kappa}
  3. n3n^3
  4. the starting point only

What does CG need from the matrix AA?

  1. Its inverse
  2. Its LU factorization
  3. Only products AvA\mathbf{v}
  4. Its eigenvalues