Imagine you’re on a mountainside at night in thick fog, and you want to get down to the valley. You can’t see the valley. All you can feel is the slope of the ground under your feet.
A sensible plan: feel which way is downhill, take a step that way, and repeat. That’s gradient descent. It’s the algorithm that trains nearly every neural network, and it fits in one line.
The rule
We want to find the input that makes a function as small as possible. In machine learning, is the loss: a number that says how wrong the model is. Start anywhere, then repeat:
- is the slope at the current point (its derivative).
- (the Greek letter “eta”) is the learning rate: it scales the step. The step itself is slope, so steep ground gives a long step and flat ground gives a short one.
- The minus sign makes you go downhill. If the slope is positive, the function rises to the right, so you move left. If it’s negative, you move right.
What is here?
In the widget below, is a parameter: a number the model can change, such as a weight. The loss is a function of the parameters. The data is fixed. Training does not change the data; it searches for the parameter values that make the loss small on that data. With one parameter the loss is a curve, like the one in the widget. A real model has millions of parameters, but the idea is the same. You’ll see a concrete example with real data further down.
Worked example
Take , whose lowest point is at . Its slope is . Start at with :
| step | slope | change slope | new | |
|---|---|---|---|---|
| 1 | 3 | 6 | −0.6 | 2.4 |
| 2 | 2.4 | 4.8 | −0.48 | 1.92 |
| 3 | 1.92 | 3.84 | −0.384 | 1.536 |
Each step moves closer to 0, and the steps get smaller on their own, because the slope shrinks as you approach the bottom. Nobody has to tell the algorithm to slow down. (Here each step multiplies by 0.8.)
Go deeper Why is the negative gradient the best direction to move?
Near a point, a smooth function looks like a straight line: . Choose and the change in is about . That is never positive, so for a small enough the function goes down (unless the slope is exactly zero).
With many parameters, the change in for a small move in a unit direction is , where is the angle between and the gradient. This is smallest (most negative) when , so is the direction of steepest descent. Example: at a point where the gradient is , moving along lowers at a rate of about 20.1 per unit distance. Moving straight left, , lowers it at only 2. This is the “gradient points uphill” fact, and P1.C5 gives the angle argument behind it; P1.C6 looks at the slope in any direction.
“Steepest” is measured for a tiny move. It does not promise the best big step.
The learning rate decides everything
Try the three learning-rate buttons in the widget on the bowl , starting at . Each row below was checked against the widget’s own rules: it declares “converged” when the next step is smaller than , “diverged” when passes 50, and it stops after 60 steps.
| learning rate | what happens |
|---|---|
| 0.02 (too small) | Creeps toward the bottom. After 60 steps it is still at . |
| 0.1 (about right) | Glides smoothly down and converges (39 steps). |
| 0.3 | Faster: converges in 11 steps, still without changing sign. |
| exactly 0.5 | Lands exactly on the bottom in one step. This is a coincidence of this function, not a general rule. |
| 0.6 | Overshoots to the other side every step (zig-zag), but settles in 7 steps. |
| 0.9 | Zig-zags and settles slowly (49 steps). |
| 0.95 to just below 1 | Zig-zags and shrinks so slowly that the widget’s 60 steps aren’t enough. At 0.99 the ball is still at after 60 steps. |
| exactly 1 | Bounces between 3 and −3 forever. |
| above 1 (too big) | Each jump lands higher than the last. It diverges. At 1.05 the widget gives up after 30 steps. |
Diverging is the dramatic failure, but too-small is just as real a problem in practice: training that takes weeks instead of hours.
Go deeper Why exactly do 0.5 and 1 matter for f(x) = x²?
For the update is . So every step multiplies by the same factor :
- : , so shrinks toward 0 without changing sign (smooth).
- : , so the first step lands exactly on 0.
- : , so flips sign every step but still shrinks (zig-zag). Near , is close to , so the shrinking is very slow.
- : , so flips between and forever.
- : , so grows every step (divergence).
For a general function the safe range depends on how sharply it curves (its second derivative). For the curvature is 2, and the safe range is . A more sharply curved bowl needs a smaller . That idea returns in P1.F6 and P4.14.
Choosing a learning rate in practice
Real losses have no formula you can analyze, so people try values and watch the loss curve (below). A common habit is to try values about a factor of 10 apart, such as 1, 0.1, 0.01 and 0.001, for a short run each. Throw out any that make the loss blow up. Among the rest, pick one of the larger ones that still falls steadily. If a value works but is slow, try about 3 times larger. This is a rule of thumb from experience, not a theorem. Changing the rate during training (schedules) is the topic of P4.14.
More than one valley
Now switch the widget to Two valleys. This function has a shallow valley on the right and a deeper one on the left.
Start the ball at with the learning rate at 0.1. It settles in the right valley, at and a height of about −0.46, even though the left valley goes down to about −1.58 (at ). Drag the ball to and it finds the deeper one. The two valleys are separated by a hilltop at , where the slope is zero. With , starts on the left of the hilltop end in the left valley, and starts on the right of it end in the right valley.
Gradient descent only ever looks at the slope where it’s standing. So it is a local method: it finds a valley (a local minimum), not necessarily the lowest one (the global minimum). Where you start matters.
With a learning rate of 0.45, the first step from lands near the hilltop (at ), and the ball then ends up bouncing around in the left valley, because that valley is steep and needs below about 0.42. Big steps can hop over hills, but erratically: that’s not a reliable way to find the best valley.
Many parameters: the loss, averaged over data
Let’s see a loss that really comes from data. The model has one parameter and predicts . (Careful: here is the input data and is the parameter we adjust. In the widget above, the thing being adjusted was called .) We have two examples, and . The loss on one example is the squared error . The loss on the whole dataset is the average over the examples:
This is a curve in , a bowl. The data (the numbers 1, 2, 2, 6) are fixed constants inside it. Its slope is , which is zero at . Gradient descent from with :
| step | gradient | loss | |
|---|---|---|---|
| start | 0 | −14 | 20 |
| 1 | 1.4 | −7 | 5.3 |
| 2 | 2.1 | −3.5 | 1.625 |
| 3 | 2.45 | −1.75 | 0.706 |
The gradient −14 at the start is the average of the two examples’ own gradients, −4 and −24. Using every example for every step, as here, is called full-batch gradient descent. The gradient of an average is the average of the gradients, so every step has to compute a gradient for every example: the cost of one step grows with the number of examples. With millions of examples this is slow, and the fix (estimating the gradient from a small batch) is stochastic gradient descent, the next lesson (P1.F4).
With more parameters, the loss is a surface over . The slope becomes a list of partial derivatives, one per parameter: the gradient . One step moves every parameter at once, each against its own partial derivative. A neural network can have millions of parameters, so the gradient has millions of entries. Backpropagation (P4.8) is how they’re computed efficiently.
Bowls that are stretched
The animation shows gradient descent on , seen from above as contour lines (each oval is a set of points with the same loss). The bowl is ten times steeper in the direction than in the direction.
The numbers here are exact. The gradient is , so with each step does this:
- . The shallow direction shrinks smoothly, but only by 19% per step.
- . The steep direction overshoots the valley floor every step (the sign flips), and shrinks by only 10% per step.
We can’t fix this by raising : at the factor is exactly (bouncing forever), and above that diverges. So the steep direction caps the learning rate, and the shallow direction then makes slow progress. After 20 steps the ball has gone from to about , and the loss from 22.25 to 0.15. On a perfectly round bowl , one step with lands exactly on the bottom.
The ratio of steepest to shallowest curvature (here 10) is the bowl’s ill-conditioning. The bigger it is, the slower and more zig-zaggy plain gradient descent gets. Momentum (P1.F5) and Adam (P4.13) help with this kind of problem: momentum smooths out the zig-zag, and Adam gives each parameter its own step size.
Why feature scaling helps
Where do stretched bowls come from? One common source is features on very different scales. Suppose a model uses two features, and one is 10 times bigger than the other (say, income in thousands and age in decades). The loss changes about times faster when you wiggle the weight of the big feature. For example, take a linear model with squared-error loss and two features whose standard deviations are about 1 and about 10. On random data like that, the curvature along the weight of the smaller feature is about 2, and along the other about 209. The largest safe learning rate is then about 0.0096 on the raw features, and about 0.94 after standardizing each feature (subtracting its mean and dividing by its standard deviation). Rescaling features makes the bowl rounder, so a much bigger learning rate is safe. This is covered in P3.A11. Scaling only fixes the part of the stretching that comes from feature scale; it does not remove all of it.
Flat regions and saddle points
The step is slope, so where the ground is nearly flat, the step is tiny, even if you’re far from any minimum. Compare two bowls from with :
- : after 100 steps, . Done.
- (very flat near 0): after 100 steps, , and after 1000 steps, still .
A plateau like this makes the loss curve look stuck. It may not be stuck at a minimum, just crawling. Watch out: the widget’s “converged” rule only checks that the step is small. A small step means flat ground, which could be a minimum or just a plateau. (With and the same rule, the step falls below 0.0001 after 310 steps, while is not yet the minimum.)
A saddle point is a point where the gradient is zero but the surface curves up in some directions and down in others, like the middle of a horse saddle. Example: with the saddle at . Start at and gradient descent walks straight into the saddle and sits there, because the part of the gradient is exactly zero. But start at and grows by a factor 1.2 every step, so after about 38 steps the ball slides away downhill. P1.F2 has the full story.
The recipe in one place
Intuition
You’re in the fog again. The gradient is the direction that goes uphill most steeply. You step the opposite way. The learning rate is how much you scale the step: tiny strides are safe but slow; giant strides can carry you right across the valley and up the other side.
You stop when you’ve walked as long as you planned, or the ground feels flat, or you stop getting lower. Flat ground does not prove you’re at the very bottom.
Math
With many parameters , the slope becomes the gradient , the vector of partial derivatives, and the update is the same idea in every coordinate at once:
The gradient points in the direction of steepest increase, so subtracting it moves in the direction of steepest decrease. If is an average of per-example losses, , then .
Common ways to decide when to stop:
- the gradient’s size falls below a small threshold;
- the loss stops improving (or the step becomes tiny);
- a fixed number of steps runs out (the usual choice when training neural networks, often together with a check on held-out data).
Code
def gradient_descent(df, x, lr, steps):
for _ in range(steps):
x = x - lr * df(x)
return x
# Minimize f(x) = x**2, whose slope is 2x
print(gradient_descent(lambda x: 2 * x, x=3.0, lr=0.1, steps=50)) # ≈ 0In PyTorch, torch.optim.SGD(params, lr=0.1) does exactly this update for every parameter of a model.
The loss curve
The small chart under the widget plots the loss after every step. This loss curve is the first thing anyone looks at when training a model:
- steadily falling: it’s learning;
- falling, but very slowly: try a bigger learning rate (or you’re on a plateau);
- jumping up, or growing: the learning rate is too big;
- bouncing up and down: also a sign the rate is a bit too big.
You’ll read many of these in P4.22.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Now a version where the loss comes from data and the parameter is . It also checks the gradient formula numerically.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Go deeper Checking a gradient with finite differences
If you compute a gradient by hand (or write backpropagation code), how do you know it’s right? Compare it with a numerical estimate: nudge the parameter a tiny bit each way and see how the loss changes.
This is the central difference. Example: for at (true slope 3), gives an error of 0.01, and gives an error of about . Making much smaller does not help: with the error grows back to about , because the computer’s rounding errors get divided by a tiny number. A value like is a common choice.
Finite differences need two loss evaluations per parameter, so they are far too slow for training a large model. They are a debugging check only. P4.9 builds an autograd engine and uses this idea to test it.
Check your understanding
At the current point the slope is and the learning rate is . Which way does move, and by how much?
The change is −η · f′(x) = −0.5 × (−4) = +2. A negative slope means the function goes down to the right, so we move right.
Why do the steps get smaller as gradient descent approaches a minimum, even with a fixed learning rate?
The step is η × slope. Near the bottom of a valley the slope approaches zero, so the step does too.
Training loss goes down for a few steps, then starts climbing higher and higher. What is the most likely fix?
Loss that grows step after step is the signature of a learning rate that is too big: each step overshoots further than the last.
Gradient descent stopped at a point where the slope is zero. What can you be sure of?
Zero slope only means flat ground right here. It might be a local minimum (like the right valley in the widget), not the global one. A zero slope can also be a hilltop or a saddle point (more in P1.F2).
The loss falls smoothly but very slowly, never rising. After many steps it is still dropping at about the same slow rate. What is a sensible first thing to try?
A smooth, slow, steady fall is the sign of a learning rate that is too small, so try a larger one. A learning rate that is too big would make the loss jump or grow, and a loss that is still falling has not converged.
Exercises
- By hand: run two steps of gradient descent on from with .
Show answer
−1, then −0.5. - For the update multiplies by . For which does flip sign on every step, and what happens at exactly ? Use the Go deeper box.
Show answer
sign flips for every above 0.5, because the factor is then negative. There is no smallest such value: any just above 0.5 works. At exactly 0.5 the factor is 0 and the first step lands on 0. - In the widget’s two-valley mode with , find the starting point that separates “ends in the left valley” from “ends in the right valley”. What is special about the curve there?
Show answer
the hilltop near , where the slope is zero. Starts at 0.20 or below end in the left valley; 0.21 or above end in the right valley. - For the data example, compute the gradient of the average loss at from the two per-example gradients.
Show answer
the per-example gradients are and ; their average is . - Check the slope of at using a central difference with .
Show answer
, close to the true slope .
Next: in real training the loss is an average over millions of examples, which is far too slow to compute for every step. Stochastic gradient descent (P1.F4) fixes that by estimating the slope from a small batch.