Loss: one number for how wrong
Read these first if they are new to you
The idea in one paragraph
A loss function compares a model's predictions with the right answers and returns one number. Zero means every prediction is right; a bigger number means worse. Training a model means changing its weights to make this number small. The most common loss for predicting numbers is the mean squared error: square each gap between prediction and answer, then average. The choice of loss decides what "good" means for the model.
A loss turns many errors into one number
A model makes a prediction for each example. Each example also has a target: the right answer. The error is prediction minus target. A model makes many predictions, so it has many errors. Some are positive and some negative.
To say whether one setting of the weights is better than another, we need a single number. A loss function provides it. It must be 0 when every prediction is right, and grow as the predictions get worse.
Mean squared error averages the squared gaps
The mean squared error (MSE) squares each error and takes the mean. For n examples with predictions pi and targets ti:
MSE = (1/n) ∑ (pi − ti)2
Squaring makes every term positive, so errors above and below cannot cancel. A related loss, the mean absolute error (MAE), averages |pi − ti| instead.
The targets are (3, 5, 7). The model predicts (2.5, 5, 8).
- Errors: 2.5 − 3 = −0.5, then 0, then 8 − 7 = 1.
- Squared errors: 0.25, 0, 1.
- MSE = (0.25 + 0 + 1) / 3 = 1.25 / 3 ≈ 0.417.
- For comparison, MAE = (0.5 + 0 + 1) / 3 = 0.5.
Your turn. The targets are (1, 2) and the predictions are (2, 4). What is the MSE?
Answer
Errors 1 and 2, squared 1 and 4, mean (1 + 4) / 2 = 2.5.
Try it. The figure fits a straight line to five points, and each squared error is drawn as a square whose side is the gap. The MSE is the average area of the squares. Predict first: will the best line pass through every point? Then move the slider until the MSE is as small as you can make it.
The points, the line and the squared errors
The MSE for every slope
Answer
No line passes through all five points, so the MSE never reaches 0. The lowest MSE is about 0.117, at a slope of 0.94.
Squaring punishes one big error more than many small ones
Compare two models on ten examples. Model A is off by 1 on every example. Model B is exactly right on nine and off by 10 on one.
| MSE | MAE | |
|---|---|---|
| A: ten errors of 1 | (10 × 1) / 10 = 1 | 10 / 10 = 1 |
| B: one error of 10 | 100 / 10 = 10 | 10 / 10 = 1 |
MAE rates the two models the same. MSE rates B ten times worse. So training with MSE works hard to avoid any large error, and a few wrong targets in the data can pull the model a long way. MAE is calmer about such outliers.
When the answer is a point, the error is a distance
Many models predict several numbers at once, such as the coordinates of a point. Then the natural error is the distance between the predicted point and the target point. The squared distance is the sum of the squared coordinate errors. Averaged over examples, it gives an MSE for points.
PyTorch's MSELoss averages over every number, coordinates included. For 3D points, that is the
mean squared distance divided by 3. The two differ only by a constant factor, so the best weights are the same.
The size of the loss, and of its gradient, differs, so compare loss values only between runs that compute them
the same way.
When one input has several targets, the mean is the best single prediction
Sometimes the same input comes with different targets. The model can give only one prediction for that input, so it must pick one number c for all of those targets. Take the five targets 4, 8, 6, 5 and 7, the film ratings from summarizing a list of numbers. Which c makes the MSE smallest?
The answer is their mean, 6. The MSE splits into two parts:
MSE(c) = (c − mean)2 + variance
To see why, write each error as (c − mean) + (mean − target) and square it. The cross terms cancel, because the deviations from the mean add up to zero. The variance does not depend on c. So the MSE is smallest when the first part is 0, that is, when c is the mean.
- Predict 6: the errors are 2, −2, 0, 1 and −1. The MSE is (4 + 4 + 0 + 1 + 1) / 5 = 2, the variance.
- Predict 7: the errors are 3, −1, 1, 2 and 0. The MSE is (9 + 1 + 1 + 4 + 0) / 5 = 3, which is (7 − 6)2 + 2.
Two facts follow. First, when the targets disagree, the loss cannot reach 0: the best it can do is their variance. Second, the best prediction need not be any of the targets: for the targets −1 and +1 it is 0. For points, the same holds for each coordinate, so the best single point is the average point. MAE behaves differently: its best single prediction is the median, the middle value.
The loss is what training sees
Training only makes the loss small. It does not see anything else. So the loss must change smoothly as the weights change, or gradient descent cannot tell which way to move them. This is why classifiers train on cross-entropy rather than on the share of correct answers, which changes in jumps.
A small loss on the training examples is also no promise about new examples. A validation set checks that.
loss_numpy.py
import numpy as np
target = np.array([3.0, 5.0, 7.0])
pred = np.array([2.5, 5.0, 8.0])
err = pred - target
print(err)
print("MSE", np.mean(err ** 2))
print("MAE", np.mean(np.abs(err)))
[-0.5 0. 1. ]
MSE 0.4166666666666667
MAE 0.5
PyTorch has both losses built in. MAE is called L1Loss there.
loss_torch.py
import torch
target = torch.tensor([3.0, 5.0, 7.0]) # a tensor: PyTorch's kind of array
pred = torch.tensor([2.5, 5.0, 8.0])
# MSELoss() makes the loss function; (pred, target) then calls it
print(torch.nn.MSELoss()(pred, target))
print(torch.nn.L1Loss()(pred, target))
tensor(0.4167)
tensor(0.5000)
Check yourself
-
The targets are (0, 0, 0, 0) and the predictions are (1, −1, 1, −1). What are the MSE and the MAE? What would a plain average of the errors give, and why is that useless?
Answer
MSE = 4 / 4 = 1 and MAE = 4 / 4 = 1. The plain average of the errors is 0, because the positive and negative errors cancel. It would call a wrong model perfect.
-
A data set has a few targets that were typed in wrong and are far too large. Which loss lets them pull the model further, MSE or MAE?
Answer
MSE. Their large errors are squared, so they dominate the average.
-
A model predicts the point (1, 2) and the target is (4, 6). What is the squared distance, and what does PyTorch's
MSELossreport for this one example?Answer
The coordinate errors are 3 and 4, so the squared distance is 9 + 16 = 25.
MSELossaverages over the two coordinates and reports 12.5. -
The targets 1, 2 and 6 all belong to one input. Which single prediction gives the lowest MSE, and what is that MSE?
Answer
The mean, 3. The errors are 2, 1 and −3, so the MSE is (4 + 1 + 9) / 3 ≈ 4.67, the variance of the three targets.
Go further
Optional background, for readers who want more than this page.
-
Compares squared and absolute losses on the same data, with exercises.
-
A scrolling page that fits a line and shows the squared error as it changes.
-
The squared loss written in vector form, as code uses it.
Where this shows up
Units that build on this one
- Gradient descent Intermediate
- Held-out data: the validation set Intermediate
- Binary cross-entropy: scoring yes-or-no guesses Intermediate
- Cross-entropy: scoring a choice among many Intermediate
- Flow matching: turning noise into shapes Advanced
- Backpropagation: gradients by the chain rule Intermediate