Gradient descent
Find the bottom of a loss by walking downhill. The gradient says which way, the learning rate says how far, and a model learns a line.
FreeAbout 15 min
Rolling downhill
A model learns by making a number called its loss smaller. The loss measures how wrong the model's answers are, and it depends on the model's settings. Picture it as a landscape: the settings are where you stand, the loss is the height, and learning means walking down to the lowest point.
Start with the simplest landscape there is, the curve , whose lowest point is at . Press Step a few times, then try the three presets.
The small learning rate creeps down, the medium one overshoots the bottom and zig-zags in, and the large one overshoots further every time until the ball flies off. By the end of this lesson you'll be able to predict all three.
Which way is downhill?
The derivative is the slope of the curve at . If the slope is positive, the curve goes up to the right, so downhill is to the left; if it's negative, downhill is to the right. Either way, downhill is the direction of .
Definition (Gradient descent (one variable))
Pick a start and a learning rate . Then repeat
Each step moves against the slope, and moves further where the curve is steeper.
Theorem (A small enough step goes downhill)
If is differentiable near and , then for every small enough .
Proof
Let , the height after a step of size , so . By the chain rule, , which is negative. A negative derivative at means for all small enough , so .
End of proof.
The theorem doesn't say how small "small enough" is: that depends on how sharply the curve bends. The next step works it out exactly for .
Example (By hand)
For the slope is . Start at with :
The height falls from to to . These are the first steps of the "Small η" preset.
Exercise, level: Core
The learning rate
For one step is . Every step multiplies by the same number, so after steps
Proposition (When gradient descent on x² converges)
For , gradient descent on converges to the bottom exactly when .
Proof
Powers of a number shrink to exactly when . Here , and means , that is, .
End of proof.
The sign of decides how the ball moves:
| Learning rate | Each step multiplies by | What happens |
|---|---|---|
| a number between and | creeps in from one side | |
| lands on the bottom in one step | ||
| a number between and | overshoots and zig-zags in | |
| bounces between and forever | ||
| a number below | overshoots further every time: diverges |
The presets in the first step are (multiplies by ), (by ) and (by ). Go back and try and on the slider.
Exercise, level: Derivation
The gradient
A real loss depends on many settings at once. For a function of two variables, the slope depends on which way you walk.
Definition (Partial derivatives and the gradient)
The partial derivative is the derivative of with respect to , treating as a constant; is the same with the roles swapped. The gradient collects them into a vector:
For a function of variables, has components, one partial derivative each.
For example, has , so at the point the gradient is .
Theorem (Slope in any direction)
If has continuous partial derivatives, then walking from in the direction of a unit vector , the height changes at the rate . This is stated here without proof; it's proved in Calculus & Optimization for ML.
Corollary (The gradient points uphill)
If , the height rises fastest in the direction of , falls fastest in the direction of , and doesn't change in the directions perpendicular to it.
Proof
By lesson 1, , where is the angle between and the gradient. This is largest when ( along the gradient), smallest when ( against it), and when .
End of proof.
The directions where the height doesn't change run along the contour lines of , the curves of equal height. So the gradient always crosses contour lines at right angles.
Exercise, level: Core
Gradient descent in two dimensions
With many variables, the rule is the same with the gradient in place of the slope.
Definition (Gradient descent)
Pick a start and a learning rate . Then repeat
Here it is on a long, narrow valley, . The rings are contour lines, the arrow is the gradient, and the dashed ring shows where the next step lands. Try the presets.
Why does the medium preset zig-zag? The gradient is , so a step treats each coordinate on its own:
Across the valley, behaves like the steep curve from the last step: it zig-zags once and diverges once . Along the valley, shrinks by a factor of at least for any up to , so it crawls. The steepest direction limits the learning rate, and then the gentle direction takes forever. That's why machine learning rescales its inputs so that no direction is much steeper than the others.
Exercise, level: Core
Learning a line
Now a real model. Four data points are , , and . The model predicts , and learning means finding the slope and intercept that fit best.
Definition (Mean squared error)
The loss of the line is the average of the squared errors over the points:
To walk downhill we need its gradient. Write for the error at point . By the chain rule, the derivative of is times the derivative of , and changes by per unit of and by per unit of . So
Example (One step by hand)
Start with the flat line , . The errors are , so the loss is , and
With , the step gives and . The loss drops from to about in one step.
Here are the same four points and the same starting line. Press Step once to check the numbers above, then Play. The dashed lines are the errors .
Exercise, level: Derivation
In code
Here is the whole training loop in NumPy: compute the errors, the loss and the gradient, then step. Press Run:
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0])
y = np.array([1.0, 3.0, 2.0, 4.0])
w, b, eta = 0.0, 0.0, 0.1
losses = []
for step in range(200):
r = w * x + b - y # the errors
losses.append(np.mean(r ** 2)) # the loss L(w, b)
dw = 2 * np.mean(r * x) # dL/dw
db = 2 * np.mean(r) # dL/db
w, b = w - eta * dw, b - eta * db
loss = np.mean((w * x + b - y) ** 2)
print(f"after 1 step: loss {losses[1]:.2f}")
print(f"after 200 steps: w = {w:.3f}, b = {b:.3f}, loss = {loss:.3f}")
show(losses, title="Loss after each step")It prints a loss of after one step, as we found by hand, and , with loss after 200 steps. The chart shows the loss falling fast at first, then levelling off. Try eta = 0.3: the steps overshoot and the loss explodes.
For a line, there's also an exact formula for the best fit (least squares, in Linear Algebra for ML). NumPy's np.polyfit uses it, and gradient descent found the same line:
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0])
y = np.array([1.0, 3.0, 2.0, 4.0])
print(np.polyfit(x, y, 1)) # [slope, intercept]Where it's used in ML
Tip
Training a neural network is this same loop with millions or billions of settings instead of two. Each step computes the loss on a small batch of examples, finds the gradient with backpropagation (the chain rule, organised to run fast), and moves every weight a little against it. Better optimisers, such as momentum and Adam, still start from the gradient; they adjust the steps so that narrow valleys cost less time.
Exercise, level: Exam
Want the full story, with convergence proofs, Newton's method and Adam? It's all in Calculus & Optimization for ML.
or press Enter