How Does a Model Learn From Its Mistakes?

Training finds a model's numbers by measuring how wrong it is and nudging every number a little, over and over. This post walks through that loop by hand: loss and mean squared error, gradient descent on one weight, the learning rate, and how batches and epochs scale it up to millions of numbers.

This is the second post in a five-part series on machine learning from zero. The first post explained what a model is. You don't have to read it first. The next section sums up the three facts from it that this post needs.

What you need from the first post

  • A model is a rule with blanks. For example, score = ? × hours predicts an exam score from hours of study. The blank is a number nobody tells you.
  • Parameters are the blanks. A weight is a blank that is multiplied with an input. A bias is a blank that is added on its own. Weights and biases together are the model's parameters.
  • Training finds the parameters from examples. Each example is one row of data with a known correct answer. In the first post, we found the blank by hand. Three students studied 2, 5 and 8 hours and scored 20, 50 and 80. We tried 3, then 7, then 10. The number 10 matched them all.

How does a computer find the numbers?

Trying numbers by hand worked for one blank. A real model can have millions of blanks. Nobody could try them one by one. So how does training find them?

The answer is a loop. The model guesses, measures how wrong it was, nudges its numbers a little, and guesses again. This post builds that loop in four steps:

  1. The recipe. The five steps almost every model's training follows.
  2. Measuring wrongness. How "how wrong" becomes one number.
  3. One step downhill. How the model knows which way to nudge, and how far.
  4. Many steps, many examples. The same idea at the scale of a real model.

The training recipe

Almost every kind of model is trained with the same basic recipe:

  1. Start with some first values for the parameters. These are often small random numbers.
  2. Predict. Run the training examples through the model and get its predictions.
  3. Measure how wrong the predictions are, compared to the real answers. This gives one number, called the loss.
  4. Adjust the parameters so that the loss gets smaller.
  5. Repeat steps 2 to 4 many times, until the loss stops improving.

Steps 2 and 3 are easy to picture. Step 4 is the clever part. The rest of this post is about steps 3 and 4.

Not every model trains this way. Post 4 shows one that doesn't.

Loss: measuring how wrong the model is

To improve, a model needs a way to measure its mistakes. That measurement is the loss. It is sometimes also called the cost or the error.

The loss is always one single number:

  • A large loss means the predictions are very wrong.
  • A small loss means the predictions are good.

The whole goal of training is to make this number as small as possible.

The loss for one example

When a model predicts a number, the simplest way to measure a mistake is the difference. Then you square it, which means multiplying it by itself:

error = prediction − real answer
loss  = error²

Say the model predicts 7, but the real answer is 20:

error = 7 − 20 = −13
loss  = (−13)² = 169

Why square the error? There are two reasons:

  • Squaring always gives a positive number. So being too high and being too low both count as mistakes. A miss of −13 and a miss of +13 both cost 169.
  • Squaring makes big errors count much more than small ones. An error of 10 gives a loss of 100. An error of 2 gives a loss of only 4. This pushes the model to fix its worst mistakes first.

From many examples to one number

The loss is worked out for each example on its own. Then all of those values are averaged into one number. That average is the loss that training tries to shrink.

The average of the squared errors has its own name: mean squared error, or MSE. You'll see it in almost every machine learning library.

Let's score the three tries from the first post this way. With ? = 7, the rule predicts 14, 35 and 56 for the three students. The real scores are 20, 50 and 80:

HoursPrediction (7 × hours)Real scoreErrorSquared error
21420−636
53550−15225
85680−24576

The MSE is (36 + 225 + 576) ÷ 3 = 279. Here are those squares drawn on the chart. The biggest miss makes by far the biggest square:

A chart of exam score against hours studied, with the three data points and the line score = 7 × hours running below them. At each point, a vertical gap shows the error, of 6, 15 and 24 points. Beside each gap is a square with that side length, with areas 36, 225 and 576. The footer reads: mean squared error = (36 + 225 + 576) ÷ 3 = 279.

Do the same for the other two tries, and you get one score per try:

TryMSE
? = 31,519
? = 7279
? = 100

The best try has the smallest loss. That is what "smaller loss is better" means.

Everything here predicts a number. Yes/no questions, like "approve this loan?", measure their mistakes differently. Post 4 shows how.

Gradient descent: the easy picture

We can now measure how wrong a model is. Next comes step 4 of the recipe: adjusting the parameters so the loss gets smaller. The method that does this is called gradient descent. Here is an everyday way to picture it.

The shower analogy

