Simple Algorithm
Machine Learning · Descent · 22 min

Gradient Descent

Following the slope downhill, and choosing the step size.

Gradient descent fits in two lines of code, yet it hides real questions. Why the negative gradient? How large a step is safe? And why does the same method solve one problem in ten steps and need ten thousand on another? This lesson derives the update, proves when it must decrease the loss, and shows how one number, the condition number, sets its speed.

What you’ll learn

  • Derive the gradient-descent update from the first-order Taylor expansion, and as the minimizer of a quadratic model of ff.
  • Prove the descent lemma for LL-smooth functions, including the guaranteed decrease ∥∇f∥2/(2L)\norm{\nabla f}^2/(2L) for the step 1/L1/L.
  • Analyze gradient descent on quadratics exactly: the contraction factor max⁡i∣1−ηλi∣\max_i\abs{1-\eta\lambda_i}, the best constant step 2/(μ+L)2/(\mu+L) and the role of κ=L/μ\kappa=L/\mu.
  • Implement backtracking (Armijo) line search and sound stopping rules, and count the cost of an iteration.

The steepest-descent direction

We want to minimize a differentiable f:Rd→Rf:\R^d\to\R, such as an empirical risk R^n(θ)\hat R_n(\boldsymbol\theta), by an iterative method xt+1=xt+η dt\mathbf x_{t+1}=\mathbf x_t+\eta\,\mathbf d_t. The first-order Taylor expansion says what a small step in direction d\mathbf d does:

f(x+ηd)=f(x)+η ∇f(x)⊤d+o(η).f(\mathbf x+\eta\mathbf d)=f(\mathbf x)+\eta\,\nabla f(\mathbf x)^\top\mathbf d+o(\eta).

Any d\mathbf d with ∇f(x)⊤d<0\nabla f(\mathbf x)^\top\mathbf d<0 is a descent direction: small enough steps along it lower ff. Among unit vectors, Cauchy–Schwarz gives ∇f(x)⊤d≥−∥∇f(x)∥\nabla f(\mathbf x)^\top\mathbf d\ge-\norm{\nabla f(\mathbf x)}, with equality exactly for d=−∇f(x)/∥∇f(x)∥\mathbf d=-\nabla f(\mathbf x)/\norm{\nabla f(\mathbf x)}. The negative gradient is the direction of steepest descent, and following it with a step size (or learning rate) η>0\eta>0 is gradient descent.

DerivationGradient descent minimizes a local model
  1. mt(y)=f(xt)+∇f(xt)⊤(y−xt)+12η∥y−xt∥2m_t(\mathbf y)=f(\mathbf x_t)+\nabla f(\mathbf x_t)^\top(\mathbf y-\mathbf x_t)+\frac1{2\eta}\norm{\mathbf y-\mathbf x_t}^2

    Trust the linear approximation only near xt\mathbf x_t: add a penalty for moving far, with weight 1/(2η)1/(2\eta).

  2. ∇f(xt)+1η(y−xt)=0⟹xt+1=xt−η ∇f(xt)\nabla f(\mathbf x_t)+\frac1\eta(\mathbf y-\mathbf x_t)=\mathbf 0\quad\Longrightarrow\quad\mathbf x_{t+1}=\mathbf x_t-\eta\,\nabla f(\mathbf x_t)

    The model is a strictly convex quadratic in y\mathbf y. Set its gradient to zero:

  3. 1η ≥ L⟹f(xt+1)≤mt(xt+1)≤mt(xt)=f(xt)\frac1\eta\ \ge\ L\quad\Longrightarrow\quad f(\mathbf x_{t+1})\le m_t(\mathbf x_{t+1})\le m_t(\mathbf x_t)=f(\mathbf x_t)

    So each step jumps to the minimizer of a quadratic model whose curvature is 1/η1/\eta in every direction. If that is at least LL, the largest curvature of ff, the model lies above ff everywhere, and minimizing it must lower ff. Making that precise is the next step.

