ML fundamentals3 / 22

Lesson 3 · Learning from data

Gradient descent

The problem

Least squares found the best line in one step. That only works because a line's mean squared error has a formula for its lowest point. Most models have no such formula. The next lesson's model doesn't, and neither does any neural network.

So we need a way to train that works for any model. In Lesson 1 you trained by nudging one knob at a time: try w+1w + 1 and w−1w - 1, keep the better one. It was slow, and it could only land on whole numbers.

There's a better guide. The gradient of the loss says which way is uphill for every knob at once, and how steep it is. Step the other way and the loss goes down. Repeat, and you walk downhill to the bottom.

One weight, one step at a time

Start as small as possible. Two deliveries: 1 km in 4 minutes, and 2 km in 8 minutes. The model is minutes=w×km\text{minutes} = w \times \text{km}, with one parameter, ww.

Its loss is the mean squared error of the two misses:

L(w)=12[(w−4)2+(2w−8)2]=12[(w−4)2+4(w−4)2]=2.5 (w−4)2.\begin{aligned} L(w) &= \tfrac{1}{2}\left[(w - 4)^2 + (2w - 8)^2\right] \\ &= \tfrac{1}{2}\left[(w - 4)^2 + 4(w - 4)^2\right] \\ &= 2.5\,(w - 4)^2 . \end{aligned}

It's a bowl with its bottom at w=4w = 4. Its slope is L′(w)=5 (w−4)L'(w) = 5\,(w - 4). Left of the bottom the slope is negative, so downhill is to the right. Right of the bottom it's positive, so downhill is to the left.

So move ww against the slope, by a small multiple of it:

w←w−α L′(w).w \leftarrow w - \alpha \, L'(w) .

The arrow means "becomes". This rule is gradient descent. The number α\alpha (alpha) sets the size of each step. It's called the learning rate.

Worked example

Two steps of gradient descent, with α = 0.1

  1. Start at w=0w = 0: the model predicts 0 minutes for everything. The loss is 2.5×(0−4)2=402.5 \times (0 - 4)^2 = 40.

Now change the learning rate and watch the ball.

−20246810020406080100w (minutes per km)lossstep 0

Step 0: w = 0.00 · slope 5 × (w − 4) = −20.00 · loss 40.00

Next step: w ← 0.00 − 0.1 × −20.00 = 2.00

Each step multiplies the distance to the bottom by 1 − 0.1 × 5 = 0.50. Each step closes a good share of the gap, from one side.

Step 0 of 8
A ball rolling down the loss 2.5 (w − 4)². Each step moves it by −α × slope. The dashed line marks the bottom.

Things to notice:

  • Too small (0.04): each step closes only a fifth of the gap. The ball crawls.
  • 0.2 lands on the bottom in one step. 0.3 jumps past it and zig-zags in.
  • Too big (0.42): each jump lands further away than the last. The loss grows without limit. This is called blowing up, or diverging.
  • One number decides all of this: 1−5α1 - 5\alpha. Each step multiplies the distance to the bottom by it.

Predict first

The loss is (w − 4)². You start at w = 0 with learning rate 0.9. What happens?

The maths

A model usually has many parameters. Collect them in one vector, θ\boldsymbol\theta (theta). The gradient ∇L(θ)\nabla L(\boldsymbol\theta) holds the slope of the loss along each one. Gradient descent moves every parameter at once:

θ←θ−α ∇L(θ).\boldsymbol\theta \leftarrow \boldsymbol\theta - \alpha \, \nabla L(\boldsymbol\theta) .

Read it back with the figure. ∇L\nabla L points uphill, so −∇L-\nabla L points downhill. α\alpha scales the step. Near the bottom the gradient is small, so the steps are small. At the bottom it's zero, and the parameters stop moving.

The learning rate isn't learned. You choose it before training starts. A setting like that is a hyperparameter, as opposed to a parameter, which training sets. Later lessons meet more of them, and ways to choose them.

DeeperThe largest safe learning rateA bowl's curvature sets a hard limit: 2 divided by the curvature. · 3 min

In the Approximation lesson, a bowl's curvature kk was its second derivative: how fast its slope changes. For a bowl, the slope is kk times the signed distance to the bottom. Our bowl 2.5(w−4)22.5(w - 4)^2 has k=5k = 5, and its slope is 5(w−4)5(w - 4).

So one step does this to the distance dd from the bottom:

d←d−α k dd←(1−αk) dfactor out d\begin{aligned} d &\leftarrow d - \alpha \, k \, d \\ d &\leftarrow (1 - \alpha k)\, d && \text{factor out } d \end{aligned}

Every step multiplies the distance by the same factor, 1−αk1 - \alpha k.

  • Between 0 and 1: the ball approaches from one side. Close to 1 means a crawl.
  • Exactly 0, at α=1/k\alpha = 1/k: one step lands on the bottom. Here that's α=0.2\alpha = 0.2.
  • Between −1-1 and 0: it overshoots, but each jump is shorter. A zig-zag that settles.
  • Below −1-1, at α>2/k\alpha > 2/k: each jump is longer. It blows up.

So the largest safe learning rate is 2/k2/k: 0.4 for our bowl. A sharper bowl needs a smaller step. Real losses have different curvature in different directions, and the sharpest direction sets the limit. That's why the next figure has such a sharp edge.

Two parameters: the bowl of a line

Now the real model from Lessons 1 and 2: minutes=w×km+b\text{minutes} = w \times \text{km} + b on the ten light-traffic deliveries. There are two parameters, so the loss is a surface over the (w,b)(w, b) floor. Draw it as a contour map, with each ring joining lines of equal loss.

The gradient has two parts, one per parameter. With ri=yi−(wxi+b)r_i = y_i - (w x_i + b) for each delivery's residual, the partial derivatives are

∂L∂w=−2n∑i=1nxi ri,∂L∂b=−2n∑i=1nri.\frac{\partial L}{\partial w} = -\frac{2}{n}\sum_{i=1}^{n} x_i\, r_i , \qquad \frac{\partial L}{\partial b} = -\frac{2}{n}\sum_{i=1}^{n} r_i .

In words: deliveries the line under-predicts (positive rir_i) push bb up, and push ww up in proportion to their distance. Lesson 2's aside on the normal equations set these same two slopes to zero.

At the start, w=b=0w = b = 0, every residual is the whole delivery time. The gradient is (−130,−42.4)(-130, -42.4): both parameters should go up, ww much faster. Press play.

0246810120510w (minutes per km)b (minutes)α = 0.05
α = 0.05 (0 steps)× minimum

Step 0: w = 0.00, b = 0.00 · gradient (−130.0, −42.4)

Loss 488.15 (the best line has 3.64)

Above α = 0.0997 this loss blows up. Below it, it settles.

Step 0 of 150
Gradient descent on the ten deliveries, from w = 0, b = 0. The map is the loss over (w, b); × marks the best line. Pick a learning rate, then play or step.

Things to notice:

  • About right (0.05): the first step drops straight into the valley, at (6.50, 2.12). Then the path turns and follows the valley floor to the ×. After 150 steps the loss is about 3.7. The best line's is 3.64.
  • Too small (0.01): the path is smooth but slow. After 150 steps it's still far from the ×.
  • Near the edge (0.095): the path bounces from wall to wall across the valley, but the bounces shrink. It ends closest of all.
  • Too big (0.105): the bounces grow, and the path leaves the map. Even 0.1 diverges, slowly. The edge is at 0.0997, and there's nothing gradual about it.

The best learning rate is often a little below the point where training blows up. Practitioners find it by trying a few values, roughly ten times apart, and keeping the fastest one that doesn't diverge.

DeeperWhy long, narrow valleys are slow, and why scaling features helpsThe steep direction limits the step size. The flat direction then takes forever. · 3 min

The valley in the figure is long and thin. Its curvature is about 20.07 across the valley and about 0.45 along it. These are the eigenvalues of the loss's Hessian, as in the Approximation lesson.

The steep direction sets the limit: α<2/20.07≈0.0997\alpha < 2/20.07 \approx 0.0997. That's the edge you found. With α\alpha close to it, each step along the flat floor closes only α×0.45\alpha \times 0.45, about 4.4%, of the remaining gap. So the path needs about 100 steps to cover the floor, whatever α\alpha you pick.

Why is the valley tilted and thin? All distances are positive, between 0.6 and 5.7 km. So raising ww and lowering bb nearly cancel: the line before and after the change both pass near the average delivery. The two parameters fight each other.

The fix is to change the features, not the method. Subtract the average distance from every distance, then divide by its spread. Then ww and bb stop fighting, and the valley becomes a round bowl, with the same curvature in every direction. One learning rate suits both. That's called feature scaling, and the course comes back to it.

DigressionLeast squares has an exact answer. Why use gradient descent?Because most models don't, and because the exact answer gets expensive. · 1 min

