Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 0: Start Here

How a machine "learns"

P0.225 min●○○ BeginnerReviewed Nov 30, 2026

Why this matters for machine learning

Most models in this course, including every neural network, learn by repeating one loop: predict, measure how wrong, nudge the parameters, repeat. Once you have run this loop on a straight line, the rest of the course is mostly about bigger models, better losses and cleverer nudges.

  • Gradient descent, the 'nudge in the direction that lowers the loss' step, is taught properly with the maths of slopes. (P1.F3: Gradient descent)
  • Fitting a line to points with a squared-error loss is the first real model, in full detail. (P3.A2: Linear regression, coming soon)
  • Backpropagation is the method that finds the right nudge for every parameter of a neural network. (P4.8: Backpropagation: step by step with numbers)
  • The PyTorch training loop is this same loop written as code. (P2.7: The PyTorch training loop, coming soon)

Before this: What are AI, ML and Deep Learning?

After this lesson you can

  • Name the five parts of the learning loop (data, model, prediction, loss, update) and say what each does
  • Compute predictions, errors, squared errors and the mean squared error for a small example by hand
  • Explain how a small trial change shows which way to nudge a parameter, and what the learning rate does
  • Tell training from using the model (inference), and say why the real goal is good predictions on new data
  • Explain what "learning" does and does not mean for a machine

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 xx and the right answer yy for each (the label, as in P0.1). We want a model that, given a new xx, predicts yy. Here xx could be the hours a student studied and yy 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:

y^=w x+b\hat{y} = w\,x + b

Read y^\hat{y} as “y-hat”: the model’s prediction. The hat means “predicted”, to keep it apart from the true yy. The two numbers ww and bb are the parameters (P0.1):

  • ww, the weight, is the slope: how much the prediction rises when xx goes up by 1.
  • bb, the bias, is the offset: the prediction when x=0x = 0.

Every pair (w,b)(w, b) 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.

  1. Predict. For each example, the model computes y^\hat{y} from xx using the current ww and bb.
  2. 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.
  3. Update. Change ww and bb a little, in the direction that should make the loss smaller.
  4. Repeat from step 1 with the new ww and bb, 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: w=1w = 1, b=0b = 0, so y^=x\hat{y} = x.

ExampleInput xxRight answer yyPrediction y^=1⋅x+0\hat{y} = 1\cdot x + 0Error y^−y\hat{y} - ySquared error
1121−11
2232−11
3373−416

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):

L=1+1+163=183=6\mathcal{L} = \frac{1 + 1 + 16}{3} = \frac{18}{3} = 6

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 ww and bb 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 ww and bb, 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 ww from 1 to 1.01 (keep b=0b = 0). 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 ww helps. Dividing the change in loss by the size of the nudge gives the slope of the loss with respect to ww:

5.9005−60.01≈−9.95\frac{5.9005 - 6}{0.01} \approx -9.95

A negative slope means “the loss falls as ww rises”. The exact value is −10 (a little calculus, or a smaller nudge, gives it; P1.C1 teaches how). Do the same for bb: 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 ww and bb. And since ww‘s slope is bigger (−10 against −4), ww 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:

w←w−η×slopewb←b−η×slopebw \leftarrow w - \eta \times \text{slope}_w \qquad b \leftarrow b - \eta \times \text{slope}_b

The new number η\eta (the Greek letter “eta”) is the learning rate: how big a step to take. With η=0.05\eta = 0.05:

  • ww: 1−0.05×(−10)=1.51 - 0.05 \times (-10) = 1.5
  • bb: 0−0.05×(−4)=0.20 - 0.05 \times (-4) = 0.2

The new line is y^=1.5x+0.2\hat{y} = 1.5x + 0.2. Predict again: 1.7, 3.2, 4.7. Errors: −0.3, 0.2, −2.3. Squared: 0.09, 0.04, 5.29. Mean: 5.42/3≈5.42/3 \approx 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 w=1w = 1, b=0b = 0, with learning rate 0.05, and the first update gives w=1.5w = 1.5, b=0.2b = 0.2.

  1. 1 Predict
  2. 2 Measure loss
  3. 3 Update
