AI Wiki中文/EN

Expectation and variance

期望与方差

Calculate a probability-weighted average and spread, distinguish population quantities from sample estimates, and see where independence matters.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The average need not be an observed value

An invented batch task takes 0, 2, or 8 minutes with probabilities 1/4,1/2,1/41/4,1/2,1/4. Its expected duration is 3 minutes, although no individual task takes exactly 3. Another system always takes 3 minutes. The means agree; the variability does not.

An expected value summarizes a distribution through a weighted average. Variance measures squared deviations from that average. Neither statistic alone tells you the whole distribution or the probability of a deadline miss. In the first model, a deadline of 5 minutes is missed with probability 1/41/4; in the constant model it is never missed.

Average values, then average squared deviations

For a discrete random variable, expectation weights each possible numerical value by its probability. With density pp, replace the sum by an integral. A finite expectation requires absolute integrability, and a finite variance requires a finite second moment:

μ=E[X]=∑xxp(x),E[X]=∫−∞∞xp(x) dx,Var⁡(X)=E[(X−μ)2].\mu=E[X]=\sum_x xp(x),\qquad E[X]=\int_{-\infty}^{\infty}xp(x)\,dx,\qquad \operatorname{Var}(X)=E[(X-\mu)^2].

The two expressions for the mean concern the discrete and density cases respectively. For a function gg, compute E[g(X)]E[g(X)] by weighting g(x)g(x) over the original distribution; do not replace it with g(E[X])g(E[X]) without justification. MML, Sections 6.4.1–6.4.3

Expanding the square gives:

Var⁡(X)=E[X2]−2μE[X]+μ2=E[X2]−μ2.\operatorname{Var}(X)=E[X^2]-2\mu E[X]+\mu^2=E[X^2]-\mu^2.

In the task example, E[X]=3E[X]=3, E[X2]=18E[X^2]=18, and variance is 9 square minutes. Standard deviation is 9=3\sqrt9=3 minutes. Adding 10 minutes to every outcome changes the mean to 13 but leaves variance unchanged. Multiplying durations by 60 converts minutes to seconds and multiplies variance by 60260^2.

Linearity of expectation needs no independence when the expectations are finite. Variances require a covariance term:

E[aX+bY]=aE[X]+bE[Y],Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)+2Cov⁡(X,Y).E[aX+bY]=aE[X]+bE[Y],\qquad \operatorname{Var}(X+Y)=\operatorname{Var}(X)+\operatorname{Var}(Y)+2\operatorname{Cov}(X,Y).

Here Cov⁡(X,Y)=E[(X−E[X])(Y−E[Y])]\operatorname{Cov}(X,Y)=E[(X-E[X])(Y-E[Y])]. Independence implies zero covariance when second moments exist; zero covariance alone does not generally imply independence. Setting Y=XY=X gives Var⁡(2X)=4Var⁡(X)\operatorname{Var}(2X)=4\operatorname{Var}(X), exposing the error in adding variances while ignoring dependence. Deep Learning, Section 3.8

Compute exact weighted moments

This complete Python example uses finite rational values and probabilities. It separately computes the descriptive variance of four observations and the corrected estimator often used for an i.i.d. sample.

from fractions import Fraction as F

def moments(points):
    if not points or any(p < 0 for _, p in points):
        raise ValueError("nonempty nonnegative probabilities required")
    if sum(p for _, p in points) != 1:
        raise ValueError("probabilities must sum to one")
    mean = sum(x*p for x, p in points)
    variance = sum(p*(x-mean)**2 for x, p in points)
    return mean, variance

points = [(F(0), F(1,4)), (F(2), F(1,2)), (F(8), F(1,4))]
mean, variance = moments(points)
assert (mean, variance) == (3, 9)
assert sum(p*x*x for x,p in points) == 18
assert moments([(2*x+7,p) for x,p in points]) == (13,36)
assert moments([(F(3),F(1))]) == (3,0)

observed = list(map(F, [0,2,2,8]))
sample_mean = sum(observed)/len(observed)
centered_sum = sum((x-sample_mean)**2 for x in observed)
assert centered_sum/len(observed) == 9
assert centered_sum/(len(observed)-1) == 12

For kk support points, the two passes use O(k)O(k) arithmetic operations and constant additional working storage beyond the supplied list. Fraction bit costs depend on the values. Floating-point implementations should avoid subtracting two almost equal large moments when computing variance; a centered two-pass calculation or an appropriate online algorithm is usually safer. MML, Section 6.4.3

A sample estimate is not a population fact

The descriptive variance of observed values uses denominator nn. For n≥2n\ge2 independent observations sharing the same distribution (i.i.d.) with finite variance, dividing the centered sum of squares by n−1n-1 instead produces an unbiased estimator of population variance. This is not an arbitrary formatting choice: estimating the mean from the same observations changes the expected centered sum.

To see why, write the sum around the true mean μ\mu and subtract the fitted-mean correction:

∑i(Xi−Xˉ)2=∑i(Xi−μ)2−n(Xˉ−μ)2.\sum_i(X_i-\bar X)^2=\sum_i(X_i-\mu)^2-n(\bar X-\mu)^2.

Under the stated assumptions, the expected terms on the right are nσ2n\sigma^2 and σ2\sigma^2, leaving (n−1)σ2(n-1)\sigma^2. Correlated observations or different sampling designs need different reasoning. Unbiasedness is a repeated-sampling property, not a promise that one estimate equals the truth.

Mean and variance can also fail to exist as finite quantities for heavy-tailed distributions. A symmetric density alone does not establish a finite mean. Even when both statistics exist, they cannot identify a general distribution. Keep tail probabilities and application-specific costs visible.

Separate the summaries

  1. Is E[X2]E[X^2] equal to (E[X])2(E[X])^2 here? Answer: no; they are 18 and 9. Their difference is the variance.
  2. What is the variance of 2X+72X+7? Answer: 36; shifting changes no centered deviation, while scaling squares the factor.
  3. For observations [0,2,2,8][0,2,2,8], why can variance be reported as 9 or 12? Answer: 9 describes the empirical distribution with denominator 4; 12 uses denominator 3 to estimate an i.i.d. population variance.
  4. Does an expected duration of 3 imply a typical run must finish by minute 3? Answer: no. The mean alone is not a deadline guarantee or a quantile.

What an average hides during evaluation

Machine-learning risk is an expected loss; a test-set average estimates it under sampling assumptions. Averaging across runs can hide unstable outcomes, and averaging across groups can hide concentrated errors. Report what is being averaged, the units, the sampling process, and variability relevant to the decision. These distinctions also prepare the bias–variance decomposition and Monte Carlo estimation.

Make a prediction, then check

X has mean 3 and variance 9. What is the variance of 2X+7?

Choose one answer

Learning objectives

  • Calculate weighted means, variances, units, and statistics after affine transformations.
  • Explain covariance terms and the different purposes of denominators n and n−1 in variance calculations.

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. Deep Learning — Chapter 3: Probability and Information Theory
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016

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 mean 3, second moment 18, variance 9, corrected sample variance 12, and mean 13/variance 36 for 2X+7.
  • Checked 30 seeded weighted distributions using centered moments, raw moments, pairwise squared differences, and affine transforms; verified finite-moment, covariance, and i.i.d. assumptions behind n−1.
  • 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.