text
GRADIENT-DESCENT(f, ∇f, x_0, η, ε, T)
  for t = 0, 1, ..., T-1:
      g ← ∇f(x_t)                 # one gradient evaluation: the dominant cost
      if ‖g‖ ≤ ε: return x_t       # approximately stationary
      x_{t+1} ← x_t - η g
  return x_T

Smoothness and the descent lemma

DerivationThe descent lemma
  1. f(y)−f(x)−∇f(x)⊤(y−x)=∫01(∇f(x+s(y−x))−∇f(x))⊤(y−x) dsf(\mathbf y)-f(\mathbf x)-\nabla f(\mathbf x)^\top(\mathbf y-\mathbf x)=\int_0^1\big(\nabla f(\mathbf x+s(\mathbf y-\mathbf x))-\nabla f(\mathbf x)\big)^\top(\mathbf y-\mathbf x)\,ds

    Write the change in ff along the segment from x\mathbf x to y\mathbf y as an integral (the fundamental theorem of calculus) and subtract the linear term:

  2. f(y)≤f(x)+∇f(x)⊤(y−x)+L2∥y−x∥2f(\mathbf y)\le f(\mathbf x)+\nabla f(\mathbf x)^\top(\mathbf y-\mathbf x)+\frac L2\norm{\mathbf y-\mathbf x}^2

    Cauchy–Schwarz and the Lipschitz gradient bound the integrand by Ls∥y−x∥2Ls\norm{\mathbf y-\mathbf x}^2, giving the quadratic upper bound:

  3. f(x−η∇f(x))≤f(x)−η(1−Lη2)∥∇f(x)∥2f\big(\mathbf x-\eta\nabla f(\mathbf x)\big)\le f(\mathbf x)-\eta\Big(1-\frac{L\eta}2\Big)\norm{\nabla f(\mathbf x)}^2

    Plug in the gradient step y=x−η∇f(x)\mathbf y=\mathbf x-\eta\nabla f(\mathbf x):

  4. η=1L:f(xt+1)≤f(xt)−12L∥∇f(xt)∥2\eta=\frac1L:\qquad f(\mathbf x_{t+1})\le f(\mathbf x_t)-\frac1{2L}\norm{\nabla f(\mathbf x_t)}^2

    The bracket is positive for 0<η<2/L0<\eta<2/L, so every such step lowers ff unless ∇f(x)=0\nabla f(\mathbf x)=\mathbf 0. The guaranteed decrease η(1−Lη/2)\eta(1-L\eta/2) is largest at η=1/L\eta=1/L:

No convexity was used. Summing the last inequality over t=0,…,T−1t=0,\dots,T-1 telescopes the left side, and f(xT)≥f⋆=inf⁡ff(\mathbf x_T)\ge f^\star=\inf f gives

min⁡t<T∥∇f(xt)∥2 ≤ 1T∑t<T∥∇f(xt)∥2 ≤ 2L(f(x0)−f⋆)T.\min_{t<T}\norm{\nabla f(\mathbf x_t)}^2\ \le\ \frac1T\sum_{t<T}\norm{\nabla f(\mathbf x_t)}^2\ \le\ \frac{2L\big(f(\mathbf x_0)-f^\star\big)}{T}.

Even on a nonconvex landscape, gradient descent finds points with small gradient, at rate 1/T1/T. A small gradient does not mean a minimum, though: it could be a saddle. The Convergence lessons Convergence Rates of Gradient Descent and Nonconvex Optimization & Saddle Points take both halves of that sentence further.

Predict before you look

The ravine f(x,y)=0.05x2+2y2f(x,y)=0.05x^2+2y^2 has Hessian diag⁡(0.1, 4)\operatorname{diag}(0.1,\,4). Above which constant learning rate does gradient descent blow up from a generic start?

Show the answer

0.5

The yy-coordinate is multiplied by 1−4η1-4\eta at every step, and ∣1−4η∣>1\abs{1-4\eta}>1 exactly when η>0.5=2/L\eta>0.5=2/L with L=4L=4. The descent lemma's sufficient condition η<2/L\eta<2/L is tight here: on a quadratic, the bound holds with equality along the top eigenvector.

