Mean squared error
均方误差
Derive why squared loss selects a conditional mean, calculate its gradients and units, and separate its statistical meaning from Gaussian assumptions.
mean-squared-errorLarge misses count more than proportionally
For three target durations , consider a model that always predicts one number. Predicting 2 gives squared errors , with mean 12. Predicting 4 gives , with mean 8. Squared loss prefers accepting two small errors to leaving one large error unchanged.
Absolute loss makes a different choice: the mean absolute error at 2 is 2, below at 4. Neither preference is universal. Squaring expresses a particular cost and a particular statistical target. Choose it because those properties fit the task.
The mean minimizes expected squared loss
For scalar predictions, mean squared error is:
If all predictions share a constant , differentiating gives , so the empirical mean minimizes the objective. In the opening example, and the minimum MSE is 8. Multiplying the objective by a positive constant, such as , leaves this minimizer unchanged while scaling gradients. D2L, Section 3.1.1.2
The population statement is stronger. At a fixed input , let and assume a finite conditional second moment. Expanding around that mean gives:
The cross term vanishes because . The first term does not depend on , and the second is minimized at . Thus squared loss targets a conditional mean, even when the conditional distribution is not Gaussian. Restricting predictions to a model family may prevent reaching every conditional mean exactly. MML, Section 8.2.2
Gaussian noise gives an additional likelihood interpretation. Suppose labels are conditionally independent given inputs and model parameters, with for fixed . The negative log-likelihood is:
The first term is constant in the mean-model parameters, so minimizing it is equivalent to minimizing the squared-error sum. This explains one modeling route to MSE; Gaussianity is not required for the conditional-mean result above. D2L, Section 3.1.3
Return both the loss and prediction gradients
This complete Python example handles nonempty scalar prediction arrays of matching length. The gradient is with respect to each prediction, before backpropagating through any model. A finite-difference check independently verifies each component.
import math
def loss_and_grad(targets, predictions):
if not targets or len(targets) != len(predictions):
raise ValueError("nonempty matching arrays required")
if any(not math.isfinite(v) for v in targets+predictions):
raise ValueError("finite values required")
n = len(targets)
residuals = [p-y for y,p in zip(targets,predictions)]
return sum(r*r for r in residuals)/n, [2*r/n for r in residuals]
targets = [2.0,2.0,8.0]
c = sum(targets)/len(targets)
predictions = [c]*len(targets)
loss, gradient = loss_and_grad(targets,predictions)
assert c == 4 and loss == 8
assert loss_and_grad(targets,[2.0]*3)[0] == 12
assert math.isclose(sum(gradient),0,abs_tol=1e-12)
h = 1e-5
for i,g in enumerate(gradient):
plus,minus = predictions.copy(),predictions.copy()
plus[i] += h
minus[i] -= h
finite_difference = (loss_and_grad(targets,plus)[0]-loss_and_grad(targets,minus)[0])/(2*h)
assert abs(finite_difference-g) < 1e-8
assert math.isclose(math.sqrt(loss), math.sqrt(8))
assert loss_and_grad([y*60 for y in targets],[p*60 for p in predictions])[0] == 3600*loss
Computing the loss and prediction gradients takes work; the returned gradient list requires space. The constant fit also takes work. A network adds its own forward and backward costs.
Units, tails, and unequal noise
If the target uses minutes, MSE uses square minutes. RMSE takes the square root, returning to minutes. Converting targets and predictions to seconds multiplies MSE by 3600. Comparing raw MSE across differently scaled targets can therefore be misleading. Multi-output averaging also makes target scaling an implicit weighting choice.
The gradient grows linearly with residual magnitude, so large outliers can have substantial influence. A mistaken target and a genuinely costly rare event may both look like large residuals; deciding how to treat them requires domain evidence. Absolute, Huber, quantile, or weighted losses express different preferences.
A conditional mean can lie between plausible modes. If a target is equally likely to be -1 or 1 at the same input, squared loss selects 0, although 0 never occurs. Pixelwise squared reconstruction can similarly favor averages of incompatible possibilities. A distributional or multimodal prediction may better represent the uncertainty.
If Gaussian noise variances differ by example, likelihood includes residuals weighted by inverse variance. If those variances are learned, their log terms matter too. Plain unweighted MSE no longer represents that full likelihood. Also distinguish a test-set MSE, an average of predictive errors, from the corrected sample-variance estimator using .
Name the quantity before interpreting it
- What is RMSE for the constant prediction 4 in the opening example? Answer: in the target’s original units.
- Why is the sum of the three prediction gradients zero at the fitted constant? Answer: residuals sum to zero at the sample mean; the derivative for jointly moving the constant vanishes.
- Does MSE require Gaussian targets? Answer: no. Gaussian assumptions justify one likelihood interpretation; the mean-minimization identity requires a finite second moment.
- Can you estimate a constant baseline from all labels, including the final test labels? Answer: not if that same test set is meant to evaluate an independently fitted baseline. Fit the constant on training labels.
A loss target is not a full predictive distribution
Squared loss connects regression, conditional expectations, and bias–variance analysis. It provides a natural baseline when averages and large-error penalties match the application. To assess a more complex model, compare against a training-fitted mean and inspect residuals, groups, tails, and distribution shift. A lower average error alone does not identify why the model improved or where it still fails.
Make a prediction, then check
At the same input, the target is equally likely to be −1 or 1. Which constant minimizes squared loss?
Learning objectives
- Derive why empirical and conditional means minimize squared loss.
- Calculate prediction gradients, RMSE, and unit changes; state the assumptions behind a Gaussian likelihood interpretation.
Prerequisites & connections
Explore related knowledge →References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - Dive into Deep Learning — Linear Regression
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Recomputed MSE 8 at constant 4, MSE 12 at constant 2, absolute-loss differences, and RMSE √8; checked each prediction gradient by finite differences and the 3600 factor for minutes-to-seconds conversion.
- Re-derived the vanishing cross term in conditional-mean decomposition, separating finite-second-moment results from fixed-homoscedastic Gaussian likelihood; checked multimodality, heteroscedasticity, and sample-variance denominator distinctions.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · §8.2.2; PDF pp. 266–267: squared loss and expected risk
- Dive into Deep Learning — Linear Regression · §3.1.1.2 and §3.1.3: squared objective and Gaussian likelihood
Related topics