012345602468x (input)y (right answer)123456

Ready. The blue line is the model's current guess. Press Next to start the loop with the Predict step.

Try:
updates so far: 0
model: ŷ = 0·x + 0
loss: not measured
lowest possible loss: 0.194
#xyŷerrorerror²
10.81.6···
21.63.4···
32.53.1···
43.34.7···
54.25.2···
656.8···
mean of error² = loss·

Loss each time it is measured (step 0 is before any update; it should go down)

024681000.51update step

Drag a point (or focus it with Tab and use the arrow keys) to change the data. The loss curve then starts again.

The learning loop on a line. Pink dots are the data (drag them, or focus one with Tab and move it with the arrow keys; hold Shift for bigger steps). The blue line is the model. Open circles are predictions, red segments are the errors, the table shows every number, and the small chart below shows the loss after each update. Buttons: Next walks through one phase at a time, Run 20 steps repeats the whole loop.

Things to try:

  1. 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.
  2. Press Run 20 steps with “about right”. The line settles and the loss curve flattens.
  3. 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.
  4. 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 η\eta 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, η=0.2\eta = 0.2 would give w=3w = 3 and b=0.8b = 0.8, 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 w=2.5w = 2.5, b=−1b = -1. 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 ww and bb 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 xx, compute y^=wx+b\hat{y} = wx + b, and read off the answer. No loop, no loss, no update.

With the final line w=2.5w = 2.5, b=−1b = -1, an input of x=2.5x = 2.5 gives y^=2.5×2.5−1=5.25\hat{y} = 2.5 \times 2.5 - 1 = 5.25. 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.

012345602468xy

Filled circles are the training points the model learned from. Squares are new points it never saw.

loss on the training points: 0.36
loss on the new points: 0.29

The straight line misses every training point a little, yet it does about as well on new points as on the training points. It captures the trend, not the noise.

Three models fitted to the same six training points. Choose Straight line, Gentle curve or Wiggly curve. The readout compares the loss on the training points with the loss on six new points the model never saw. The fits here are computed directly, not by the learning loop, but they are the same lowest-loss fits that the loop would approach.

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:

PieceOur lineA large language model (LLM)
Data3 to 7 points of (x,y)(x, y)A very large amount of text
Modely^=wx+b\hat{y} = wx + bA very large neural network
Parameters2 numbersFrom millions up to hundreds of billions or more (GPT-3 reported 175 billion; makers of some newer models do not publish their size)
PredictionA numberA probability for each possible next word-piece (token)
LossMean squared errorA measure of how surprised the model was by the word that really came next (P10.B2)
UpdateNudge using the slopesNudge 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 (w,b)(w, b). 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 (ww and bb), 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 NN examples (xi,yi)(x_i, y_i) and the model y^i=wxi+b\hat{y}_i = w x_i + b:

ei=y^i−yi,L(w,b)=1N∑i=1Nei 2e_i = \hat{y}_i - y_i, \qquad \mathcal{L}(w, b) = \frac{1}{N}\sum_{i=1}^{N} e_i^{\,2}

The slopes of the loss (partial derivatives, P1.C4) are

∂L∂w=2N∑iei xi,∂L∂b=2N∑iei\frac{\partial \mathcal{L}}{\partial w} = \frac{2}{N}\sum_{i} e_i\, x_i, \qquad \frac{\partial \mathcal{L}}{\partial b} = \frac{2}{N}\sum_{i} e_i

and the update with learning rate η\eta is

w←w−η ∂L∂w,b←b−η ∂L∂b.w \leftarrow w - \eta\,\frac{\partial \mathcal{L}}{\partial w}, \qquad b \leftarrow b - \eta\,\frac{\partial \mathcal{L}}{\partial b}.