Quadratics: the condition number

Near a strict minimum, every smooth function looks like a quadratic, so quadratics show what limits gradient descent. Take f(x)=12x⊤Ax−b⊤xf(\mathbf x)=\tfrac12\mathbf x^\top A\mathbf x-\mathbf b^\top\mathbf x with AA symmetric positive definite, eigenvalues μ=λmin⁡≤⋯≤λmax⁡=L\mu=\lambda_{\min}\le\dots\le\lambda_{\max}=L and orthonormal eigenvectors qi\mathbf q_i. The minimizer is x⋆=A−1b\mathbf x^\star=A^{-1}\mathbf b, and the ratio κ=L/μ\kappa=L/\mu is the condition number.

DerivationGradient descent on a quadratic, exactly
  1. et+1=et−ηAet=(I−ηA) et\mathbf e_{t+1}=\mathbf e_t-\eta A\mathbf e_t=(I-\eta A)\,\mathbf e_t

    The gradient is Ax−b=A(x−x⋆)A\mathbf x-\mathbf b=A(\mathbf x-\mathbf x^\star), so the error et=xt−x⋆\mathbf e_t=\mathbf x_t-\mathbf x^\star obeys a linear recursion:

  2. ci(t)=(1−ηλi)t ci(0)⟹∥et∥≤ρ(η)t∥e0∥,ρ(η)=max⁡i∣1−ηλi∣c_i(t)=(1-\eta\lambda_i)^t\,c_i(0)\qquad\Longrightarrow\qquad\norm{\mathbf e_t}\le\rho(\eta)^t\norm{\mathbf e_0},\quad\rho(\eta)=\max_i\abs{1-\eta\lambda_i}

    In the eigenbasis the coordinates ci=qi⊤ec_i=\mathbf q_i^\top\mathbf e decouple, each shrinking (or growing) geometrically:

  3. η⋆=2L+μ,ρ⋆=L−μL+μ=κ−1κ+1;with η=1L: ρ=1−1κ\eta^\star=\frac2{L+\mu},\qquad\rho^\star=\frac{L-\mu}{L+\mu}=\frac{\kappa-1}{\kappa+1};\qquad\text{with }\eta=\frac1L:\ \rho=1-\frac1\kappa

    ∣1−ηλ∣\abs{1-\eta\lambda} is convex in λ\lambda, so the maximum sits at an end of the spectrum: ρ(η)=max⁡(∣1−ημ∣,∣1−ηL∣)\rho(\eta)=\max(\abs{1-\eta\mu},\abs{1-\eta L}). It is below 1 exactly for 0<η<2/L0<\eta<2/L. The best η\eta balances the two ends, 1−ημ=ηL−11-\eta\mu=\eta L-1:

  4. t ≈ κ2 ln⁡1εt\ \approx\ \frac{\kappa}{2}\,\ln\frac1\varepsilon

    To shrink the error by a factor ε\varepsilon takes ln⁡(1/ε)/ln⁡(1/ρ⋆)\ln(1/\varepsilon)/\ln(1/\rho^\star) iterations, and ln⁡κ+1κ−1≈2κ\ln\frac{\kappa+1}{\kappa-1}\approx\frac2\kappa for large κ\kappa:

κ\kappaρ⋆=κ−1κ+1\rho^\star=\frac{\kappa-1}{\kappa+1}iterations for 10−610^{-6} at η⋆\eta^\starat η=1/L\eta=1/L
1011
100.81869132
40 (the ravine)0.951277546
1000.9806911,375
10410^40.999869,078138,149
The worst-case number of iterations grows linearly in κ\kappa. Features on very different scales, or strongly correlated features, make X⊤XX^\top X ill-conditioned, which is one reason to standardize inputs before training a linear model.

Choosing the step: line search

