Sign in

MSE

Mean Squared Error

A regression loss that averages the squared difference between prediction and target, so large errors count far more than small ones.

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

  1. Compute the error ee as prediction minus target for each element.
  2. Square each error.
  3. Reduce with reduction: the mean over all elements by default.
  4. In backward, return 2e2e 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

IfUse instead
The data has outliers that should not dominateHuber loss or mean absolute error
The target is a class labelSoftmax cross-entropy or binary cross-entropy
One input can have several distinct valid targetsMixture density loss

Math foundations

  1. The loss

    L=1n∑i=1n(y^i−yi)2\mathcal{L} = \frac{1}{n}\sum_{i=1}^{n} (\hat{y}_i - y_i)^{2}

    The average squared error. It is also called the L2 loss.

  2. The gradient

    ∂L∂y^i=2n (y^i−yi)\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = \frac{2}{n}\,(\hat{y}_i - y_i)

    Proportional to the error. A prediction that is too high is pushed down, and twice as far off means twice the push.

  3. The best constant prediction is the mean

    arg⁡min⁡c  ∑i=1n(c−yi)2=1n∑i=1nyi\arg\min_{c}\; \sum_{i=1}^{n} (c - y_i)^{2} = \frac{1}{n}\sum_{i=1}^{n} y_i

    Setting the derivative 2∑i(c−yi)2\sum_i (c - y_i) to zero gives the average. More generally, a model minimising squared error estimates the conditional mean of the target.

  4. The noise model behind it

    −ln⁡p(y∣y^)=(y−y^)22σ2+12ln⁡ ⁣(2πσ2)-\ln p(y \mid \hat{y}) = \frac{(y - \hat{y})^{2}}{2\sigma^{2}} + \frac{1}{2}\ln\!\big(2\pi\sigma^{2}\big)

    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

y^i\hat{y}_i
the prediction for element i, pred
yiy_i
the target for element i, target
nn
the number of elements
L\mathcal{L}
the mean squared error
cc
a constant prediction used for every example
σ\sigma
the standard deviation of the Gaussian noise

Worked by hand

Predictions (2,5,9)(2, 5, 9) against targets (3,5,5)(3, 5, 5).

e=(2−3,  5−5,  9−5)=(−1,  0,  4)e = (2 - 3,\; 5 - 5,\; 9 - 5) = (-1,\; 0,\; 4)
L=1+0+163=5.6667\mathcal{L} = \frac{1 + 0 + 16}{3} = 5.6667
∂L∂y^=23 (−1,  0,  4)=(−0.6667,  0,  2.6667)\frac{\partial \mathcal{L}}{\partial \hat{y}} = \tfrac{2}{3}\,(-1,\; 0,\; 4) = (-0.6667,\; 0,\; 2.6667)

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

  1. 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.

  2. 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.

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

  4. 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.