Lessons › Chapter 3: Regression and optimization
Gradient descent
Plot the loss for every possible value of a weight w and you get a valley. Training means finding the bottom. We start at a random spot, w = 7.5.
Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.
Start the interactive lessonStep by step
Tuning by hand is too slow
Leo has been adjusting the model’s numbers by hand. He wants the computer to walk downhill on its own.
Loss as a landscape
Plot the loss for every possible value of a weight w and you get a valley. Training means finding the bottom. We start at a random spot, w = 7.5.
Feel the slope
Imagine standing on a hill in thick fog. You can’t see the bottom, but you can feel which way the ground tilts. Here the slope is +1.75: it rises to the right, so downhill is to the left.
Step downhill
Take a step the opposite way to the slope: new w = 7.5 − 1.0 × 1.75 = 5.75. The error drops.
lr, the learning rate, sets how big each step is. Next lesson is all about it.
Repeat
Do it again and again. Near the bottom the slope gets gentler, so the steps shrink on their own: 5.75 → 4.88 → 4.44 → 4.22.
Arrive at the bottom
After a few more steps the slope is nearly 0 and w hardly moves: we have reached the minimum loss at w ≈ 4. The model is trained.
Two weights: a bowl
With two weights the valley is a bowl. The ball follows the negative gradient, the steepest way down, at every step. Real networks do this with millions of weights at once.
In real life: a hiker in thick fog
Gradient descent is a hiker in fog who can’t see the valley: feel the slope underfoot, take a step downhill, repeat. Every modern AI model, including the chat assistants you use, is trained with this same loop, just with billions of “directions” at once.
Quick check: Gradient descent updates a weight by…
- Adding the gradient
- Subtracting learning rate × gradient (correct)
- Setting it to zero
The gradient points uphill, so we subtract a small multiple of it to move downhill.
Pseudocode
w = 7.5 # start anywhere
step_size = 1.0 # the learning rate
repeat 10 times:
slope = slope of loss at w
w = w − step_size × slope # step downhill
show w and loss
# w ends near 4: the bottom of the valley
Key terms
- slope
- How steep something is. Positive goes up to the right, negative goes down.
Build it: Gradient descent from scratch (30 min, runs in your browser)
See the project