Check with the worked example, where e=(−1,−1,−4)e = (-1, -1, -4) and x=(1,2,3)x = (1, 2, 3): ∂L/∂w=23(−1−2−12)=−10\partial\mathcal{L}/\partial w = \tfrac{2}{3}(-1 - 2 - 12) = -10 and ∂L/∂b=23(−6)=−4\partial\mathcal{L}/\partial b = \tfrac{2}{3}(-6) = -4. 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 e2e^2 with e=wx+b−ye = wx + b - y. By the chain rule (P1.C3), the slope of e2e^2 with respect to ww is 2e×∂e/∂w=2e x2e \times \partial e/\partial w = 2e\,x, and with respect to bb it is 2e×1=2e2e \times 1 = 2e. 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.

Try it: the learning loop in NumPy

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 ww and bb 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

  1. During training of the line ŷ = w·x + b, what is changed by the update step?

  2. Why does mean squared error square the errors before averaging?

  3. 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?

  4. You train, and the loss goes 6, 9, 14, 25, 60 over five steps. What is the most likely cause?

  5. A model has a training loss of almost 0, but a large loss on new data. What is the best description?

Exercises

  1. Using the data (1,2),(2,3),(3,7)(1, 2), (2, 3), (3, 7), compute the mean squared error of the line with w=2w = 2, b=0b = 0.
    Show answerpredictions 2, 4, 6; errors 0, 1, −1; squared 0, 1, 1; mean = 2/3 ≈ 0.67. Better than w=1w = 1, whose loss was 6.
  2. For w=1w = 1, b=0b = 0 the loss is 6. Lowering ww to 0.99 gives a loss of about 6.1005. Should the update raise or lower ww?
    Show answerraise it. Lowering ww made the loss go up, which agrees with the negative slope of about −10.
  3. A parameter is w=2w = 2 with slope +3, and b=1b = 1 with slope −2. Apply one update with η=0.1\eta = 0.1.
    Show answerw=2−0.1×3=1.7w = 2 - 0.1 \times 3 = 1.7 and b=1−0.1×(−2)=1.2b = 1 - 0.1 \times (-2) = 1.2.
  4. Explain why the loss in the worked example can never reach 0.
    Show answerthe 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 w=2.5w = 2.5, b=−1b = -1.
  5. In the worked example, η=0.2\eta = 0.2 gives w=3w = 3, b=0.8b = 0.8. Compute the new loss and say what went wrong.
    Show answerpredictions 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.
  6. Using the final line w=2.5w = 2.5, b=−1b = -1, predict yy for x=2.5x = 2.5 and for x=40x = 40. Which prediction do you trust less, and why?
    Show answer5.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.
  7. A friend says: “My model has zero training loss, so it is perfect.” Give two questions you would ask.
    Show answerwhat 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.
  8. Name the five parts of the learning loop for training a spam filter that learns one score per word.
    Show answerdata = 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.

Key takeaways

  • Learning is a loop: the model predicts, a loss function measures how wrong the predictions are, and an update nudges the parameters to lower the loss. Then repeat.
  • The model here is a line, ŷ = w·x + b. The two parameters w (slope) and b (offset) are the only things that change during learning.
  • Mean squared error (MSE): subtract, square, average. Squaring stops positive and negative errors from cancelling and punishes big mistakes more.
  • To know which way to nudge a parameter, ask how the loss changes if you change it a tiny bit (its slope). Move the opposite way: new = old − η × slope. η, the learning rate, is the step size: too small is slow, too big overshoots and can blow up.
  • Training sets the parameters; inference uses them on new inputs. A low training loss is not the goal. What matters is the loss on new data (P3.A4), and a model that memorises its training examples fails there (overfitting, P3.A3).
  • A language model is trained with the same loop, with billions of parameters and different ingredients. 'Learning' means reducing a loss on examples. It does not mean understanding in the human sense.
Found a mistake? Tell us