AI Logic

Loss Functions

Mean Squared Error (MSE)

Updated:

Graph of mean squared error. The horizontal axis is the error (prediction āˆ’ target) and the vertical axis is the loss of a single example, overlaying the squared error e² of MSE (solid parabola), the mean absolute error |e| (dashed), and the Huber loss with Ī“ = 1 (dotted). At e = 2, e² = 4 and |e| = 2. Legend on the right

What Is Mean Squared Error?

Mean squared error (MSE) is a loss function that squares the difference (error) between the prediction and the ground truth and averages it over all examples. It is the most basic loss for training regression models, which predict values.

MSE=1māˆ‘i=1m(y^iāˆ’yi)2\mathrm{MSE} = \frac{1}{m} \sum_{i=1}^{m} \left( \hat{y}_i - y_i \right)^2

Here mm is the number of examples, y^i\hat{y}_i is the model's prediction, and yiy_i is the ground-truth value. It is 0 when every prediction matches the ground truth and grows as they diverge.

The figure at the top plots the loss of a single example as a function of the error e=y^āˆ’ye = \hat{y} - y. The MSE curve (solid line) is a parabola with the following characteristics.

  • Lenient on small errors: For e=0.5e = 0.5, the loss is 0.250.25, smaller than the absolute error ∣e∣=0.5|e| = 0.5.
  • Harsh on large errors: For e=2e = 2, the loss is 44; doubling the error quadruples the loss.

For example, in a model that predicts daily temperatures, being off by 1 degree on 4 days and being off by 4 degrees on 1 day both give a total error of 4 degrees. Under MSE, however, the former is 4Ɨ12=44 \times 1^2 = 4 and the latter is 42=164^2 = 16, showing that MSE strongly dislikes predictions that are far off.

Definition and Computation

MSE is computed in the following steps. As an example, take four examples with targets y=(3.0,Ā āˆ’0.5,Ā 2.0,Ā 7.0)y = (3.0,\ -0.5,\ 2.0,\ 7.0) and predictions y^=(2.5,Ā 0.0,Ā 2.0,Ā 8.0)\hat{y} = (2.5,\ 0.0,\ 2.0,\ 8.0).

  1. Compute the error ei=y^iāˆ’yie_i = \hat{y}_i - y_i for each example. Here e=(āˆ’0.5,Ā 0.5,Ā 0,Ā 1.0)e = (-0.5,\ 0.5,\ 0,\ 1.0).
  2. Square the errors. Here this gives (0.25,Ā 0.25,Ā 0,Ā 1.0)(0.25,\ 0.25,\ 0,\ 1.0). The sign disappears, so overshooting and undershooting count the same.
  3. Average over the number of examples. Here (0.25+0.25+0+1.0)/4=0.375(0.25 + 0.25 + 0 + 1.0) / 4 = 0.375.

The gradient with respect to the prediction y^i\hat{y}_i is proportional to the error.

āˆ‚ā€‰MSEāˆ‚y^i=2m(y^iāˆ’yi)\frac{\partial\, \mathrm{MSE}}{\partial \hat{y}_i} = \frac{2}{m} \left( \hat{y}_i - y_i \right)

Examples with larger errors are pushed back harder, and the gradient shrinks as the prediction approaches the ground truth. Some textbooks write it with a factor of 12\frac{1}{2}, as 12(y^āˆ’y)2\frac{1}{2}(\hat{y} - y)^2, so that the 2 cancels on differentiation. Since this is only a constant factor, the minimizer does not change.

The square root of MSE is called RMSE (root mean squared error). RMSE has the same unit as the ground truth (degrees, for temperature), which makes it easier to read the size of the error as an evaluation metric. For the training loss, it is common to use MSE as is, since it is simpler to compute.

Why Squared Errors?

MSE is the standard for regression not only for computational convenience but also for probabilistic reasons.

  • It is equivalent to maximum likelihood estimation under Gaussian noise: If the ground truth is assumed to follow a normal distribution with mean equal to the prediction y^\hat{y} and constant variance, the log of the probability of observing the ground truth (the likelihood) is āˆ’āˆ‘i(y^iāˆ’yi)2-\sum_i (\hat{y}_i - y_i)^2 multiplied by a constant plus a constant. Minimizing MSE is therefore the same as maximizing this probability (maximum likelihood estimation).
  • The optimal prediction is the mean of the ground truth: When a sufficiently expressive model is trained with MSE on sufficient data, it learns to predict, for each input, the mean of the ground truth (the conditional expectation). When the ground truth varies for the same input, MSE aims at its mean.
  • It is smoothly differentiable everywhere: Because it is a parabola, the gradient changes continuously even at zero error. The absolute error ∣e∣|e| has a kink at zero error.

One can also view MSE as the cross-entropy (negative log-likelihood) under a Gaussian assumption. Using cross-entropy for classification and MSE for regression both come from the same idea: "maximum likelihood estimation under an assumed probability distribution."

Where It Is Used

MSE is widely used for tasks whose outputs are continuous values.

  • Regression: It is the basic loss for tasks that predict numbers, such as house prices, temperatures, and sales.
  • Regression tasks in meta-learning: MAML uses MSE as the loss for regression tasks.
  • Regularization that aligns two outputs: R-Drop uses the KL divergence between the distributions of two outputs for classification, but for regression tasks, whose outputs are not distributions, it adds the MSE between the two predictions.

Practical Considerations