For a linear model with the mean squared error, use least squares. It's exact and fast.

Gradient descent earns its place everywhere else. Logistic regression, in the next lesson, has no formula for its best weights. Neither do neural networks, with millions of weights. The normal equations also get expensive: their cost grows with the cube of the number of features.

Gradient descent only needs the gradient. Autograd computes that for any model you can write down. So the same few lines of code train a line, a logistic regression or a large language model.

Watching training: the loss curve

Training a model for real, you can't draw the loss surface. With more than two parameters, there's no map. What you can always draw is the loss after each step.

0123456010203040distance (km)minutes

Step 0 · loss 488.15

Line: minutes = 0.00 × km + 0.00 · learning rate 0.05

00.20.40.60.814006301000steploss (log scale)
train 488
Gradient descent at learning rate 0.05 on the ten deliveries. Top: the current line. Bottom: the loss after every step, on a log scale.

This plot of the loss against training steps is a loss curve. It's the first thing to look at when training anything.

Things to notice:

  • The first step does most of the work: the loss falls from 488 to 22. The line jumps from flat to steep.
  • After that, the curve flattens. The line slowly swings, getting less steep and starting higher.
  • The log scale lets you see both stages at once. On an ordinary scale, everything after step 1 looks flat.
  • After 200 steps the line is 3.94×km+10.753.94 \times \text{km} + 10.75, close to least squares' 3.91×km+10.853.91 \times \text{km} + 10.85.

A loss curve tells you what's wrong when training fails. A curve that falls and flattens is healthy. One that's barely moving says the learning rate is too small. One that shoots up says it's too big.

In PyTorch

Here is the same descent written by hand. It uses autograd for the gradient and does the update itself.

Gradient descent by hand
def descend_by_hand(lr: float = 0.05, steps: int = 200) -> tuple[float, float, list[float]]:
    """Gradient descent on minutes = w × km + b, with the update written out. Returns w, b and the losses."""
    km, minutes = ten_deliveries()  # shape (10,) each, float64
    w = torch.zeros((), dtype=km.dtype, requires_grad=True)  # start from the flat line at 0 minutes
    b = torch.zeros((), dtype=km.dtype, requires_grad=True)
    losses = []
    for _ in range(steps):
        loss = F.mse_loss(w * km + b, minutes)  # the mean squared error
        losses.append(loss.item())
        loss.backward()  # fills w.grad and b.grad
        with torch.no_grad():  # update the weights without recording it
            w -= lr * w.grad
            b -= lr * b.grad
        w.grad = None  # clear the gradients, or the next backward() adds to them
        b.grad = None
    return w.item(), b.item(), losses


w, b, losses = descend_by_hand()
print([round(v, 2) for v in losses[:5]])  # [488.15, 22.1, 21.28, 20.51, 19.76]: one big drop, then slow
print(round(w, 2), round(b, 2))  # 3.94 10.75: close to least squares (3.91, 10.85)
[488.15, 22.1, 21.28, 20.51, 19.76]
3.94 10.75

The losses match the figure step for step. What each line does:

  • F.mse_loss(pred, target) is the mean squared error between two tensors of the same shape. F is torch.nn.functional.
  • loss.backward() fills w.grad and b.grad with ∂L/∂w\partial L / \partial w and ∂L/∂b\partial L / \partial b.
  • The update runs inside torch.no_grad(), so autograd doesn't record it.
  • w.grad = None clears the gradient. Without it, the next backward() would add to the old one (gradient accumulation).

Writing the update by hand gets tedious with many parameters. PyTorch's optimiser objects do it for you. torch.optim.SGD holds a list of parameters and applies θ←θ−α∇L\theta \leftarrow \theta - \alpha \nabla L to all of them:

The same descent with nn.Linear and torch.optim.SGD
def descend_with_sgd(lr: float = 0.05, steps: int = 200) -> tuple[nn.Linear, list[float]]:
    """The same descent with nn.Linear, nn.MSELoss and torch.optim.SGD."""
    km, minutes = ten_deliveries()
    x = km.unsqueeze(1)  # one row per delivery, one column per feature   shape (10, 1)
    y = minutes.unsqueeze(1)  # match the model's output                       shape (10, 1)

    model = nn.Linear(1, 1, dtype=x.dtype)  # weight w (1, 1) and bias b (1,)
    with torch.no_grad():
        model.weight.zero_()  # start from w = 0 and b = 0, as above
        model.bias.zero_()
    loss_fn = nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=lr)

    losses = []
    for _ in range(steps):
        optimizer.zero_grad()  # 1. clear the old gradients
        loss = loss_fn(model(x), y)  # 2. predict and score
        loss.backward()  # 3. gradients of the loss
        optimizer.step()  # 4. w ← w − lr × w.grad, for every parameter
        losses.append(loss.item())
    return model, losses


