AI Wiki中文/EN

Bias and variance

偏差与方差

Separate prediction bias, training variability and fresh-response noise with an exactly enumerated experiment; explain why the identity does not force a U-shaped curve.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A worse fit can make a better prediction

Imagine a sensor whose readings are either −1/2 or 3/2, equally likely and independent. Its true mean is 1/2. We get only two training readings and must predict a fresh one. These numbers define a teaching experiment; they are not measurements from a real device.

One rule predicts the training average. Another predicts one third of that average, pulling it toward zero. The first rule is unbiased: across all four equally likely training sequences, its predictions average to 1/2. The second rule is biased: its predictions average to 1/6. Yet the second rule has lower expected squared error on the next reading: 7/6 instead of 3/2. Being right on average is not enough if individual fits fluctuate too much.

Bias measures the difference between an average fitted prediction and the target conditional mean. Variance measures how much that prediction changes when the training procedure is repeated. Neither is the error of one particular prediction. Deep Learning, Section 5.4.4 relates their squared-error contributions; the example here computes them without simulation noise.

Prediction error for three rules

New-response noiseSquared biasPrediction variance
a = 0MSE = 5/4

New-response noise 1 +Squared bias 1/4 +Prediction variance 0

a = 1/3MSE = 7/6

New-response noise 1 +Squared bias 1/9 +Prediction variance 1/18

a = 1MSE = 3/2

New-response noise 1 +Squared bias 0 +Prediction variance 1/2

μ=1/2, two training readings, independent ±1 noise. Bars share one scale and use exact averages over every training sequence; at a=1/3, the variance reduction exceeds the added squared bias.

Specify what is random before splitting the error

Fix a query x. Write f(x)=E[Y∣X=x]f(x)=E[Y\mid X=x] and σ2(x)=Var⁡(Y∣X=x)\sigma^2(x)=\operatorname{Var}(Y\mid X=x). Let D be the random training data and, if relevant, include random initialization or sampling in the training procedure. Its fitted prediction is f^D(x)\widehat f_D(x); define m(x)=ED[f^D(x)]m(x)=E_D[\widehat f_D(x)]. Assume the required second moments are finite and the new response at x is independent of the training procedure. Then

ED,Y∣x[(Y−f^D(x))2]=σ2(x)+(m(x)−f(x))2+ED[(f^D(x)−m(x))2].E_{D,Y\mid x}[(Y-\widehat f_D(x))^2]=\sigma^2(x)+(m(x)-f(x))^2+E_D[(\widehat f_D(x)-m(x))^2].

The terms are conditional noise, squared bias, and prediction variance. To derive this identity, write the residual as (Y−f)+(f−m)+(m−f^D)(Y-f)+(f-m)+(m-\widehat f_D). After squaring, all three cross terms have expectation zero: the centered response and centered prediction have mean zero, and their independence removes their product. Averaging the identity over the intended test-input distribution gives overall expected test risk. Cornell CS4780, Lecture 12, decomposition

For the sensor, Yi=μ+εiY_i=\mu+\varepsilon_i with independent equiprobable noises −1 and +1. The estimator is μ^a=aYˉ\widehat\mu_a=a\bar Y, with a fixed before seeing the sample. For n training readings,

E[μ^a]=aμ,Bias⁡=(a−1)μ,Var⁡(μ^a)=a2n.E[\widehat\mu_a]=a\mu,\qquad \operatorname{Bias}=(a-1)\mu,\qquad \operatorname{Var}(\widehat\mu_a)=\frac{a^2}{n}. R(a)=E[(Ynew−μ^a)2]=1+(a−1)2μ2+a2n.R(a)=E[(Y_{\mathrm{new}}-\widehat\mu_a)^2]=1+(a-1)^2\mu^2+\frac{a^2}{n}.

