In the last lesson the spam filter got its word scores by counting. That was a lucky shortcut. For most models there is no counting trick: the best numbers inside the model cannot be written down in one go. So how does a machine find them?
The answer is something you already do. Think of finding the right shower temperature: you turn the tap, feel whether it is too hot or too cold, and turn it a bit the other way. You repeat until it feels right. Nobody tells you the correct tap position. You try, check, adjust. A machine learns the same way, and in this lesson you will run the whole process, one step at a time.
The goal: a model that predicts a number
To keep every step visible, we use the smallest interesting task. We have some inputs and the right answer for each (the label, as in P0.1). We want a model that, given a new , predicts . Here could be the hours a student studied and their test score, but any pair of numbers works.
Tasks like this, where the answer is a number, are called regression. (P0.3 sorts the kinds of learning, and P3.A1 sets up the supervised case carefully.)
Our model is a straight line:
Read as “y-hat”: the model’s prediction. The hat means “predicted”, to keep it apart from the true . The two numbers and are the parameters (P0.1):
- , the weight, is the slope: how much the prediction rises when goes up by 1.
- , the bias, is the offset: the prediction when .
Every pair is a different line, that is, a different model. “Learning” will mean finding a good pair. Nothing else about the model changes: the shape (a line), the inputs and the data stay fixed.
The learning loop
Here is the whole idea: three steps, then repeat.
- Predict. For each example, the model computes from using the current and .
- Measure the loss. Compare each prediction with the right answer and combine all the mismatches into one number, the loss. A big loss means “very wrong”. The loss is the machine’s only sense of how it is doing.
- Update. Change and a little, in the direction that should make the loss smaller.
- Repeat from step 1 with the new and , until the loss stops improving.
The data is what feeds the loop; the model is what makes the predictions; the loss and the update are what turn mistakes into improvement. That is the five-word summary: data, model, prediction, loss, update.
Now we put real numbers into each step.
Step 1 and 2 by hand: predict and measure the loss
Three training examples (the data), and a starting line that is not good yet: , , so .
| Example | Input | Right answer | Prediction | Error | Squared error |
|---|---|---|---|---|---|
| 1 | 1 | 2 | 1 | −1 | 1 |
| 2 | 2 | 3 | 2 | −1 | 1 |
| 3 | 3 | 7 | 3 | −4 | 16 |
The error is the prediction minus the right answer. A negative error means the model predicted too low. Now combine the three errors into one number. We square each error (so 1, 1, 16) and take the mean (average):
This is the mean squared error, or MSE. Our loss is 6. A perfect model would have loss 0.
Why square the errors, and not just add them up? Two reasons.
- Signs would cancel. Errors of +2 and −2 add up to 0, but the model is wrong both times. Squared, they become 4 and 4.
- Big mistakes count much more. An error of 4 costs 16, while four errors of 1 cost only 4 in total. So the model is pushed hardest to fix its worst mistakes. (Whether that is what you want depends on the problem. One wild data point can pull the fit a long way. You can try it in the widget below with the “outlier” data.)
Using the absolute value (drop the minus sign) also stops cancelling, and is sometimes used. Squaring has a practical bonus: the loss changes smoothly as and change, with a well-defined slope everywhere (the absolute value has a sharp corner at 0), which is what the update step needs. Why we take the mean: so the loss does not grow just because we have more examples, and two datasets of different sizes can be compared.
Step 3: which way should we nudge?
We have a loss of 6 and want a smaller one. We can change and , but which way? The machine cannot see the whole landscape. All it can do is the shower trick: try a tiny change and see what the loss does.
Try raising from 1 to 1.01 (keep ). The new predictions are 1.01, 2.02, 3.03; the errors are −0.99, −0.98, −3.97, and the loss comes out as 5.9005. It went down from 6, by 0.0995. So raising helps. Dividing the change in loss by the size of the nudge gives the slope of the loss with respect to :
A negative slope means “the loss falls as rises”. The exact value is −10 (a little calculus, or a smaller nudge, gives it; P1.C1 teaches how). Do the same for : raise it from 0 to 0.01 and the loss becomes 5.9601, a slope of about −3.99. The exact value is −4. Both slopes are negative, so we should increase both and . And since ‘s slope is bigger (−10 against −4), is the more effective knob right now.
Real systems do not try each nudge one by one. A formula, which for a line you can see in the Math tab below, gives all slopes at once, and for neural networks an algorithm called backpropagation (P4.8) does the same job for millions or billions of parameters. But what it computes is exactly this: for every parameter, how does the loss change if I nudge it? This collection of slopes is called the gradient (P1.C5).
The update rule: move each parameter against its slope (downhill), by an amount proportional to the slope:
The new number (the Greek letter “eta”) is the learning rate: how big a step to take. With :
- :
- :
The new line is . Predict again: 1.7, 3.2, 4.7. Errors: −0.3, 0.2, −2.3. Squared: 0.09, 0.04, 5.29. Mean: 1.81. The loss fell from 6 to 1.81 in one step. That is one lap of the loop.
(Why the minus sign? A positive slope means the loss rises as the number rises, so we must go down, which means subtracting. A negative slope means we add. The minus sign handles both cases.)
Watch the loop run
This widget is the same loop. The line is the model, the dots are the data, and the three boxes show which phase you are in. Press Next to walk through Predict, Measure loss and Update, or press Run 20 steps.
Choose “Worked example (3 points)” to see the numbers from this page appear: start at , , with learning rate 0.05, and the first update gives , .
Things to try:
- Press Next three times and watch one full lap: predictions appear, the errors appear and the loss is computed, then the line moves. Compare the table with the by-hand table above.
- Press Run 20 steps with “about right”. The line settles and the loss curve flattens.
- Drag a point far from the others, then run again. The line is pulled towards it. Squaring makes one far-away point matter a lot.
- Choose “too small”, then “too big”. Read the next sections to see what you are looking at.
The learning rate: how big a step?
The learning rate multiplies the slope to decide the step size.
- Too small: every step is safe but tiny, so the loss falls slowly and you may run out of time before the line is good.
- About right: quick progress, and the steps shrink by themselves as you near the bottom (the slope gets close to 0 there).
- Too big: a step jumps past the best value and lands somewhere worse. If it overshoots by more each time, the loss grows instead of falling and the numbers blow up (divergence).
On our worked example, would give and , with predictions 3.8, 6.8, 9.8 and a loss of 8.51, worse than the 6 we started from. The step overshot. The widget’s “too big” button shows the loss curve shooting upwards. There is no single best learning rate for every problem. Finding a good one is a routine part of training, and P1.F3 and P4.14 cover it in detail.
When do we stop?
The loss curve at the bottom of the widget is the best tool for judging this. It usually falls fast at first and then flattens. When it has flattened, more steps change little, and we stop. In practice people stop when one of these happens: the loss has almost stopped falling, a fixed budget of steps is used up, or the loss on held-out data (see below) stops improving.
Notice that the loss does not reach 0 for our three points. They do not lie on one straight line, so no line can touch all three. The lowest loss any line can reach is 0.5, at , . The loop slowly closes in on it: after 10 steps the loss is about 0.72, after 50 about 0.58, after 200 about 0.50. The widget shows the lowest possible loss for the data on screen so you can see how close you are.
Training versus using the model
Everything so far is training: the loop adjusts and using examples whose answers we know. Once training stops, the parameters are frozen. Using the model is called inference or prediction (P0.1): feed in a new , compute , and read off the answer. No loop, no loss, no update.
With the final line , , an input of gives . A new input needs one multiplication and one addition. That is why trained models are cheap to use compared with the cost of training them.
The real goal: doing well on new data
Here is the catch. We trained by shrinking the loss on the training examples. But we do not care about those: we already know their answers. We care about new inputs the model has never seen. This is called generalization, and it is the real measure of success.
A model can get a very low training loss by memorising the quirks of its examples, including random noise, instead of the real pattern. That is called overfitting. See it for yourself. Six training points (circles) are fitted by models with more and more adjustable numbers. Six new points (squares) were hidden during fitting.
The wiggly curve has six adjustable numbers, enough to pass through all six training points, so its training loss is 0.00. On the new points its loss is about 8.6, much worse than the straight line’s 0.29. A lower training loss did not mean a better model.
So real projects keep some data out of training (a test set) and judge the model on that. P3.A4 covers train, validation and test sets, and P3.A3 explains overfitting and underfitting. For now remember one rule: a model is only as good as its loss on data it did not train on.
What “learning” really means
Look back at what the machine did. It never “understood” hours of study or test scores. It had a line with two numbers, a way to score mistakes, and a rule to nudge the numbers so the score improved. Learning, for a machine, means adjusting parameters to reduce a loss on the examples it was given. Three consequences are worth keeping in mind:
- It only fits what it was given. The line is best for these points. If the examples are unrepresentative, or contain mistakes, the model learns those too. (If your points only cover 1 to 3 hours, the line’s answer for 40 hours is a guess far outside anything it has seen.)
- The loss defines what “good” means. The machine improves only what the loss measures. If the loss measures the wrong thing, you get a model that is good at the wrong thing.
- No understanding is required, and none is implied. A machine that predicts well has not necessarily grasped why the answer is what it is. Whether and in what sense large models “understand” is something researchers argue about. This lesson only claims what we can see: the machine reduces a number.
The same loop, scaled up
Nothing in the loop depends on the model being a line. Swap the pieces and the loop stays the same:
| Piece | Our line | A large language model (LLM) |
|---|---|---|
| Data | 3 to 7 points of | A very large amount of text |
| Model | A very large neural network | |
| Parameters | 2 numbers | From millions up to hundreds of billions or more (GPT-3 reported 175 billion; makers of some newer models do not publish their size) |
| Prediction | A number | A probability for each possible next word-piece (token) |
| Loss | Mean squared error | A measure of how surprised the model was by the word that really came next (P10.B2) |
| Update | Nudge using the slopes | Nudge using the slopes, found by backpropagation (P4.8) and applied with improved rules such as Adam (P4.13) |
Details differ and matter: real training uses small batches of examples instead of all of them at once (P1.F4, P2.7), and LLMs go through further stages after the first. But the heart of how a chatbot’s parameters were set is the loop you just ran: predict, measure the loss, nudge, repeat, typically hundreds of thousands to millions of times, each time on a large batch of text. That is why this lesson comes before almost everything else.
Intuition
Picture the loss as the height of a landscape, where each position is a pair . High ground means a bad line, low ground a good one. You are standing somewhere in fog and can only feel the slope under your feet. The loop says: feel which way the ground tilts, step the other way, repeat. The learning rate is the length of your stride.
Where the picture breaks: our landscape has only two directions ( and ), and it is a smooth bowl with a single lowest point, so you cannot get stuck. A neural network’s landscape has millions of directions and is far more complicated (P1.F2). The idea of feeling the slope and stepping downhill still works there, which is why it is used everywhere.
Math
For examples and the model :
The slopes of the loss (partial derivatives, P1.C4) are
and the update with learning rate is
Check with the worked example, where and : and . These match the slopes found by the tiny-nudge test. This is gradient descent on the mean squared error (P1.F3), and it is what the widget runs.
Go deeper Where do those slope formulas come from?
One example’s loss is with . By the chain rule (P1.C3), the slope of with respect to is , and with respect to it is . The loss is the average of these over all examples, and the slope of an average is the average of the slopes. That gives the two formulas above. No calculus is needed to use the loop, only to get the exact slopes quickly.
Code
The loop in NumPy. It follows the worked example exactly. Run it, then change eta or the number of steps.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first lines print slopes of about −9.995 and −3.999 (the exact values are −10 and −4). The steps then show the loss falling from 6.000 to 1.807, 0.970, … and creeping towards 0.5.
Go deeper Why not just solve for the best line directly?
For a line with squared error, a formula gives the best and in one go (P3.A2 shows it). So why learn with a loop? Because that formula only exists for very simple models. For a neural network there is no such shortcut, but the loop works unchanged. We practise on the line because you can check the loop’s answer against the formula.
Go deeper One lap through all the examples is not how big models train
Our loop uses every example in every lap. With millions of examples, that is slow, so real training computes the slopes on a small random batch of examples at each step and updates after each batch (P1.F4, P2.7). The slopes are a little noisy, but a step is far cheaper, so many more steps fit in the same time. One full pass through the data is called an epoch.
Misconceptions
Check yourself
Check your understanding
During training of the line ŷ = w·x + b, what is changed by the update step?
The parameters w and b are the only things the update changes. The data and its labels stay fixed, and so does the shape of the model (a line).
Why does mean squared error square the errors before averaging?
Squaring makes every error positive, so they cannot cancel, and it makes big errors count much more than small ones. A squared number is not always smaller (4 squared is 16), and the loss has no fixed value.
At the current w, the slope of the loss with respect to w is +3 (the loss rises as w rises). What should the update do to w?
We move against the slope: new w = w − η × 3, which is smaller than w. Raising w would make the loss larger.
You train, and the loss goes 6, 9, 14, 25, 60 over five steps. What is the most likely cause?
A loss that grows step after step means the updates overshoot the bottom by more each time, the signature of a learning rate that is too big. A too-small rate makes the loss fall slowly, not rise.
A model has a training loss of almost 0, but a large loss on new data. What is the best description?
Good performance on new data is the goal. A tiny training loss with a large loss on new data is the classic sign of overfitting. It does not show underfitting, which would give a high training loss, and it does not mean the new data is wrong.
Exercises
- Using the data , compute the mean squared error of the line with , .
Show answer
predictions 2, 4, 6; errors 0, 1, −1; squared 0, 1, 1; mean = 2/3 ≈ 0.67. Better than , whose loss was 6. - For , the loss is 6. Lowering to 0.99 gives a loss of about 6.1005. Should the update raise or lower ?
Show answer
raise it. Lowering made the loss go up, which agrees with the negative slope of about −10. - A parameter is with slope +3, and with slope −2. Apply one update with .
Show answer
and . - Explain why the loss in the worked example can never reach 0.
Show answer
the three points do not lie on one straight line, so no line passes through all of them. The lowest possible loss is 0.5, at , . - In the worked example, gives , . Compute the new loss and say what went wrong.
Show answer
predictions 3.8, 6.8, 9.8; errors 1.8, 3.8, 2.8; squared 3.24, 14.44, 7.84; mean ≈ 8.51, which is worse than 6. The step was too big and overshot. - Using the final line , , predict for and for . Which prediction do you trust less, and why?
Show answer
5.25 and 99. Trust 99 less. The line was fitted on inputs from 1 to 3 and nothing guarantees the trend continues so far outside them. - A friend says: “My model has zero training loss, so it is perfect.” Give two questions you would ask.
Show answer
what is its loss on data it was not trained on (a test set), and how many adjustable numbers does it have compared with the number of examples? Zero training loss can mean memorising. - Name the five parts of the learning loop for training a spam filter that learns one score per word.
Show answer
data = labelled emails; model = add up the word scores; prediction = spam or ham for an email; loss = how wrong the predictions are; update = nudge the word scores to reduce the loss.