The analysis says "use η=1/L\eta=1/L", but LL is rarely known, and a global LL can be far more pessimistic than the curvature near the current point. Three common answers:

  • Tune a constant on a logarithmic grid, the usual choice in machine learning.
  • Exact line search: ηt=arg min⁡η>0f(xt−η∇f(xt))\eta_t=\argmin_{\eta>0}f(\mathbf x_t-\eta\nabla f(\mathbf x_t)). For the quadratic above it has a closed form, ηt=gt⊤gt/(gt⊤Agt)\eta_t=\mathbf g_t^\top\mathbf g_t/(\mathbf g_t^\top A\mathbf g_t) with gt=∇f(xt)\mathbf g_t=\nabla f(\mathbf x_t), but in general it is a costly one-dimensional problem per step.
  • Backtracking: start from a trial step and shrink it until the decrease is large enough. Cheap, and it adapts to the local curvature.
python
import numpy as np

def gd_backtracking(f, grad, x, eta0=1.0, beta=0.5, c=1e-4, tol=1e-6, max_iter=10_000):
    """Gradient descent with Armijo backtracking line search."""
    g0 = np.linalg.norm(grad(x))
    for t in range(max_iter):
        g = grad(x)
        if np.linalg.norm(g) <= tol * max(1.0, g0):    # relative stopping rule
            break
        eta, fx = eta0, f(x)
        while f(x - eta * g) > fx - c * eta * (g @ g):  # Armijo condition
            eta *= beta                                  # step too long: shrink it
        x = x - eta * g
    return x

Each trial costs one function evaluation. Practical codes often start each search from a slightly enlarged copy of the previous accepted step instead of a fixed η0\eta_0.

Exact line search is less of a free lunch than it sounds. Each accepted step leaves the new gradient orthogonal to the old one (the derivative of f(xt−ηgt)f(\mathbf x_t-\eta\mathbf g_t) in η\eta is −gt⊤gt+1-\mathbf g_t^\top\mathbf g_{t+1}, which vanishes at the optimum), so on an ill-conditioned quadratic the path zig-zags at right angles. Its worst case on quadratics, Kantorovich's bound f(xt+1)−f⋆≤(κ−1κ+1)2(f(xt)−f⋆)f(\mathbf x_{t+1})-f^\star\le\big(\frac{\kappa-1}{\kappa+1}\big)^2\big(f(\mathbf x_t)-f^\star\big), is the same factor that the best constant step achieves.

Check your understanding

Backtracking line search with c=10−4c=10^{-4} and β=12\beta=\tfrac12 is applied to an LL-smooth ff starting from η0=1\eta_0=1. Which outcome is impossible?

  1. The first trial step η=1\eta=1 is accepted
  2. The accepted step is larger than 1/L1/L
  3. The search halves the step forever without ever accepting one, at a point with ∇f(x)≠0\nabla f(\mathbf x)\ne\mathbf 0
  4. The accepted step changes from one iteration to the next
Show the answer

C. The search halves the step forever without ever accepting one, at a point with ∇f(x)≠0\nabla f(\mathbf x)\ne\mathbf 0

Every η≤1/L\eta\le1/L satisfies the Armijo condition with c≤12c\le\tfrac12, so after at most ⌈log⁡2(Lη0)⌉\lceil\log_2(L\eta_0)\rceil halvings a step is accepted. Steps above 1/L1/L can also pass, since the condition only asks for a sufficient decrease, and the accepted step adapts to the local curvature.

Stopping, cost and guarantees

When to stop. The usual tests are a small gradient, ∥∇f(xt)∥≤ε\norm{\nabla f(\mathbf x_t)}\le\varepsilon (often relative to ∥∇f(x0)∥\norm{\nabla f(\mathbf x_0)}), a small relative decrease of ff over several iterations, or a budget of iterations or time. For a μ\mu-strongly convex ff the gradient is a certificate: f(x)−f⋆≤∥∇f(x)∥2/(2μ)f(\mathbf x)-f^\star\le\norm{\nabla f(\mathbf x)}^2/(2\mu) and ∥x−x⋆∥≤∥∇f(x)∥/μ\norm{\mathbf x-\mathbf x^\star}\le\norm{\nabla f(\mathbf x)}/\mu. In machine learning the training loss is a means, not the goal: stopping early on a validation curve, early stopping, deliberately leaves the training loss above its minimum because it regularizes.

