Overview
Mean squared error is the default way to say how wrong a set of numeric predictions is. Each error is squared and the squares are averaged. Squaring does two things. It makes every error positive, and it makes big errors count disproportionately: an error of 10 costs a hundred times an error of 1. The gradient is proportional to the error, so far-off predictions are corrected strongly and near-correct ones gently. A model trained this way learns to predict the mean of the targets for a given input.
A short history
Adrien-Marie Legendre published the method of least squares in 1805 for fitting orbits to astronomical observations, and Carl Friedrich Gauss published his own account in 1809, linking it to normally distributed errors. Minimising squared error is maximum likelihood under Gaussian noise and has a closed-form solution for linear models. Those two properties made it the default regression loss for two centuries.
How it works
- Compute the error as prediction minus target for each element.
- Square each error.
- Reduce with
reduction: the mean over all elements by default. - In
backward, return for each element, divided by the element count for the mean.
Watch out for
- Outliers dominate. One target that is off by 100 contributes as much as ten thousand targets off by 1, and the fit bends toward it.
- The loss is in squared units of the target, which makes it hard to read. Take the square root to get back to the original units.
- It depends on the scale of the targets. Targets in the thousands give huge losses and gradients unless they are standardised first.
- Used on a sigmoid or softmax output for classification, its gradient vanishes when the model is confidently wrong. Use cross-entropy there.
Use cases
When to use it
Regression with roughly symmetric, light-tailed noise, where large errors really are much worse than small ones and you want the average outcome predicted.
In industry
- Energy
- Utilities train load forecasting models with squared error because large misses are far more costly than small ones.
- Image generation
- Diffusion models are trained with a squared error between the noise that was added to an image and the noise the network predicts.
- Recommendation
- Matrix factorisation on explicit star ratings, as in the Netflix Prize, minimises squared error between predicted and actual ratings.
Choosing it: what must hold
- A real-valued target where the mean is the right thing to predict.
- Errors that are roughly symmetric, without extreme outliers.
- Targets scaled to a moderate range, so that squared values do not produce very large gradients.
When to choose something else
| If | Use instead |
|---|---|
| The data has outliers that should not dominate | Huber loss or mean absolute error |
| The target is a class label | Softmax cross-entropy or binary cross-entropy |
| One input can have several distinct valid targets | Mixture density loss |
Math foundations
The loss
The average squared error. It is also called the L2 loss.
The gradient
Proportional to the error. A prediction that is too high is pushed down, and twice as far off means twice the push.
The best constant prediction is the mean
Setting the derivative to zero gives the average. More generally, a model minimising squared error estimates the conditional mean of the target.
The noise model behind it
The negative log-likelihood of a Gaussian with fixed variance. Minimising squared error is maximum likelihood under Gaussian noise, which is why it suits light-tailed errors.
Symbols
- the prediction for element i,
pred - the target for element i,
target - the number of elements
- the mean squared error
- a constant prediction used for every example
- the standard deviation of the Gaussian noise
Worked by hand
Predictions against targets .
The loss is 5.6667, and 16 of the 17 units come from one element. Its gradient is four times that of the element with an error of 1.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import MSELoss
from config import MSELossConfig
loss = MSELoss(MSELossConfig(reduction="mean"))
pred, target = np.array([1.0, 2.0, 3.0]), np.array([1.0, 4.0, 0.0])
print(loss.forward(pred, target)) # 4.3333
print(loss.backward(pred, target)) # [0.0, -1.3333, 2.0]Read the implementation (56 lines)
"""Mean squared error: loss = mean((pred - target)^2).
NumPy only. `forward` returns the loss, `backward` its gradient with respect to the prediction.
"""
from __future__ import annotations
import numpy as np
try:
from .config import MSELossConfig
except ImportError: # run from the template's own folder
from config import MSELossConfig
def _pair(pred, target) -> tuple[np.ndarray, np.ndarray]:
"""Both inputs as float arrays of one shape. Raises ValueError when the shapes differ."""
pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
if pred.shape != target.shape:
raise ValueError(f"pred and target must have the same shape, got {pred.shape} and {target.shape}")
return pred, target
def _reduce(values: np.ndarray, reduction: str):
"""Reduce per-element losses: "mean" and "sum" give a float, "none" returns the array unchanged."""
if reduction == "mean":
return float(values.mean())
if reduction == "sum":
return float(values.sum())
return values
def _grad_scale(count: int, reduction: str) -> float:
"""Factor the reduction puts on every per-element gradient: 1 / count for "mean", otherwise 1."""
return 1.0 / count if reduction == "mean" else 1.0
class MSELoss:
"""Squared difference between prediction and target, reduced as the config says."""
def __init__(self, config: MSELossConfig | None = None) -> None:
self.config = config or MSELossConfig()
def forward(self, pred: np.ndarray, target: np.ndarray):
"""pred, target: same shape, any number of axes. Returns a float, or the per-element array for "none"."""
pred, target = _pair(pred, target)
return _reduce((pred - target) ** 2, self.config.reduction)
def backward(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:
"""Gradient of the reduced loss with respect to pred, same shape as pred.
For "none" there is no single scalar, so the per-element derivative 2 * (pred - target) is returned
(the gradient of the sum).
"""
pred, target = _pair(pred, target)
return 2.0 * (pred - target) * _grad_scale(pred.size, self.config.reduction)
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build MSELoss(MSELossConfig()) and reproduce the worked example with forward and backward. Check one gradient entry with a finite difference. Then switch to reduction="sum" and reduction="none" and explain how the output of backward changes in each case.
Check on learning
- Your targets include a few values recorded in the wrong units, 1000 times too large. Predict what a model trained with this loss does.
A way to think about it
Compare the loss contributed by one such point with that of all the correct points together. The fit moves to reduce the largest terms first.
- Why is the gradient being proportional to the error helpful late in training?
A way to think about it
As predictions approach the targets the steps shrink on their own. Compare with a loss whose gradient keeps a constant size however close you are.
- The same model reports a loss of 0.04 on one dataset and 400 on another. Can you say which fit is better?
A way to think about it
The loss scales with the square of the target's units. Divide by the variance of the targets, or compare with the loss of always predicting the mean.
- House prices are strongly right-skewed. What happens if you train on the raw prices, and what would a log transform of the target change?
A way to think about it
On raw prices the expensive houses produce the largest errors and dominate. After a log transform the loss measures relative error. Note that it then estimates a different quantity.