MSE is easily dragged around by outliers. Because errors are squared, a single example that is far off dominates the loss and gradient. In the example above, if the fourth target were recorded incorrectly so that its error became 10, MSE would jump from 0.375 to (0.25+0.25+0+100)/4=25.125(0.25 + 0.25 + 0 + 100)/4 = 25.125, and the gradient of that example would be 20 times that of the others. For data containing outliers, consider the Huber loss or the mean absolute error.

Keep the following points in mind as well.

  • Do not use it on classification outputs: Combining MSE with an output layer that produces probabilities via a sigmoid function or softmax makes the gradient very small when the output sticks to 0 or 1 (saturates), so training barely progresses even when the prediction is badly wrong. Use cross-entropy for classification.
  • Put targets on a common scale: Since MSE is the square of the error, the magnitude of the loss changes greatly with the unit and scale of the target values. When predicting several values at once, standardizing the targets (to mean 0 and variance 1) keeps outputs with large values from dominating training.
  • PyTorch's nn.MSELoss averages over all elements: The default reduction="mean" divides by the total number of elements in the tensor, not by the batch size. Specify reduction="sum" if you want the sum.
  • The order of the arguments does not affect the loss value: Since (y^āˆ’y)2=(yāˆ’y^)2(\hat{y} - y)^2 = (y - \hat{y})^2, swapping the prediction and the target gives the same value, but writing criterion(prediction, target) in the conventional order makes the code easier to read.

Comparison with Other Loss Functions

The table below compares MSE with related loss functions from the same viewpoints.

Loss functionLoss for one exampleRobustness to outliersOptimal prediction / shapeMain uses
MSE (mean squared error)e2e^2Weak (large errors weigh heavily because they are squared)Mean of the ground truthStandard for regression
Mean absolute error (MAE)∣e∣\lvert e \rvertStrong (proportional to the error)Median of the ground truthRegression with many outliers
Huber loss12e2\frac{1}{2}e^2 for ∣e∣<Ī“\lvert e \rvert < \delta, otherwise Ī“(∣eāˆ£āˆ’12Ī“)\delta(\lvert e \rvert - \frac{1}{2}\delta)Moderate (large errors grow linearly)Same shape as MSE for small errors and MAE for large onesRegression with a few outliers
Cross-entropyāˆ’log⁔ptarget-\log p_{\text{target}}—Probability of the correct classClassification

Rough guidelines for choosing among them:

  • For regression, start with MSE: It is the most standard and has theoretical backing under the assumption of Gaussian noise.
  • If there are many outliers and training is thrown around by a few examples, switch to the Huber loss or MAE: MAE has a kink at zero error and its gradient magnitude does not change even near the target, so MSE and the Huber loss are better at fine-tuning small errors.
  • For classification, use cross-entropy rather than MSE.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Example from the text: targets y and predictions Å·
y_true = torch.tensor([3.0, -0.5, 2.0, 7.0])
y_pred = torch.tensor([2.5, 0.0, 2.0, 8.0], requires_grad=True)

criterion = nn.MSELoss()             # reduction="mean": divides by the total number of elements
loss = criterion(y_pred, y_true)
print(loss.item())                   # 0.375

# Computation by definition
print(((y_pred - y_true) ** 2).mean().item())   # 0.375

# The gradient is 2(Å· āˆ’ y) / m
loss.backward()
print(y_pred.grad)                   # (āˆ’0.25, 0.25, 0.0, 0.5)

# A single outlier makes MSE jump sharply
y_bad = torch.tensor([3.0, -0.5, 2.0, -2.0])     # the 4th error is 10
print(nn.MSELoss()(y_pred.detach(), y_bad).item())   # 25.125
print(nn.L1Loss()(y_pred.detach(), y_bad).item())    # 2.75 (mean absolute error)
print(nn.HuberLoss(delta=1.0)(y_pred.detach(), y_bad).item())  # 2.4375


# Usage in a regression model: the output layer is linear, with no activation function
model = nn.Sequential(nn.Linear(8, 64), nn.ReLU(), nn.Linear(64, 1))
x = torch.randn(32, 8)               # dummy mini-batch
target = torch.randn(32, 1)          # standardized targets
loss = nn.MSELoss()(model(x), target)
loss.backward()

FAQ

Q. What is the difference between MSE and RMSE?
A.

RMSE is the square root of MSE. The model that minimizes them is the same, but RMSE has the same unit as the ground truth, making it easier to read "how far off the predictions are on average." MSE is often used as the training loss and RMSE for reporting results.

Q. My loss starts at a very large value. Is that a problem?
A.

When the target values are large, the squared errors are also large, so it is not unusual for the loss to start large. However, the gradients also become large and training tends to be unstable, so it is common to standardize the targets before training and convert the predictions back to the original units.

Q. Can MSE be used for classification?
A.

It is possible, but not recommended. Combined with an output layer that produces probabilities, the gradient becomes small when the output sticks to 0 or 1, so training barely progresses even when the prediction is wrong. Use cross-entropy for classification.

References

  1. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Section 5.1.4 Linear Regression and Section 5.5.1 Conditional Log-Likelihood and Mean Squared Error.
  2. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Section 6.2.1.2 Learning Conditional Statistics.
  3. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 3.1 Linear Regression.
  4. PyTorch Documentation, "torch.nn.MSELoss."
  5. PyTorch Documentation, "torch.nn.HuberLoss."