What an iteration costs. For an empirical risk over nn examples, one gradient costs about nn per-example gradients: O(nd)\order{nd} arithmetic for a linear model with dd features, and for a neural network a backward pass of backpropagation costing a small constant multiple of the forward pass. With about κln⁡(1/ε)\kappa\ln(1/\varepsilon) iterations, gradient descent on a strongly convex linear model (ridge regression, say) costs O(nd κln⁡(1/ε))\order{nd\,\kappa\ln(1/\varepsilon)}. The factor nn in every step is what Stochastic Gradient Descent removes.

Assumption on ff (all LL-smooth, η=1/L\eta=1/L)Guarantee after TT stepsSteps for accuracy ε\varepsilon
bounded below (nonconvex)min⁡t<T∥∇f(xt)∥2≤2L(f(x0)−f⋆)T\min_{t<T}\norm{\nabla f(\mathbf x_t)}^2\le\frac{2L(f(\mathbf x_0)-f^\star)}TO(1/ε2)\order{1/\varepsilon^2} for ∥∇f∥≤ε\norm{\nabla f}\le\varepsilon
convexf(xT)−f⋆≤L∥x0−x⋆∥22Tf(\mathbf x_T)-f^\star\le\frac{L\norm{\mathbf x_0-\mathbf x^\star}^2}{2T}O(1/ε)\order{1/\varepsilon}
μ\mu-strongly convexf(xT)−f⋆≤(1−1κ)T(f(x0)−f⋆)f(\mathbf x_T)-f^\star\le\big(1-\frac1\kappa\big)^T\big(f(\mathbf x_0)-f^\star\big)O(κln⁡(1/ε))\order{\kappa\ln(1/\varepsilon)}
The first row was proved above. The other two, and why the second row is not the best any first-order method can do, are proved in the Convergence lessons.

Key takeaways

  • The negative gradient is the steepest-descent direction in the Euclidean norm, and xt+1=xt−η∇f(xt)\mathbf x_{t+1}=\mathbf x_t-\eta\nabla f(\mathbf x_t) minimizes a quadratic model of curvature 1/η1/\eta around xt\mathbf x_t.
  • Descent lemma: for LL-smooth ff, f(x−η∇f)≤f(x)−η(1−Lη/2)∥∇f∥2f(\mathbf x-\eta\nabla f)\le f(\mathbf x)-\eta(1-L\eta/2)\norm{\nabla f}^2. Any η<2/L\eta<2/L decreases ff; η=1/L\eta=1/L guarantees ∥∇f∥2/(2L)\norm{\nabla f}^2/(2L), which gives min⁡t∥∇f(xt)∥2≤2L(f(x0)−f⋆)/T\min_t\norm{\nabla f(\mathbf x_t)}^2\le2L(f(\mathbf x_0)-f^\star)/T even without convexity.
  • On a quadratic the error contracts by max⁡i∣1−ηλi∣\max_i\abs{1-\eta\lambda_i} per step; the best constant step 2/(L+μ)2/(L+\mu) gives (κ−1)/(κ+1)(\kappa-1)/(\kappa+1), about κ2ln⁡(1/ε)\tfrac\kappa2\ln(1/\varepsilon) iterations. Ill-conditioning, not dimension, is what makes gradient descent slow.
  • Backtracking (Armijo) line search accepts a step once ff drops by c η∥∇f∥2c\,\eta\norm{\nabla f}^2; it always terminates and matches the 1/L1/L guarantee, up to a constant factor, without knowing LL.
  • Each iteration costs a full gradient, O(nd)\order{nd} for a linear model on nn examples, which motivates stochastic gradients.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why is −∇f(x)-\nabla f(\mathbf x) the direction of steepest descent at x\mathbf x, in the Euclidean norm?

  1. Because it always points to the minimizer of ff
  2. Because ff is convex
  3. Because it minimizes the directional derivative ∇f(x)⊤d\nabla f(\mathbf x)^\top\mathbf d over unit vectors d\mathbf d, by Cauchy–Schwarz
  4. Because it is the only direction along which ff decreases
