08 / 22 · Random Variables
Expectation and variance
A distribution summarized by two numbers: the expectation as a balance point and long-run average, linearity and the indicator trick (Secret Santa, shared birthdays, the coupon collector), the expectation of a function and Jensen's inequality, the variance and the 1/√n rule for averages, and moment and characteristic functions.
On this page 11
A distribution is a whole function, and most questions need much less: where is it centred, and how far from the centre do the values typically fall? The expectation and the variance answer these two questions. They are also the quantities machine learning optimizes and reports: a risk is an expected loss, an accuracy is an expected indicator, and the error bar of a benchmark is a standard deviation. This note defines both, shows the one property that makes expectations easy to compute, linearity, and derives the rule for averages that the opening note stated without proof.
Notation. is the expectation (mean) of , often ; its variance, ; its standard deviation. are i.i.d. if they are independent and have the same distribution; is their average.
Expectation#
The expectation weights every value by its probability:
A fair die has , a value it never shows. Two readings make the definition natural. Physically, is the balance point: a rod loaded with mass at position balances there. Statistically, it is the long-run average: the average of many independent copies of approaches , which the law of large numbers will prove. The distributions of the previous notes have the means
| Distribution | |||||||
|---|---|---|---|---|---|---|---|
| Mean |
The mean is one of several centres. For a symmetric distribution the mean and the median coincide; for a skewed one they separate, and the mean is pulled toward the long tail:
Mode, median and mean of a skewed distribution
This is why reports of incomes or house prices quote the median: a few very large values move the mean far more than they move the median.
Linearity#
For any random variables and constants,
Written as a weighted sum over outcomes rather than over values, the expectation is linear in the random variable, so the proof is one line, and it needs no independence. Its power comes from indicators: . A count of events is a sum of indicators, so its expectation is a sum of probabilities, however the events depend on each other.
- Binomial mean. is a sum of indicators, each with probability : , without touching the PMF.
- Secret Santa. The axioms note needed inclusion–exclusion to find that nobody draws their own name with probability close to . The expected number of people who draw their own name is a one-liner: person does with probability , so the expectation is , for every group size.
- Shared birthdays. Among 23 people there are pairs, each sharing a birthday with probability ; the expected number of shared pairs is .
- The coupon collector. How many rolls of a die until every face has appeared? Split the wait into six stages, one per new face; each stage is geometric, and linearity adds their means:
How many rolls it takes to see every face of a die
With equally likely coupons the same argument gives : about 519 packs to complete a collection of 100 stickers, most of them spent on the last few.
The expectation of a function#
To find , there is no need to find the distribution of first: weight of each value by the probability of the value,
For the log-normal with of the previous note, completing the square gives
the mean in the figure above. It is not : in general . For a convex (a function that bends upward) the inequality has a direction, Jensen’s inequality:
With it says . With the concave it reverses, , and this one line gives the evidence lower bound of the variational autoencoder and the fact that the KL divergence of the entropy note is never negative. In practice it is a warning: the average of a loss over predictions is not the loss of the average prediction.
Variance#
The variance measures the typical squared distance from the mean:
The second form follows from linearity: . For a die, , so and . The standard deviation is in the units of , which makes it the number to report; the variance is the one that adds up.
| Distribution | |||||||
|---|---|---|---|---|---|---|---|
| Variance |
Two rules do most of the work. Shifting does not change the spread and scaling multiplies it: . And for independent and , variances add: ; the joint distributions note proves it and shows the extra covariance term for dependent variables.
The rule. For i.i.d. with variance , the two rules give
The average is times less variable than one observation in variance, but only times in standard deviation. A classifier with true accuracy , measured on 1,000 independent test examples, gets a measured accuracy with standard deviation , about one percentage point; halving that requires 4,000 examples.
Moment and characteristic functions#
Optional depth: moments beyond the variance, and the transforms that turn sums into products and prove the central limit theorem. The rest of the note does not depend on it.
The mean and the variance are built from the first two moments , . The third and fourth standardized moments, and , are the skewness and the kurtosis: lopsidedness, and how much of the variance comes from rare large deviations.
All the moments are packed into one function, the moment generating function
since the -th derivative of at is . Its main use is sums: for independent and , and the expectation of a product of independent variables factorizes, so . A Poisson() variable has ; multiplying two of them gives the MGF of Poisson(), and since an MGF that exists near 0 determines the distribution, the sum of independent Poisson variables is Poisson. The normal has , and the same argument shows that sums of independent normals are normal.
The MGF does not exist for heavy-tailed distributions such as the log-normal, where is infinite for every . The characteristic function always exists. Here is the imaginary unit, , and , so is a pair of ordinary expectations of bounded quantities, and . It also determines the distribution and turns sums into products. Its other property is Lévy’s continuity theorem, the tool behind the proof of the central limit theorem: the distributions of converge to the distribution of exactly when for every ; and if converges for every to a limit that is continuous at , that limit is the characteristic function of some distribution, to which the converge. The condition at matters: has , which tends to for every and equals at . The limit jumps at , it is not a characteristic function, and the distributions spread out without converging to any distribution.
What changed#
| A distribution | Its summaries | |
|---|---|---|
| Centre | a whole PMF or density | , a balance point and long-run average |
| Spread | , | |
| Sums | convolution of distributions | means always add; variances add under independence; MGFs multiply |
| Averages of | mean unchanged, standard deviation |
Limitations#
- The expectation may not exist. The Cauchy distribution, the ratio of two independent standard normals, has a density but no mean: its averages do not settle however many samples are taken (see the code).
- Means are sensitive to tails. A single extreme value can move a mean arbitrarily far; the median is robust, and for skewed quantities such as latencies, incomes or losses on rare inputs the mean alone misleads.
- Two numbers do not describe a shape. Distributions with the same mean and variance can have very different tails, which is exactly where risk, failures and outliers live.
What you should remember#
- or : a balance point and the long-run average.
- Linearity: for any dependence; turns expected counts into sums of probabilities.
- ; in general , and for convex (Jensen).
- ; ; variances of independent variables add.
- The average of i.i.d. variables has standard deviation .
- MGFs and characteristic functions turn sums of independent variables into products.
Code#
Each number of the note, computed exactly or by simulation:
import numpy as np, math
from scipy import stats
rng = np.random.default_rng(0)
# a fair die: the variance from the definition and as E[X^2] - (E[X])^2
die = np.arange(1, 7)
mean = die.mean()
print(mean, round(((die - mean) ** 2).mean(), 4), round((die**2).mean() - mean**2, 4)) # 3.5 2.9167 2.9167
# linearity with indicators: own names drawn among 20 people; shared-birthday pairs among 23
perm = np.argsort(rng.random((100_000, 20)), axis=1)
print(round((perm == np.arange(20)).sum(axis=1).mean(), 3), round(math.comb(23, 2) / 365, 4)) # 0.996 0.6932
# coupon collector: rolls until all six faces have appeared
rolls = []
for _ in range(20_000):
seen, n = set(), 0
while len(seen) < 6:
seen.add(int(rng.integers(6))); n += 1
rolls.append(n)
print(round(sum(6 / k for k in range(1, 7)), 2), round(float(np.mean(rolls)), 2)) # 14.7 14.71
# the expectation of a function: E[e^X] for X ~ N(0, 1), against e^E[X] = 1 and the median of e^X
x = rng.normal(size=1_000_000)
print(round(float(np.exp(x).mean()), 3), round(math.exp(0.5), 4), round(float(np.median(np.exp(x))), 3)) # 1.645 1.6487 0.998
# the 1/sqrt(n) rule: accuracy measured on 1,000 test examples when the true accuracy is 0.9
print(round(math.sqrt(0.9 * 0.1 / 1000), 4), round(float(rng.binomial(1000, 0.9, 100_000).std()) / 1000, 4)) # 0.0095 0.0095
# generating functions: Poisson(2) + Poisson(3), independent, is Poisson(5)
s = rng.poisson(2, 1_000_000) + rng.poisson(3, 1_000_000)
print(round(float(s.mean()), 3), round(float(s.var()), 3), round(float((s == 5).mean()), 4), round(stats.poisson(5).pmf(5), 4)) # 4.998 5.004 0.1756 0.1755
# no mean at all: averages of Cauchy samples do not settle
c = rng.standard_cauchy(1_000_000)
print([round(float(c[:n].mean()), 2) for n in (10**3, 10**4, 10**5, 10**6)]) # [0.83, 2.88, 0.4, -0.23]
Next#
The expectation and the variance describe one random variable. Data come in several at once: a person’s height and weight, a word and the next one, a feature vector and a label. The next note describes several random variables together: joint and marginal distributions, independence, and the covariance and correlation that measure, partly, how they move together.
References#
- J. K. Blitzstein, J. Hwang. Introduction to Probability, 2nd ed. CRC Press, 2019. Chapter 4 (expectation, linearity, indicators, LOTUS, variance, the coupon collector), Chapter 6 (moments, moment generating functions).
- W. Feller. An Introduction to Probability Theory and Its Applications, Vol. 1, 3rd ed. Wiley, 1968. Chapter IX (random variables, expectation), Chapter XI (generating functions).
- A. N. Shiryaev. Probability-1, 3rd ed. Springer, 2016. Chapter 2, §6 (expectation as an integral), §12 (characteristic functions).