model, sgd_losses = descend_with_sgd()
print(model.weight.item(), model.bias.item())  # the same w and b as the loop by hand
  • nn.Linear(1, 1) holds ww (its weight) and bb (its bias). model.parameters() hands both to the optimiser.
  • Every step is the same four lines: optimizer.zero_grad() clears the gradients, the forward pass and loss, loss.backward(), then optimizer.step().
  • nn.MSELoss() is the layer form of F.mse_loss. They compute the same number.

The weights it finds are exactly the hand loop's. The Neural-net foundations course uses this same loop for networks with thousands of weights, and swaps in better optimisers.

A few examples per step

Every step so far used every delivery. The gradient is an average over all of them, so one step costs one pass through the data. With 300 deliveries that's fine. With 10 million, each step is slow, and you'd want thousands of steps.

The fix is to estimate the gradient from a few deliveries. Pick 32 at random, and average their gradients. It's a sample mean, so it's a noisy estimate of the full gradient. But it costs 32 deliveries' work, not 10 million.

  • A small random group of examples used for one step is a minibatch, or batch.
  • Gradient descent with random minibatches is stochastic gradient descent (SGD). "Stochastic" means random. Strictly, SGD uses one example per step. In practice people say SGD for any batch size.
  • One pass through all the training data is an epoch. Each epoch, shuffle the data and deal it out in batches, so every example is used once.

Predict first

300 deliveries, batches of 32. How many steps are in one epoch?

Here is the line fitted to all 300 deliveries three ways, from the same start with the same learning rate, 0.005. Step through the epochs.

024681005101520w (minutes per km)b (minutes)Full batch (300)Minibatch (32)SGD (1)
Full batch (300) (0 steps)Minibatch (32) (0 steps)SGD (1) (0 steps)× minimum
After 0 epochsstepsloss
Full batch (300)01008.1
Minibatch (32)01008.1
SGD (1)01008.1

The best line has loss 71.3. Learning rate 0.005 for all three.

Epoch 0 of 20
Full batch, minibatches of 32, and single deliveries, on the loss of all 300 deliveries. Each epoch is one pass through the data: 1, 10 or 300 steps.

Things to notice:

  • Per epoch, small batches get further. After 5 epochs the full-batch path has taken 5 steps (loss 328). Minibatches have taken 50 (loss 106). Single deliveries have taken 1,500 (loss 74). The best line's loss is 71.3. All three did the same amount of work.
  • Small batches wander. Each single-delivery step follows one delivery's opinion, so the path jitters. Near the bottom it never quite settles, but it stays close.
  • Minibatches sit in between. Their path is a little rough, and they're the usual choice. A batch of 32 also suits the hardware: a GPU often handles 32 examples about as fast as 1.

The full-batch path could use a bigger learning rate here, up to about 0.075. Each step would still cost a whole pass through the data.

There's a second way to see SGD. Fix w=0w = 0, and use one delivery per step. The update for bb becomes b←b+2α (yi−b)b \leftarrow b + 2\alpha\,(y_i - b). That's the incremental mean from the Expectation lesson, with step size 2α2\alpha. So SGD keeps a running average of what each example asks for.

In PyTorch: minibatches

PyTorch deals the batches for you. A TensorDataset pairs the feature rows with their labels, and a DataLoader shuffles them each epoch and serves them in batches. The Neural-net foundations course covers both properly (Dataset and DataLoader).

This fits Lesson 2's model, with distance and traffic, on all 300 deliveries:

Minibatch SGD with a DataLoader
def minibatch_sgd(
    batch_size: int = 32, lr: float = 0.01, epochs: int = 100, seed: int = 0
) -> tuple[nn.Linear, list[float]]:
    """Fit Lesson 2's model, minutes = w1 × km + w2 × traffic + b, on all 300 deliveries in minibatches."""
    torch.manual_seed(seed)  # the starting weights
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    df = deliveries()
    X = torch.tensor(df[["distance_km", "traffic"]].to_numpy(), dtype=torch.float32)  # (300, 2)
    y = torch.tensor(df["minutes"].to_numpy(), dtype=torch.float32).unsqueeze(1)  # (300, 1)

    shuffler = torch.Generator().manual_seed(seed)  # the batch order is part of the seed
    loader = DataLoader(TensorDataset(X, y), batch_size=batch_size, shuffle=True, generator=shuffler)

    model = nn.Linear(2, 1).to(device)
    loss_fn = nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=lr)

    epoch_losses = []
    for epoch in range(epochs):
        model.train()
        for xb, yb in loader:  # a new shuffle every epoch; 300 / 32 → 10 steps
            xb, yb = xb.to(device), yb.to(device)
            optimizer.zero_grad()
            loss = loss_fn(model(xb), yb)
            loss.backward()
            optimizer.step()
        model.eval()
        with torch.inference_mode():  # the loss on all 300, once per epoch
            epoch_losses.append(loss_fn(model(X.to(device)), y.to(device)).item())
    return model, epoch_losses


net, epoch_losses = minibatch_sgd()
print([round(epoch_losses[e], 1) for e in (0, 9, 99)])  # [39.1, 20.9, 18.6]
print(net.weight.data, net.bias.data)  # about (4.2, 6.5) and 6.5; least squares gives (4.10, 6.45), 6.74
[39.1, 20.9, 18.6]
tensor([[4.1827, 6.4789]]) tensor([6.4578])

After 100 epochs (1,000 steps) the loss is 18.6. Least squares gets 18.58, with weights 4.10, 6.45 and intercept 6.74. Minibatch SGD lands close, and keeps jiggling around the answer, because each batch pulls a little differently. The same model with full batches, at a learning rate of 0.02, only reaches 19.9 in 100 epochs.

A few things in the code are worth copying:

  • torch.manual_seed fixes the starting weights. The loader gets its own seeded generator, so the batch order repeats too.
  • model.train() before training and model.eval() with torch.inference_mode() for checking. They change nothing for a linear model, but they're good habits. Later models behave differently in the two modes.
  • The loss is checked on all 300 deliveries once per epoch. A single batch's loss is too noisy to read.

Putting it together

Gradient descent turns training into a recipe that works for any model with a gradient:

  1. Start the parameters anywhere, such as 0.
  2. Take a minibatch, compute the loss and its gradient.
  3. Move every parameter against the gradient, scaled by the learning rate.
  4. Repeat for several epochs, and watch the loss curve.
ChoiceToo smallToo big
Learning ratecrawlszig-zags, then blows up
Batch sizenoisy stepsslow epochs, few steps
Epochsnot finishedwasted time (and, later, overfitting)

On the ten deliveries, 200 steps at learning rate 0.05 reach 3.94×km+10.753.94 \times \text{km} + 10.75. On all 300, 100 epochs of minibatches reach a loss of 18.6, against 18.58 for least squares. Neither needed a formula. The next lesson trains a model that has none.

Common misconceptions

"A bigger learning rate always trains faster." Only up to an edge. On the ten deliveries, 0.095 is the fastest you tried, and 0.1 diverges. Past the edge, the loss grows instead of shrinking.

"Gradient descent goes straight to the bottom." It goes straight downhill, which is not the same. In a narrow valley, downhill points across the valley, so the path drops in and then turns along the floor.

"An epoch is one step." An epoch is one pass through all the training data. With 300 deliveries in batches of 32, that's 10 steps.

"SGD's jitter means something is broken." Each minibatch gives a noisy estimate of the gradient, so the path wobbles. On average it still goes downhill, and the wobble stays small near the bottom.

"Gradient descent finds the exact answer." It gets close, and how close depends on the learning rate and the number of steps. Least squares is exact for linear regression. Gradient descent is for everything else.

Recap

  • Gradient descent repeats θ←θ−α∇L(θ)\boldsymbol\theta \leftarrow \boldsymbol\theta - \alpha \nabla L(\boldsymbol\theta): step every parameter against the gradient.
  • The learning rate α\alpha is a hyperparameter. Too small crawls; too big zig-zags, then blows up. The sharpest curvature sets the limit, 2/k2 / k.
  • A loss curve plots the loss against steps. It's the first check on any training run.
  • Stochastic gradient descent estimates the gradient from a random minibatch. An epoch is one pass through the data. Small batches take more, noisier steps per epoch.
  • PyTorch names: F.mse_loss and nn.MSELoss, loss.backward(), torch.no_grad(), torch.optim.SGD (zero_grad, step), nn.Linear, TensorDataset and DataLoader.