How Models Learn
How a loss function measures a model's error, how gradient descent adjusts parameters to reduce it, and what to watch for when you train or fine-tune.
On this page
A model learns by repeating three steps: it makes predictions, a loss function scores how wrong those predictions are, and an algorithm called gradient descent changes the model's parameters slightly so that the score improves. Almost all modern models, from a small regression to a large language model, are trained this way. Knowing the loop tells you why a run diverges, stalls or overfits, and which setting to change.
Without this loop, the only way to find good parameters would be to try candidate values and keep the best one. That is workable for a single number and impossible for a model with millions of parameters. Gradient descent avoids the search because it uses the loss to tell each parameter which direction to move.
A model with one parameter
To see the loop clearly, use the smallest model that still learns. A courier app estimates trip time from distance with the formula minutes = w × km. The parameter w is the number of minutes per kilometre, and training has to find it. The two past trips are 1 km in 3 minutes and 3 km in 9 minutes, so the right answer is w = 3, and you can check whether the method finds it without being told.
The loss measures how wrong the model is
For each example, the error is the prediction minus the real answer. With w = 0 the model predicts 0 minutes for both trips, so the errors are −3 and −9.
The loss turns the errors into a single number. The most common choice for predicting numbers is the mean squared error, which squares each error and averages the results:
loss = ((−3)² + (−9)²) / 2 = (9 + 81) / 2 = 45
Squaring makes every error positive, so a guess that is too high and a guess that is too low cannot cancel each other out. It also penalises large errors more heavily: an error of 9 costs 81, which is nine times the cost of an error of 3. Training means finding the value of w that gives the lowest loss.
The gradient says which way to move
If you plot the loss for every possible value of w, you get a curve shaped like a valley, with its lowest point at w = 3 where the loss is 0.
The gradient is the slope of that curve at the current value of w. It tells you how much the loss changes if you increase w by a tiny amount. A negative gradient means that increasing w lowers the loss, and a positive gradient means that decreasing it does.
For this model and loss, calculus gives a simple formula. For one example with input x and error e, the squared error changes by about 2 × e × x for each unit that w increases. Averaging over all the examples gives the gradient:
gradient = average of (2 × error × input)
Real frameworks compute the gradient automatically for any model, using an algorithm called backpropagation, so you never write this formula yourself. It is shown here so that the trace below can be checked by hand.
Updating the parameter and repeating
Each training step moves the parameter a small distance against the gradient:
w = w − learning rate × gradient
The learning rate controls how large the step is. The person training the model chooses it, and it is not learned. Here it is 0.05. The trace below runs the loop five times from w = 0.
w = 0, rate = 0.05repeat: errors = w * km - minutes loss = average of errors squared gradient = average of 2 * error * km w = w - rate * gradient- km0113minutes0319predicted0010error0-31-9
- w
- 0
- loss
- 45
1The model starts with a blind guess of
w = 0. The errors are −3 and −9, so the loss is (9 + 81) / 2 = 45. - km0113minutes0319predicted0010error0-31-9
- w
- 0
- loss
- 45
- gradient
- -30
2The two per-example gradients are 2 × (−3) × 1 = −6 and 2 × (−9) × 3 = −54, which average to −30. The gradient is negative, so
wshould increase. - km0113minutes0319predicted01.514.5error0-1.51-4.5
- w
- 1.5
- loss
- 11.25
3The update is
w = 0 − 0.05 × (−30) = 1.5, and the loss drops from 45 to 11.25. - km0113minutes0319predicted01.514.5error0-1.51-4.5
- w
- 1.5
- loss
- 11.25
- gradient
- -15
4The errors are now −1.5 and −4.5, which give a gradient of (−3 + −27) / 2 = −15. The slope is half as steep as before.
- km0113minutes0319predicted02.2516.75error0-0.751-2.25
- w
- 2.25
- loss
- 2.8125
- gradient used
- -15
5The update is
w = 1.5 − 0.05 × (−15) = 2.25, and the loss is 2.8125. - km0113minutes0319predicted02.62517.875error0-0.3751-1.125
- w
- 2.625
- loss
- 0.703125
- gradient used
- -7.5
6The gradient is −7.5, so
w = 2.25 + 0.375 = 2.625. The gradient halves every round, and so does the size of the step. - km0113minutes0319predicted02.812518.4375error0-0.18751-0.5625
- w
- 2.8125
- loss
- 0.1758
- gradient used
- -3.75
7The gradient is −3.75, so
w = 2.8125and the loss is about 0.18. - km0113minutes0319predicted02.9062518.71875error0-0.093751-0.28125
- w
- 2.90625
- loss
- 0.0439
- steps
- 5
8A gradient of −1.875 gives
w = 2.90625. After five updates the loss has fallen from 45 to about 0.04, and the model found a value close to 3 without being told the answer.
The steps get smaller on their own because the slope flattens as w approaches the bottom of the valley.
// Average squared error of the model minutes = w * km.
function loss(w, km, minutes) {
let total = 0;
for (let i = 0; i < km.length; i++) {
const error = w * km[i] - minutes[i];
total += error * error;
}
return total / km.length;
}
// Slope of the loss at w: average of 2 * error * input.
function gradient(w, km, minutes) {
let total = 0;
for (let i = 0; i < km.length; i++) {
const error = w * km[i] - minutes[i];
total += 2 * error * km[i];
}
return total / km.length;
}
let w = 0;
for (let step = 1; step <= 5; step++) {
w = w - 0.05 * gradient(w, [1, 3], [3, 9]);
}
// w is 2.90625, loss(w, [1, 3], [3, 9]) is about 0.044def loss(w, km, minutes):
"""Average squared error of the model minutes = w * km."""
errors = [w * x - y for x, y in zip(km, minutes)]
return sum(e * e for e in errors) / len(km)
def gradient(w, km, minutes):
"""Slope of the loss at w: average of 2 * error * input."""
total = 0
for x, y in zip(km, minutes):
error = w * x - y
total += 2 * error * x
return total / len(km)
w = 0
for step in range(5):
w = w - 0.05 * gradient(w, [1, 3], [3, 9])
# w is 2.90625, loss(w, [1, 3], [3, 9]) is about 0.044The learning rate
The learning rate is the setting that most often decides whether training works, because the gradient only says which direction is downhill and says nothing reliable about how far the bottom is.
A learning rate that is too large
If the step is larger than the valley is wide, each update lands on the far side of the bottom, higher up the opposite slope than where it started. With a rate of 0.25 in this example, w jumps from 0 to 7.5, then to −3.75, then to 13.125, and the loss grows from 45 to 101.25 to about 228. With a rate of exactly 0.2, w bounces between 0 and 6 forever. The sign is a loss that rises or turns into NaN, and the fix is to lower the rate, usually by a factor of 3 to 10, and run again.
A learning rate that is too small
A small rate does not fail visibly. It only makes training slow. With a rate of 0.005, five steps move w only from 0 to about 0.68. The sign is a loss that decreases but barely changes from one step to the next. The fix is to raise the rate until the loss falls quickly but not erratically.
Rates that change during training
Large models are usually trained with a rate that changes over time. It starts small for a short warm-up, because the first gradients are unreliable, then it is held or raised, and it is lowered toward the end so that the parameters settle instead of bouncing around the minimum. Optimisers such as Adam and momentum variants also adjust the effective step for each parameter. They change how the step is calculated, but the loop of predict, score and update is the same.
Batches
The example computed the gradient from both trips. A real dataset can have millions of examples, and averaging over all of them for every update is too slow. Mini-batch gradient descent instead computes the gradient on a random subset, for example a few dozen or a few hundred examples, and updates the parameters after each subset. One pass over the whole dataset is called an epoch.
A batch gives a noisy estimate of the true gradient, so the loss jumps around from step to step instead of falling smoothly. The batch size is a trade-off. Small batches update often and use little memory but give noisy steps, while large batches give smoother steps but need more memory and fewer, larger updates.
Choosing a loss
The loss defines what the model is trained to do, so it has to match the task. Mean squared error suits predicting a number such as a trip time. When the model chooses between categories or predicts the next token of text, the usual loss is cross-entropy. The model outputs a probability for each option, and the loss is low when it gave a high probability to the correct one and very high when it was confident and wrong. A language model is trained by minimising cross-entropy on the next token across a very large amount of text.
A model optimises the loss you give it and nothing else. If the loss does not reflect what you want, such as a classifier trained on data where one class is rare, the model can score well on the loss and still be useless for the task.
Pitfalls
What this changes in practice
When you train or fine-tune a model, watch the training loss and the validation loss together on a plot, because the two curves tell you what to change. A training loss that rises or turns into NaN means the learning rate is too high. A training loss that falls very slowly means the rate is too low or the model has too little capacity. A validation loss that rises while the training loss falls means overfitting.
Change one setting at a time, so you can tell which change caused the difference. For a classifier with k equally likely classes, the cross-entropy at the start of training should be close to the natural logarithm of k, which is about 0.69 for two classes. A starting loss far from that value usually points to a bug in the data or the loss calculation, not to a bad model.
Training, validation and test data
Choosing the learning rate, the number of training steps and the model size by looking at the validation loss means those choices are tuned to the validation examples. So you keep a third set, the test set, and use it once at the end to estimate how the model will do on new data. If you keep adjusting settings until the test result looks good, the test set stops being an honest estimate.
Fine-tuning
Fine-tuning continues training a model that was already trained on a large dataset, using your smaller dataset. The loop is the same, but it normally uses a much lower learning rate than the original training, because large steps can overwrite what the model already learned. A small dataset is easy to memorise, so watch the validation loss.
Use the same two trips and the same learning rate of 0.05, but start too high, at w = 4. Work out the errors, the loss, the gradient and the new w. Which way does w move, and why?
Show a sample answer
The predictions are 4 × 1 = 4 and 4 × 3 = 12, so the errors are 4 − 3 = 1 and 12 − 9 = 3. The loss is (1² + 3²) / 2 = (1 + 9) / 2 = 5.
The gradient is (2 × 1 × 1 + 2 × 3 × 3) / 2 = (2 + 18) / 2 = 10. The new value is w = 4 − 0.05 × 10 = 3.5, and the loss at that point is (0.5² + 1.5²) / 2 = 1.25.
The value of w went down. The errors were positive, because the predicted trips were too long, so the gradient was positive, which means the loss rises when w rises. Stepping against the gradient therefore lowers w.
At the current w, the gradient is +12. What does the next update do?
During training, the loss goes 40, 90, 210, 480. What is the most likely cause?
The training loss keeps falling, but the validation loss has started to rise. What does this indicate?
Why does mean squared error square each error instead of just averaging the errors?
What to practise next
Regression and Classification adds a second parameter to get a better-fitting line, and then uses the same training loop for a model that chooses a category, such as spam or not spam.