Show the answer

C. Because it minimizes the directional derivative ∇f(x)⊤d\nabla f(\mathbf x)^\top\mathbf d over unit vectors d\mathbf d, by Cauchy–Schwarz

The first-order change of ff along a unit direction d\mathbf d is ∇f(x)⊤d≥−∥∇f(x)∥\nabla f(\mathbf x)^\top\mathbf d\ge-\norm{\nabla f(\mathbf x)}, with equality only at d=−∇f/∥∇f∥\mathbf d=-\nabla f/\norm{\nabla f}. It is a local statement: in another norm the steepest direction changes, and it need not point at the minimizer.

Question 2

ff is LL-smooth with L=10L=10, and ∥∇f(xt)∥=3\norm{\nabla f(\mathbf x_t)}=3. What does the descent lemma guarantee for one step with η=0.1\eta=0.1?

  1. f(xt+1)≤f(xt)−0.45f(\mathbf x_{t+1})\le f(\mathbf x_t)-0.45
  2. f(xt+1)≤f(xt)−0.9f(\mathbf x_{t+1})\le f(\mathbf x_t)-0.9
  3. f(xt+1)=f(xt)−0.45f(\mathbf x_{t+1})=f(\mathbf x_t)-0.45 exactly
  4. Nothing, unless ff is convex
Show the answer

A. f(xt+1)≤f(xt)−0.45f(\mathbf x_{t+1})\le f(\mathbf x_t)-0.45

With η=1/L\eta=1/L the decrease is at least ∥∇f∥2/(2L)=9/20=0.45\norm{\nabla f}^2/(2L)=9/20=0.45. It is a lower bound on the decrease: the true decrease can be larger, and no convexity is needed.

Question 3

Gradient descent with the best constant step runs on a strongly convex quadratic with condition number κ=100\kappa=100. By what factor does the distance to the minimizer shrink per iteration, in the worst case?

  1. 1/κ=0.011/\kappa=0.01
  2. 1−1/κ=0.91-1/\sqrt\kappa=0.9
  3. (κ−1)/(κ+1)≈0.980(\kappa-1)/(\kappa+1)\approx0.980
  4. 1/21/2, independent of κ\kappa
Show the answer

C. (κ−1)/(κ+1)≈0.980(\kappa-1)/(\kappa+1)\approx0.980

With η⋆=2/(L+μ)\eta^\star=2/(L+\mu) both ends of the spectrum shrink by (L−μ)/(L+μ)=99/101(L-\mu)/(L+\mu)=99/101. That means about 691 iterations for a millionfold reduction: the cost of ill-conditioning.

Question 4

You multiply your loss by 10 (same minimizer) and keep the learning rate that used to work. What happens to gradient descent?

  1. Nothing: the minimizer is unchanged, so the iterates are too
  2. The steps become 10 times longer, so a previously stable learning rate may now diverge
  3. It converges 10 times faster, with no risk
  4. The steps become 10 times shorter
Show the answer

B. The steps become 10 times longer, so a previously stable learning rate may now diverge

Scaling ff by 10 scales its gradient, and LL, by 10. Stability needs η<2/L\eta<2/L, so the safe range shrinks tenfold. Gradient descent is not invariant to rescaling of ff or of the coordinates, unlike Newton's method, which is why step sizes must be retuned when a loss is rescaled.

Go deeper

Further reading

  • A.-L. Cauchy, "Méthode générale pour la résolution des systèmes d'équations simultanées," Comptes Rendus Hebdomadaires des Séances de l'Académie des Sciences 25, 536–538 (1847).
  • L. Armijo, "Minimization of functions having Lipschitz continuous first partial derivatives," Pacific Journal of Mathematics 16(1), 1–3 (1966).
  • S. Boyd & L. Vandenberghe, Convex Optimization (Cambridge University Press, 2004), sections 9.1–9.4.
  • J. Nocedal & S. J. Wright, Numerical Optimization, 2nd ed. (Springer, 2006), chapter 3.