Differentiate this quadratic. The best a within [0,1] is a∗=μ2/(μ2+1/n)a_* = \mu^2/(\mu^2+1/n). At μ=1/2 and n=2 it is 1/3. This is an oracle choice using the true mean; it explains the trade-off but cannot be used as a data-free tuning recipe when μ is unknown.

Fixed shrink factor aSquared biasPrediction varianceNew-response noiseExpected test MSEExpected training MSE
01/4015/45/4
1/31/91/1817/65/6
101/213/21/2

The training column is different for a reason: a training label also helped determine its own prediction. It does not satisfy the independence assumption above. Using ∑i(Yi−aYˉ)2=∑i(Yi−Yˉ)2+n(1−a)2Yˉ2\sum_i(Y_i-a\bar Y)^2=\sum_i(Y_i-\bar Y)^2+n(1-a)^2\bar Y^2 gives

E[1n∑i(Yi−aYˉ)2]=1−1n+(1−a)2(μ2+1n).E\left[\frac1n\sum_i(Y_i-a\bar Y)^2\right]=1-\frac1n+(1-a)^2\left(\mu^2+\frac1n\right).

Thus the unbiased sample mean has the best training fit among these choices and the worst expected test error. The gap is calculated over repetitions; one observed train/test split need not display this ordering.

Enumerate every possible training sequence

This complete program uses exact fractions. It fits all 2n2^n sequences of noisy labels, then averages over a separate new response. It evaluates a deliberately small known distribution, not an estimate of an unknown real-world noise floor.

from fractions import Fraction as F
from itertools import product

def exact(v):
    if type(v) is not int and not isinstance(v, F):
        raise ValueError("integer or Fraction required")
    return F(v)

def experiment(n, mu, shrink):
    # All features are identical; only independent label noise varies.
    if type(n) is not int or not 1 <= n <= 12:
        raise ValueError("enumeration requires 1 <= n <= 12")
    mu, a = exact(mu), exact(shrink)
    if not 0 <= a <= 1:
        raise ValueError("shrink must be in [0,1]")
    count = 2**n
    s1 = s2 = training = test = F(0)
    for signs in product((-1, 1), repeat=n):
        labels = [mu+e for e in signs]
        pred = a*sum(labels)/n
        s1 += pred
        s2 += pred**2
        training += sum((v-pred)**2 for v in labels)/n
        # A NEW, independent label has its own two possible noises.
        test += sum((mu+e-pred)**2 for e in (-1, 1))/2
    mean = s1/count
    bias2 = (mean-mu)**2
    variance = s2/count-mean**2
    result = dict(mean=mean, bias2=bias2, variance=variance,
                  noise=F(1), train=training/count, test=test/count)
    assert result["test"] == bias2+variance+1
    return result

for a in (F(0), F(1,3), F(1)):
    print(a, experiment(2, F(1,2), a))
r = experiment(2, F(1,2), F(1,3))
assert (r["bias2"],r["variance"],r["test"]) == (F(1,9),F(1,18),F(7,6))
assert r["train"] == F(5,6)
assert experiment(2,F(1,2),1)["train"] == F(1,2)

For each shrink factor, the program takes O(n·2ⁿ) arithmetic operations and O(n) working storage; fraction bit costs are additional. The cap of twelve samples makes the exponential enumeration explicit. Analytic formulas handle larger n cheaply; empirical repeated-fit studies usually use resampling or new datasets instead.

Change μ to four. Strong shrinkage toward zero now introduces much more error because the signal is far from the shrinkage target. Change n while keeping a=1: variance becomes 1/n. Change n while keeping a=1/3 and a nonzero μ: variance decreases, but the nonzero bias persists. These are properties of specified procedures, not of the word “simple.”

The identity is exact; a U-shaped curve is not a theorem

The decomposition does not force bias to decrease or variance to increase with parameter count. Both depend on the data distribution, sample size, model, optimizer, regularization and the quantity predicted. In particular, finite-sample bias is not defined only by what happens with infinite data. An estimator’s bias can change with n; approximation error from a restricted function class is a related but distinct idea.

