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 .
- Prove the descent lemma for -smooth functions, including the guaranteed decrease for the step .
- Analyze gradient descent on quadratics exactly: the contraction factor , the best constant step and the role of .
- 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 , such as an empirical risk , by an iterative method . The first-order Taylor expansion says what a small step in direction does:
Any with is a descent direction: small enough steps along it lower . Among unit vectors, Cauchy–Schwarz gives , with equality exactly for . The negative gradient is the direction of steepest descent, and following it with a step size (or learning rate) is gradient descent.
Trust the linear approximation only near : add a penalty for moving far, with weight .
The model is a strictly convex quadratic in . Set its gradient to zero:
So each step jumps to the minimizer of a quadratic model whose curvature is in every direction. If that is at least , the largest curvature of , the model lies above everywhere, and minimizing it must lower . Making that precise is the next step.
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_TSmoothness and the descent lemma
Write the change in along the segment from to as an integral (the fundamental theorem of calculus) and subtract the linear term:
Cauchy–Schwarz and the Lipschitz gradient bound the integrand by , giving the quadratic upper bound:
Plug in the gradient step :
The bracket is positive for , so every such step lowers unless . The guaranteed decrease is largest at :
No convexity was used. Summing the last inequality over telescopes the left side, and gives
Even on a nonconvex landscape, gradient descent finds points with small gradient, at rate . 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.
The ravine has Hessian . Above which constant learning rate does gradient descent blow up from a generic start?
Show the answer
0.5
The -coordinate is multiplied by at every step, and exactly when with . The descent lemma's sufficient condition 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 with symmetric positive definite, eigenvalues and orthonormal eigenvectors . The minimizer is , and the ratio is the condition number.
The gradient is , so the error obeys a linear recursion:
In the eigenbasis the coordinates decouple, each shrinking (or growing) geometrically:
is convex in , so the maximum sits at an end of the spectrum: . It is below 1 exactly for . The best balances the two ends, :
To shrink the error by a factor takes iterations, and for large :
| iterations for at | at | ||
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 10 | 0.818 | 69 | 132 |
| 40 (the ravine) | 0.951 | 277 | 546 |
| 100 | 0.980 | 691 | 1,375 |
| 0.9998 | 69,078 | 138,149 |
Choosing the step: line search
The analysis says "use ", but is rarely known, and a global 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: . For the quadratic above it has a closed form, with , 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.
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 xEach 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 .
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 in is , 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 , is the same factor that the best constant step achieves.
Backtracking line search with and is applied to an -smooth starting from . Which outcome is impossible?
- The first trial step is accepted
- The accepted step is larger than
- The search halves the step forever without ever accepting one, at a point with
- 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
Every satisfies the Armijo condition with , so after at most halvings a step is accepted. Steps above 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, (often relative to ), a small relative decrease of over several iterations, or a budget of iterations or time. For a -strongly convex the gradient is a certificate: and . 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 examples, one gradient costs about per-example gradients: arithmetic for a linear model with features, and for a neural network a backward pass of backpropagation costing a small constant multiple of the forward pass. With about iterations, gradient descent on a strongly convex linear model (ridge regression, say) costs . The factor in every step is what Stochastic Gradient Descent removes.
| Assumption on (all -smooth, ) | Guarantee after steps | Steps for accuracy |
|---|---|---|
| bounded below (nonconvex) | for | |
| convex | ||
| -strongly convex |
Key takeaways
- The negative gradient is the steepest-descent direction in the Euclidean norm, and minimizes a quadratic model of curvature around .
- Descent lemma: for -smooth , . Any decreases ; guarantees , which gives even without convexity.
- On a quadratic the error contracts by per step; the best constant step gives , about iterations. Ill-conditioning, not dimension, is what makes gradient descent slow.
- Backtracking (Armijo) line search accepts a step once drops by ; it always terminates and matches the guarantee, up to a constant factor, without knowing .
- Each iteration costs a full gradient, for a linear model on 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.
Why is the direction of steepest descent at , in the Euclidean norm?
- Because it always points to the minimizer of
- Because is convex
- Because it minimizes the directional derivative over unit vectors , by Cauchy–Schwarz
- Because it is the only direction along which decreases
Show the answer
C. Because it minimizes the directional derivative over unit vectors , by Cauchy–Schwarz
The first-order change of along a unit direction is , with equality only at . It is a local statement: in another norm the steepest direction changes, and it need not point at the minimizer.
is -smooth with , and . What does the descent lemma guarantee for one step with ?
- exactly
- Nothing, unless is convex
Show the answer
A.
With the decrease is at least . It is a lower bound on the decrease: the true decrease can be larger, and no convexity is needed.
Gradient descent with the best constant step runs on a strongly convex quadratic with condition number . By what factor does the distance to the minimizer shrink per iteration, in the worst case?
- , independent of
Show the answer
C.
With both ends of the spectrum shrink by . That means about 691 iterations for a millionfold reduction: the cost of ill-conditioning.
You multiply your loss by 10 (same minimizer) and keep the learning rate that used to work. What happens to gradient descent?
- Nothing: the minimizer is unchanged, so the iterates are too
- The steps become 10 times longer, so a previously stable learning rate may now diverge
- It converges 10 times faster, with no risk
- 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 by 10 scales its gradient, and , by 10. Stability needs , so the safe range shrinks tenfold. Gradient descent is not invariant to rescaling of or of the coordinates, unlike Newton's method, which is why step sizes must be retuned when a loss is rescaled.
Go deeper
- Convergence Rates of Gradient Descent · Smoothness, strong convexity, condition numbers and linear rates.
- Momentum & Nesterov Acceleration · Heavy-ball momentum and the optimal first-order rate.
- Nonconvex Optimization & Saddle Points · Stationary points, escaping saddles and benign landscapes.
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.