Gradient Descent
To minimize a function you can't solve in closed form, walk downhill. Turn a direction and watch the slope trace a cosine, steer descent across a narrow valley, compare convex and nonconvex landscapes against Newton's method, sample mini-batches, and see why the small eigenvalues of a quadratic set the speed of learning.
Follows S. Boyd and L. Vandenberghe, Convex Optimization (Cambridge University Press, 2004; free online), Chapter 9, and I. Goodfellow, Y. Bengio and A. Courville, Deep Learning (MIT Press, 2016), Chapter 8, for momentum and stochastic gradients. The questions and examples are written for this page. Gradient descent is the explicit Euler scheme for the gradient flows of the Gradient Flows page; its uses in machine learning are on the Neural Networks page. For how this subject connects to the others, see the roadmap.
Gradient descent, momentum and mini-batches
Fitting a network means minimizing a loss over its weights. Gradient descent does it by walking downhill: from wherever you are, take a small step in the direction in which the loss decreases fastest. Which direction is that? The directional derivative answers it.
Start here: the directional derivative
Stand at a point on a surface . In one dimension you can only go left or right, but here you can head off in any direction. Pick a unit vector . The directional derivative is the slope of in that direction:
the second equality by the chain rule applied to . Since , where is the angle between and the gradient, the slope as you turn all the way round is a cosine wave of height :
- it is largest, , at : along the gradient, the steepest way up;
- it is zero at : along the contour line through ;
- it is smallest, , at : along , the steepest way down.
That last line is the whole reason gradient descent steps along . Try it below: drag the direction round and find the minimum of the curve on the right.
The idea
The update. To decrease a loss , step in its steepest downhill direction, , found above:
The gradient says which way to go, not how far: the learning rate is a choice. In machine learning is the average loss over the data, and computing its gradient through the network's layers is backpropagation.
Explore: descent on a valley
Worked example
, so . Start at .
With : the per-step factors in each coordinate, and .
and . So : the steep coordinate is solved in one step, and after that. Reaching takes steps.
With ?
Factors and . The second coordinate flips sign and grows by 1.5 each step: divergence, since .
What is the best fixed , and how fast is it?
Balance the two factors: , so and both have size . About 35 steps for three digits. Momentum improves this to roughly per step.
Check your understanding
Why step against the gradient rather than along it?
- is smallest at : the loss falls fastest opposite to the gradient.
- Along the gradient the step would be too long.Length is set by ; direction is the issue.
On an ill-conditioned quadratic () plain gradient descent is slow because:
- must be below for the steep direction, which makes progress in the flat direction tiny.
- The gradient points away from the minimum.It points downhill, just not at the minimum: it zigzags across the valley.
Doubling the batch size changes the mini-batch gradient's standard deviation by a factor of:
- That is the variance, not the standard deviation.
- : the noise comes from the data, not the batch.Averaging more independent samples reduces it.
Practice
The gradient of a quadraticThree lines
For with symmetric, show , find the minimizer, and rewrite gradient descent as .
Solution
by symmetry, and . The minimizer solves . Then ; subtract .
Momentum on a lineThe characteristic equation
Apply heavy ball to . Show that satisfies , and find when it converges for , .
Solution
Substitute . The roots of have product ; the iteration converges iff both have modulus below 1, which (Jury's test) means : . Momentum enlarges the stable range from to .
Convexity and convergence rates
How fast gradient descent converges, and whether it finds the best point at all, depends on the shape of the function. Three shapes cover most of what happens: strongly convex (fast and sure), convex but flat at the bottom (sure but slow), and nonconvex (fast, but maybe to the wrong place).
The idea
- Strongly convex: . Linear convergence: a fixed number of steps per extra digit, about .
- Convex and -smooth only: . Sublinear: ten times more steps for one more digit.
- Nonconvex, -smooth: . Gradients get small, so the iterates approach some stationary point, which can be a local minimum that is not global.
Explore
Worked example
, so , , , . Gradient descent with .
What does the strongly convex rate promise?
. To gain six digits, : steps.
What actually happens? (Do each coordinate separately.)
is multiplied by : gone after one step. is multiplied by per step, so : six digits after about 66 steps. The bound holds, with room to spare (it assumes the worst direction for every step).
Now take from with . Is the convergence linear?
. Near 0 the step shrinks with : from the next iterate is . The curvature vanishes at the minimum, so there is no , and decays like rather than geometrically: sublinear.
Check your understanding
Gradient descent on a convex function stops at a point with . Is it the global minimum?
- Yes: for convex , for every .
- Not necessarily; it could be a local minimum.That happens only without convexity.
On a plot of against , linear convergence looks like:
- A straight line sloping down.
- A curve that keeps flattening.That is sublinear convergence, like .
In the figure, Newton's method on the nonconvex function sometimes moves uphill. Why?
- Where , the Newton step points uphill: it heads for the stationary point of a downward-curving quadratic, a maximum.
- The step size is too large.Newton's method has no step size here; the direction itself is wrong.
Practice
The descent lemmaWhy the step is 1/L
If , show , and deduce that a gradient step with decreases by at least .
Solution
Taylor's theorem with remainder: for some on the segment, and the last term is at most . Put : . Summing these decreases over steps gives the nonconvex rate.
Linear rate from strong convexityOne line more
Strong convexity implies . Combine with the previous problem to get .
Solution
. Iterate.
Mini-batches and stochastic gradients
The loss is an average over the whole dataset, and so is its gradient. With millions of data points, computing it exactly for every step is too expensive. Instead, pick a small random batch, average its gradients, and step. The step is now random, and that randomness is the whole story of this module.
The idea
With data , , and a per-example loss ,
One full gradient step costs per-example gradients.
The consequence: with a fixed step size , SGD does not converge to the minimizer. It reaches the neighbourhood quickly and then jitters around it, at a scale set by and the noise. Decreasing over time (a schedule) or increasing shrinks the jitter.
Explore
Worked example
Fit to four points , with . Take .
Compute each and the full gradient.
Residuals ; gradients . Full gradient .
List the mini-batch gradients for all six batches of size 2.
, , , , , . They range from to .
Average them.
, the full gradient exactly. Unbiased, but any single step can be five times too short or nearly twice too long.
Check your understanding
The randomness in a mini-batch gradient comes from:
- Noise in the labels .The data are fixed once collected; full-batch descent on them is deterministic.
- Which examples happened to be drawn into the batch.
- Rounding errors.Those are tiny and not the point.
You quadruple the batch size. Per step, the gradient's standard deviation:
- halves, and each step costs four times as much.
- quarters, at four times the cost.That's the variance.
In the figure, with and a large step, the SGD path ends in a cloud around the minimizer rather than at it. To land closer you could:
- Decrease the step size over time, or use bigger batches.
- Run more steps with the same settings.The cloud has a fixed size for fixed α and |B|: more steps just wander inside it.
Practice
UnbiasednessProve it
Let be indices drawn independently and uniformly from . Show and (coordinatewise), where is computed per coordinate.
Solution
Each draw has and variance . is the average of independent copies: same mean, variance divided by .
EpochsCounting passes
With examples and , how many SGD steps make one pass over the data (an epoch)? How many full-gradient steps cost the same?
Solution
500 SGD steps per epoch; the same compute buys one full-gradient step. Early in training, 500 noisy steps make far more progress than one exact one, which is why mini-batches are standard.
Quadratics, spectra and power laws
On a quadratic loss, gradient descent splits into independent one-dimensional problems, one for each eigenvector of the Hessian. Each shrinks at its own rate, and the slow ones, with small eigenvalues, set the pace. When the eigenvalues follow a power law, so does the loss: .
The idea
The model. . Check the objects: are column vectors, is a symmetric matrix, so and are numbers and is a number. The gradient with respect to (the variable we choose; and are given) is , so the minimizer has .
Where comes from. For a linear model with squared loss, averaged over data, the Hessian is . Note the order: is a number (inner product), is a matrix (outer product). is the covariance of the inputs, so its eigenvalues measure how much the data vary in each direction.
Momentum and acceleration. With constant and , heavy ball behaves like gradient descent with step on the slow directions: a constant-factor gain, the same exponent . Schedules that vary with (built from orthogonal polynomials such as Chebyshev or Jacobi polynomials) can roughly double the exponent to on deterministic problems. With mini-batch noise these aggressive schedules can amplify the noise and diverge, which is an active research question.
Polynomials and contours. After steps of any such method the error is for a polynomial of degree with (for gradient descent, ). So the question “how fast can a method be?” becomes “how small can such a polynomial be on the spectrum?”. Functions of a matrix can be written with Cauchy's integral formula: for a closed curve in the complex plane enclosing all the eigenvalues,
which for diagonalizable is the scalar formula applied to each eigenvalue. Some recent work designs optimizers by choosing the contour instead of the polynomial, and complex numbers are natural there: the per-direction iteration of a momentum method is a matrix whose eigenvalues are complex when it oscillates.Explore
Worked example
, , , step .
Per-step factors and .
and : , then . The first direction is solved immediately.
The loss, and how many steps to reduce it by a factor of 1000.
. Need : . All of that time is spent on the flat direction.
Could a larger step help?
Only up to , where the steep factor is . At the flat factor is , about 175 steps, but the steep direction now oscillates with factor . The best fixed step balances the two at , giving for . With thousands of directions spread over many scales, there is no balancing point, and the power law takes over.
Check your understanding
For a column vector , the object is:
- The number .That is .
- A matrix of rank one.
“Spectral decomposition of the error vector ” means:
- Computing the eigenvalues of .A vector has no eigenvalues; the spectrum is 's.
- Writing as a combination of the eigenvectors of .
In the figure, raising the momentum from 0 to 0.9 shifts the heavy-ball curve but leaves its slope at about . Why?
- With constant , slow directions behave like gradient descent with step : a constant-factor speed-up, same exponent.
- Momentum has no effect on quadratics.It moves the curve by a factor of about ten.
Practice
From ν and κ to ζBuild a power law
Let and . Show that , so .
Solution
iff . The tail , and . This is how the figure builds its problem: for given and it sets .
Momentum per directionComplex eigenvalues
For one eigen-direction, heavy ball is . Write it as , and find when 's eigenvalues are complex. What is their modulus then?
Solution
with characteristic polynomial . The roots are complex when , and then both have modulus (their product is ). In that regime the coordinate spirals in at rate per step, whatever is: this is how momentum speeds up the flat directions.