The familiar U-shaped sketch is useful in some regimes, but cannot be substituted for measurements. Belkin and colleagues report double-descent curves for specified model families and datasets, including minimum-norm random-feature fits. That observation does not invalidate the squared-error identity or establish a universal advantage for larger networks. Their 2019 version, Sections 1–2 states the interpolation setup and the rule for selecting among multiple fits.

The three-term equation is for squared loss. Accuracy and zero-one classification loss do not automatically have the same decomposition. Statistical estimator bias is also distinct from social bias or group disparities; this equation alone does not assess fairness.

The “irreducible” noise term is relative to the available features and target distribution. Additional informative measurements may reduce conditional variance. A distribution shift changes the reference f and noise, so an old decomposition need not describe deployment. Leakage, optimization failure and corrupted labels can also create a large train/test gap; the gap by itself does not identify a unique cause. D2L, Sections 3.6.1–3.6.2 separates training error from the distributional quantity we want to predict.

Try to defeat an overgeneralization

  1. Why does the a=1/3 rule beat the unbiased rule in the sensor example? Answer: its variance falls from 1/2 to 1/18, more than compensating for squared bias 1/9. New-response noise remains one for both.
  2. Can the same decomposition be applied to a training label as if it were a new independent response? Answer: not without retaining the dependence terms. For n=2 and a=1, the expected training MSE is 1/2, whereas the new-response risk is 3/2.
  3. If μ=0, which a minimizes risk in this known toy distribution? Answer: a=0, giving risk one. This uses knowledge of the true mean; it does not authorize setting every real-world prediction to zero.
  4. Does a model with more parameters have to have larger variance? Answer: no. The identity imposes no monotonic dependence on parameter count. Specify the training procedure and distribution, then calculate or measure the terms.

Use repeated fits to ask a narrower question

For an actual experiment, fix the data-generating or resampling protocol, sample size, test inputs, loss and training algorithm. Record predictions from multiple fits. Their variation estimates something about that protocol; changing only the random seed measures a different source of variation from drawing new training datasets. If both vary, the law of total variance separates expected seed variance conditional on D from variance across the seed-averaged fits.

Estimating bias is harder because the true f is generally unknown. Synthetic experiments make it known, which is why they are useful for checking a claim. On real data, report validation performance and uncertainty from a defensible protocol instead of labeling two observed loss numbers as exact bias and variance. Train/validation/test splits and regularization provide the next operational steps.

Make a prediction, then check

Must an unbiased estimator have lower prediction MSE than a biased one?

Choose one answer

Learning objectives

  • Derive the squared prediction-error decomposition under explicit independence and finite-second-moment conditions.
  • Exactly compute training and test errors for shrinkage rules, distinguishing finite-sample bias, variability and noise.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Machine Learning Basics, §5.4
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. Cornell CS4780 Spring 2024 — Lecture 12: Bias-Variance Tradeoff
    Cornell University · 2024
  3. Reconciling modern machine learning practice and the bias-variance trade-off
    Mikhail Belkin; Daniel Hsu; Siyuan Ma; Soumik Mandal · 2019
  4. Dive into Deep Learning — 3.6 Generalization
    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: source locations, independent numerical verification and full bilingual rereading; some drafts by an agent reviewed by the parent; no independent human peer review.

  • Independently verified54 enumerated cases using binomial count weights, including training error and test gap2a/n; checked oracle shrinkage by completing the square and the heteroskedastic/seed total-variance decomposition.
  • Figure stores exact rational error components and is compared with the program distribution; oracle a uses the true mean and is not a data-free tuning rule for an unknown mean.
  • The parent executed all19 independent learning-theory/neural tests. Structure checks compare bilingual anchors,display equations,code and sources; parent reread four answers and arguments. Historical articles make no code-execution claim.

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.