Gradient descent
Last updated
Searching a grid finds the bottom of the bowl for two numbers, but not for the millions in a neural network. Gradient descent does: stand anywhere, work out which way is downhill, take a small step, and repeat. This lesson derives the gradient of the squared-error loss, checks it, and trains linear regression with a loop you write yourself in NumPy. The same loop, with a different model inside, trains everything later in the course.
By the end of this lesson you can
- Derive and for the squared-error loss, and check them numerically
- Write the gradient descent update and a training loop in NumPy
- Read a loss curve, and recognise a learning rate that’s too large
Derive the gradient
Lesson 1.8 showed that the gradient points uphill, the steepest way, and that its opposite points downhill. To walk down the loss bowl, you need the gradient of
Call each error . The loss is a mean of , and by the chain rule (lesson 1.7), the derivative of is times the derivative of . That inner derivative is with respect to , and with respect to . So
In words: for , twice the mean error; for , twice the mean of each error times its input. If the line is too low, the errors are negative, both derivatives are negative, and stepping against them raises and .
A derivation is easy to get wrong, so check it against lesson 1.8's numerical derivative, which nudges each number a tiny amount each way:
The formula and the nudges agree: for and for , at the line , . Always check a gradient like this the first time you write it.
The update rule
Gradient descent takes a step against the gradient:
The arrow means "becomes". (the Greek letter eta) is the learning rate: how big a step to take, as a fraction of the gradient. In code it's lr. Where the bowl is steep the gradient is big and the steps are long; near the bottom the gradient shrinks towards zero, so the steps shrink too, and the walk settles.
Try it. Choose a start (click the map, or use the sliders) and take steps:
w = 35, b = 70: price = 35 × kg + 70, with loss 3375. The bottom, marked ×, is 19.03.
With learning rate 0.02 the ball heads quickly into the valley, then slides along it to the bottom. With 0.03 it zig-zags across the valley but still gets there. With 0.05 it blows up; step 5 says why.
The training loop
Training is the update rule in a loop. Each time round, four things happen, and every model in this course is trained by some version of them:
- Predict with the current numbers.
- Measure the errors (and the loss).
- Work out the gradient of the loss.
- Step each number against its gradient.
Drawn as a UML activity diagram (the filled dot is the start, the ringed dot the end, and the diamonds are where the flow joins and where it decides, with the condition for each way out in brackets):
Press Walk through it to follow the work round the chart, one stop at a time.
- Start: set every weight and the bias to 0.
- Predict every example with the current weights.
- Measure the errors and the loss.
- Work out the gradient of the loss.
- Step each weight against its gradient, scaled by the learning rate.
- If there are steps left, go back to 2; otherwise stop.
Starting from , , 1,000 steps arrive at , , with loss 19.03: the same line as np.polyfit in lesson 3.1. The printout shows how it got there: the loss was 9,022 after the first step and 132 after the third, then crept the rest of the way. That's typical: big gains early, slow progress near the bottom, as the gradient gets smaller.
Plotting the loss curve
The loss curve, the loss after each step, is the first thing to look at whenever a model trains:
The loss falls over a range of several hundredfold, so the plot uses a log scale (lesson 1.1) to show the whole fall. A healthy curve drops quickly, then flattens. A curve still falling at the end says "train longer"; one that bounces or rises says the learning rate is too big.
Wrong way: a learning rate that’s too big
A bigger learning rate sounds faster. Here's 0.1 instead of 0.02:
After one step the loss is 2.9 million, much worse than at the start. By step 200 it's , close to the largest number a float can hold; then it's inf, infinity, and then nan, "not a number", because the next step works out infinity minus infinity. Nothing raises an error. The training just quietly produces garbage.
What happened: the step was so big that it jumped right over the bottom of the valley to a point higher up the other side. There the gradient was bigger still, so the next jump was bigger again, and so on, further out each time. In the figure in step 2, it's the 0.05 button.
The fix is a smaller learning rate. There's no universal right value; it depends on how steep the bowl is (lesson 3.7 shows how to make that easier). The usual habit: try a few values, ten times apart (0.1, 0.01, 0.001), and watch the loss curve. And whenever you see nan in a loss, suspect the learning rate first.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Goodfellow, Bengio and Courville, Deep Learning, chapter 4: Numerical Computation: gradient-based optimisation and the learning rate (4.3)
- Prince, Understanding Deep Learning, MIT Press, 2023: chapter 6, Fitting models: gradient descent on linear regression, with the same pictures
- Ruder, An overview of gradient descent optimization algorithms, 2016: gradient descent and its variants, and the trouble with learning rates