How a Model Learns: Gradient Descent

Train a tiny model on four data points and watch it discover a hidden rule by predicting, measuring its error and correcting itself, one line at a time.

Machine Learning · beginner · 15 min · 32 steps · free

What you'll learn

gradient_descent.py

# Hours studied -> exam score. The hidden rule is score = 2 * hours + 1.
xs = [1, 2, 3, 4]
ys = [3, 5, 7, 9]

w, b = 0.0, 0.0   # the model starts knowing nothing
lr = 0.05         # learning rate: how big each correction is

for epoch in range(3):
    preds = [w * x + b for x in xs]
    errors = [p - y for p, y in zip(preds, ys)]
    loss = sum([e * e for e in errors]) / len(xs)
    dw = 2 * sum([e * x for e, x in zip(errors, xs)]) / len(xs)
    db = 2 * sum(errors) / len(xs)
    w = w - lr * dw
    b = b - lr * db
    print(f"epoch {epoch}: loss {loss:.2f}, w {w:.2f}, b {b:.2f}")

Step by step

  1. Four students: xs holds how many hours each one studied. The model will try to predict their scores from this.
  2. ys holds the scores they actually got. The hidden rule is score = 2 × hours + 1, but the model is never told that. It has to discover it from these four examples.
  3. The model is a straight line: prediction = w × hours + b. Both start at 0, so right now it predicts 0 for everyone. On the chart, the blue line lies flat on the floor, far below the green points. Below it, the loss map shows how wrong every possible (w, b) would be: darker is worse, the blue dot is the model now and the star is the best it could ever do.
  4. The learning rate lr decides how big each correction will be. 0.05 means "move 5% of the way the gradient suggests". Too small and learning is slow; too big and it overshoots (try the other version above to see).
  5. Each pass over the data is called an epoch. We will do 3 epochs. Each one has the same four moves: predict, measure the error, work out which way to nudge w and b, then nudge them.
  6. Predict: for every student, work out w * x + b. With w and b both 0, every prediction is 0: the hollow dots on the chart all sit on the flat line.
  7. Measure: each error is prediction − actual score. All four are negative (−3, −5, −7, −9): the model guesses too low for everyone. On the chart, each red square has the error as its side.
  8. The loss squares each error and averages them: (9 + 25 + 49 + 81) / 4 = 41. One number that says how wrong the model is: the average area of the red squares. Training is about shrinking those squares.
  9. dw is the gradient for w: how the loss changes if w grows a little. It is −35. Negative means "if you increase w, the loss goes down".
  10. db is the gradient for b: the average of 2 × error, which is −12. Also negative, so raising b will lower the loss too. On the loss map, the amber arrow is the gradient (−35, −12): it points uphill, towards a worse model. The green dashed arrow is where the update will actually go: the opposite way, downhill.
  11. Nudge w against its gradient: 0 − 0.05 × (−35) = 1.75. The line tilts up sharply towards the points, and on the loss map the dot moves right along the w axis.
  12. Nudge b the same way: 0 − 0.05 × (−12) = 0.6. The line also lifts a little (the dashed grey line is where it was a moment ago), and the dot on the loss map moves up, landing where the green arrow pointed.
  13. End of epoch 0. The loss was 41 when this epoch measured it. The line now sits much closer to the points, but the loss for this new line is only worked out at the start of the next epoch.
  14. Epoch 1: the same four moves, starting from the improved w = 1.75 and b = 0.6.
  15. New predictions: 2.35, 4.1, 5.85, 7.6. Compare them with the real scores 3, 5, 7, 9: much closer than a row of zeros.
  16. The errors shrank from −3…−9 to −0.65…−1.4. Still all negative: the line is a bit too low everywhere, and too flat (the error grows with x).
  17. Loss: 1.13, down from 41 after a single correction. The loss chart drops steeply.
  18. dw is now −5.75: still negative, but much smaller. When the model is nearly right, the gradient gets small, so the steps get small too.
  19. db is −2.05, so b will rise a bit more.
  20. w becomes 1.75 − 0.05 × (−5.75) = 2.0375. That is already very close to the true slope of 2.
  21. b becomes 0.6 − 0.05 × (−2.05) = 0.7025, creeping towards the true value of 1.
  22. End of epoch 1. The printed loss (1.13) belongs to the line from the start of this epoch; the new line is better still.
  23. Epoch 2, from w = 2.04 and b = 0.70.
  24. Predictions 2.74, 4.78, 6.82, 8.85 against real scores 3, 5, 7, 9. On the chart the line nearly touches every point.
  25. The errors are tiny now (−0.26 down to −0.15), and they get smaller as x grows: the slope is good, and most of what is left is in b.
  26. Loss: 0.04. From 41 to 1.13 to 0.04 in three epochs. The red squares have almost vanished. On the loss map, each step of the path is shorter than the last, because the ground gets flatter near the bottom of the valley.
  27. dw is −0.925: a gentle nudge.
  28. db is −0.41.
  29. w becomes 2.084: it has slightly overshot 2. w and b are learned together, so while b is still too low, w leans a little high to make up for it. More epochs would let both settle.
  30. b becomes 0.723, still climbing towards 1. The bias usually learns more slowly than the slope here, because its gradient does not get multiplied by x.
  31. End of epoch 2. The model now predicts score ≈ 2.08 × hours + 0.72, very close to the hidden rule 2 × hours + 1, learned only from four examples and its own mistakes.
  32. range(3) is used up, so training stops. Nobody told the model the rule: it found it by repeating predict, measure, nudge. Every neural network, however big, learns with this same loop.

Common mistakes

Best practices

Key takeaways

Check yourself

The gradient db is +4. What does b = b - lr * db do to b?

Answer: Makes it smaller. Subtracting a positive amount makes b smaller. A positive gradient means increasing b would raise the loss, so we decrease it.

During training the loss goes 41 → 92 → 210. What is the most likely fix?

Answer: Use a smaller learning rate. A growing loss means each step overshoots. Smaller steps let the model settle instead of bouncing away.

Why is each error squared before averaging?

Answer: So positive and negative errors do not cancel, and big errors count more. An error of −5 and +5 would add up to 0 without squaring. Squaring also makes a miss of 9 cost 81, far more than a miss of 3.

·