Gradient LabStart the lesson

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 lesson

Step by step

Story

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.

Concept

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.

Build

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.

Key idea

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.

Build

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.

Build

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.

Insight

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.

Real life

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…

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