AI Wiki中文/EN

Mean squared error

均方误差

Derive why squared loss selects a conditional mean, calculate its gradients and units, and separate its statistical meaning from Gaussian assumptions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Large misses count more than proportionally

For three target durations [2,2,8][2,2,8], consider a model that always predicts one number. Predicting 2 gives squared errors [0,0,36][0,0,36], with mean 12. Predicting 4 gives [4,4,16][4,4,16], 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 8/38/3 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 nn scalar predictions, mean squared error is:

MSE⁡=1n∑i=1n(y^i−yi)2,∂MSE⁡∂y^i=2n(y^i−yi).\operatorname{MSE}=\frac1n\sum_{i=1}^{n}(\hat y_i-y_i)^2,\qquad \frac{\partial\operatorname{MSE}}{\partial\hat y_i}=\frac2n(\hat y_i-y_i).

If all predictions share a constant cc, differentiating gives 2(c−yˉ)2(c-\bar y), so the empirical mean minimizes the objective. In the opening example, yˉ=4\bar y=4 and the minimum MSE is 8. Multiplying the objective by a positive constant, such as 1/21/2, leaves this minimizer unchanged while scaling gradients. D2L, Section 3.1.1.2

The population statement is stronger. At a fixed input xx, let m(x)=E[Y∣X=x]m(x)=E[Y\mid X=x] and assume a finite conditional second moment. Expanding around that mean gives:

E[(Y−c)2∣X=x]=Var⁡(Y∣X=x)+(m(x)−c)2.E[(Y-c)^2\mid X=x]=\operatorname{Var}(Y\mid X=x)+(m(x)-c)^2.

The cross term vanishes because E[Y−m(x)∣X=x]=0E[Y-m(x)\mid X=x]=0. The first term does not depend on cc, and the second is minimized at c=m(x)c=m(x). 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 Yi∣xi∼N(fθ(xi),σ2)Y_i\mid x_i\sim\mathcal N(f_\theta(x_i),\sigma^2) for fixed σ2>0\sigma^2>0. The negative log-likelihood is:

−log⁡p(y∣X,θ)=n2log⁡(2πσ2)+12σ2∑i(yi−fθ(xi))2.-\log p(y\mid X,\theta)=\frac n2\log(2\pi\sigma^2)+\frac1{2\sigma^2}\sum_i(y_i-f_\theta(x_i))^2.

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 nn prediction gradients takes O(n)O(n) work; the returned gradient list requires O(n)O(n) space. The constant fit also takes O(n)O(n) 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 n−1n-1.

Name the quantity before interpreting it

  1. What is RMSE for the constant prediction 4 in the opening example? Answer: 8≈2.828\sqrt8\approx2.828 in the target’s original units.
  2. 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.
  3. Does MSE require Gaussian targets? Answer: no. Gaussian assumptions justify one likelihood interpretation; the mean-minimization identity requires a finite second moment.
  4. 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?

Choose one answer

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

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.