Imagine stepping into a shower. The water is cold, and you want it warm.

  • Which way do you turn the knob? You feel the water. If it's too cold, you turn toward hot. If it's too hot, you turn toward cold. This is the direction.
  • How far do you turn it? If the water is freezing, you make a big turn. If it's almost right, you make a tiny turn. This is the size of the step.
  • Then you feel the water again, turn the knob again, and repeat until the temperature is just right.

Gradient descent works the same way:

In the showerIn the model
The knobA weight (or a bias)
The water temperatureThe model's prediction
How far the water is from "just right"The loss
Feeling the water: which way to turn, and how muchThe gradient
How hard you turn the knob each timeThe learning rate

Two of those words are new:

  • The gradient is a number for each parameter. Its sign says which way to move the parameter. Its size says how strongly.
  • The learning rate is a small number you choose, such as 0.05. The gradient is multiplied by it, so each step stays small and careful. It is also called the step size.

A worked example with one weight

Take the simplest model, score = w × hours. Use a single example: 2 hours of study, real score 20. The right answer is w = 10, but the model doesn't know that. It starts at w = 3. The learning rate is 0.05.

Each step does two things. It works out the gradient. Then it updates the weight:

new w = w − learning rate × gradient

The gradient comes from a short formula. Post 3 derives it. For now, just watch its sign and its size.

StepwPrediction (w × 2)ErrorGradientNew w
13.006.00−14.00−56.05.80
25.8011.60−8.40−33.67.48
37.4814.96−5.04−20.28.49
48.4916.98−3.02−12.19.09

Check step 1 yourself: 3 − 0.05 × (−56) = 3 + 2.8 = 5.8.

Over more steps, w keeps moving toward 10:

3 → 5.8 → 7.48 → 8.49 → 9.09 → 9.46 → 9.67 → 9.80 → 9.88 → ... (closer and closer to 10)

Two things to notice:

  • The gradient is negative because w is too small. The update takes away the gradient. Taking away a negative number pushes w up.
  • The steps get smaller. As w gets closer to 10, the error shrinks, so the gradient shrinks, so the steps shrink. The process slows down by itself as it nears the answer. It's like making tiny knob turns when the water is almost perfect.

Another picture: rolling downhill

You can also draw the loss as a landscape. For this one-weight model, try every value of w, and plot the loss for each. You get a valley. The bottom of the valley, at w = 10, is where the loss is smallest.

The gradient is the slope of the valley where you stand. It says which way is downhill, and how steep it is. Gradient descent is like a ball rolling downhill, step by step, until it settles at the bottom:

The steep wall gives big steps. The flat bottom gives small ones. That is the same pattern as the table.

Why the learning rate matters

Back to the shower:

  • If you turn the knob too hard each time, you overshoot: freezing, then boiling, then freezing again. The temperature never settles.
  • If you turn it too gently, you'll get there in the end, but it takes a very long time.

A learning rate does the same two things. Let's run the same example with two other learning rates.

Too big: 0.25. Step 1 starts at w = 3, with a gradient of −56. The update is 3 − 0.25 × (−56) = 17. That jumps right past 10. At w = 17, the prediction is 34, the error is +14 and the gradient is +56. The update is 17 − 0.25 × 56 = 3. We're back where we started. It bounces 3 → 17 → 3 → 17 forever.

Too small: 0.005. Step 1 moves w from 3 to only 3.28. After 10 steps, w has reached just 5.35. In the same 10 steps, a learning rate of 0.05 gets w to 9.96.

Two copies of the same U-shaped loss curve, with the goal at w = 10. On the left, with a learning rate of 0.25, the weight jumps from 3 across the valley to 17 and back to 3, again and again, bouncing forever. On the right, with a learning rate of 0.005, ten tiny steps crowd together on the left wall, and after ten steps w has only reached 5.35.

Choosing a learning rate is a balance. Big enough to make progress, and small enough to settle.

What the name means

  • Gradient means slope, like the steepness of a road. It tells you which way is downhill and how steep it is.
  • Descent means going down. Here, it means going down the loss, toward fewer mistakes.

From one weight to many: batches, epochs and the loop

Real models have many parameters and many examples. Here is the same idea at that scale.

A real model is like a shower with millions of knobs, all changing the same water at once. Nobody could test each knob by hand. The gradient solves this. It gives every knob its own instruction at the same time: "this one up a bit, that one down a lot, this one barely matters." All the knobs turn together, a little at a time, and the process repeats.

Let's walk through what actually happens. Imagine a model with 800 training examples. A real project also keeps some examples aside and never trains on them. Why is the subject of post 4.

Batches

The model doesn't learn from one example at a time. It usually doesn't look at all 800 at once, either. Instead, it works with small groups of examples, such as 32 at a time. Each group is called a batch.

Why use batches?

  • One example at a time is noisy. A single unusual example could push the model the wrong way.
  • All the examples at once is slow. It gives a very reliable direction, but each step takes a long time, especially with huge datasets.
  • Batches are the middle ground. Reasonably reliable, and reasonably fast.

One training step, in detail

Step 1: Take a batch. Pick 32 of the 800 training examples.

Step 2: Predict. Run all 32 examples through the model, using its current weights and biases. You get 32 predictions.

Step 3: Measure the loss. Compare each prediction with its real answer, work out the loss for each, and average them. You now have one number, say 45. The goal is to make it smaller.

Step 4: Get a hint for every parameter. Next, training works out the gradient for every weight and bias. Think of each one as a hint. It says two things: should this parameter go up or down, and should it change a lot or a little? All the hints come from one calculation, for all the parameters at once. Post 3 shows how.

Here is an example with three parameters. The numbers are made up, just to show how hints are read:

ParameterCurrent valueHint (gradient)What it means
w13.00−40Go up, strongly
w21.50+10Go down, a little
b0.50−2Go up, very slightly

The sign gives the direction: negative means go up, positive means go down. The size gives the strength: a bigger number means a bigger push.

Step 5: Scale the hints down. Each hint is multiplied by the learning rate, such as 0.01. This keeps each change small, so the model doesn't overshoot.

Step 6: Update every parameter at the same time. This is the same update rule as before, applied to every parameter:

new value = old value − (learning rate × hint)
ParameterOld valueChangeNew value
w13.00−0.01 × (−40) = +0.403.40
w21.50−0.01 × (+10) = −0.101.40
b0.50−0.01 × (−2) = +0.020.52

The old values are replaced. The model now has slightly better parameters.

Step 7: Move on to the next batch. Take the next 32 examples and repeat steps 2 to 6, using the new values. The loss won't drop after every single batch, because each batch is a little different. But on average, it gets smaller over time.

Epochs

With 800 examples and batches of 32, it takes 800 ÷ 32 = 25 batches to go through all the training data once. One full pass through all the training data is called an epoch.

Training usually runs for many epochs. Before each new epoch, the examples are shuffled into a new random order, so the batches are different each time. For example, 50 epochs of 25 batches each gives 1,250 small updates in total.

The loop at a glance

A cycle of five steps joined by arrows: take a batch of 32 examples, predict, measure the loss as one number, work out a hint for every parameter (the gradient), and nudge every parameter by the learning rate times its hint, then back to the first step. In the centre: 800 examples ÷ 32 = 25 batches = 1 epoch, then shuffle and start the next epoch.

When does training stop?

Training stops when the loss stops improving. In real projects, people also watch how the model does on examples it never trained on. Post 4 explains why.

The final parameters are then saved to a file. That file, together with the code that describes the model's structure, is the trained model.

Two common misunderstandings

  • The model does not change one weight at a time and then re-check. That would be far too slow with millions of weights. All the hints come from one calculation, and all the parameters change together.
  • The model does not only learn from its wrong answers. Every example in every batch is used. But wrong predictions produce large losses, which create large hints and push the parameters hard. Correct predictions produce tiny losses and barely push at all. So the mistakes drive the learning on their own.

After training

Once training is finished, the parameters are frozen. An app loads the saved model and uses it to make predictions. Making predictions never changes the parameters. If you want the model to learn from new data, you have to train it again.

New words in this post

WordMeaning
LossOne number that measures how wrong the model's predictions are
Squared errorThe error multiplied by itself; the loss for one number prediction
Mean squared error (MSE)The average of the squared errors over many examples
GradientFor each parameter: which way to move it, and how strongly, to lower the loss
Learning rate (step size)A small number that scales every gradient, so each step stays small
Gradient descentTraining by nudging every parameter a small step downhill on the loss, again and again
BatchA small group of training examples, such as 32, used for one update
EpochOne full pass through all the training data

Recap

  • Training is a loop: predict, measure how wrong, adjust, and repeat.
  • The loss is one number that says how wrong the model is. For number predictions, it is usually the mean squared error. Squaring makes big misses count much more.
  • The gradient tells each parameter which way to move and how strongly. A negative gradient means "go up".
  • Each update is new value = old value − learning rate × gradient. Big errors give big steps. Small errors give small steps.
  • A learning rate that is too big bounces around and never settles. One that is too small crawls.
  • Real training works on batches of examples. All the parameters change together after each batch. One pass over all the training data is an epoch.

Next up: every rule so far multiplies and adds. A rule like that can only draw a straight line, so it can never learn that too much sleep hurts a score. How Do Neural Networks Work, and How Do They Learn? builds a model that can, and shows where the gradient comes from.