Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Expectation and variance

P1.D445 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Expectation turns a whole distribution into one number, its average, and variance says how far values stray from it. Training losses, gradient noise, normalization and initialization are all built from these two.

  • Mean squared error is the expectation of squared error, and the single number with the smallest expected squared error is the mean, which is why a regression model trained with MSE learns to predict averages. (P3.A2: Linear regression, coming soon)
  • A mini-batch gradient is an average of per-example gradients: its expectation is the full gradient (it is unbiased), and its noise shrinks like 1/B1/\sqrt{B} as the batch size BB grows. (P1.F4: Stochastic and mini-batch gradient descent, coming soon)
  • Normalization layers subtract a mean and divide by a standard deviation computed from the activations, so each layer sees inputs with mean 0 and variance 1. (P4.19: Normalization layers, coming soon)
  • Weight initialization chooses the variance of the random starting weights so that the variance of the signal stays stable from layer to layer instead of exploding or fading. (P4.12: Weight initialization, coming soon)
  • Dropout multiplies the surviving activations by 1/(1−p)1/(1-p) so that their expected value is the same with and without dropout. (P4.17: Regularization for neural nets, coming soon)

Before this: Probability basics, Random variables

After this lesson you can

  • Compute the expectation of a discrete variable as ∑x p(x)\sum x\,p(x) and of a continuous one as ∫x p(x) dx\int x\,p(x)\,dx, read it as a balance point and as a long-run average, and explain why it need not be a value the variable can take
  • Compute E[g(X)]=∑g(x) p(x)\mathbb{E}[g(X)]=\sum g(x)\,p(x) without finding the distribution of g(X)g(X), and say why E[g(X)]\mathbb{E}[g(X)] is not g(E[X])g(\mathbb{E}[X]) in general
  • Use linearity, E[aX+b]=a E[X]+b\mathbb{E}[aX+b]=a\,\mathbb{E}[X]+b and E[X+Y]=E[X]+E[Y]\mathbb{E}[X+Y]=\mathbb{E}[X]+\mathbb{E}[Y] (no independence needed), with indicator variables to count expected successes
  • Compute Var(X)=E[X2]−E[X]2\mathrm{Var}(X)=\mathbb{E}[X^2]-\mathbb{E}[X]^2 and the standard deviation, use Var(aX+b)=a2Var(X)\mathrm{Var}(aX+b)=a^2\mathrm{Var}(X), add variances of independent variables, and show that the average of nn independent draws has standard deviation σ/n\sigma/\sqrt{n}

Roll a fair die thousands of times and add up the results. The average of the rolls creeps towards 3.53.5, a number that no single roll can show. Where does 3.53.5 come from? And if you only roll 100100 times, how far from 3.53.5 should you expect the average to be?

Two numbers answer both questions. The expectation says where a distribution is centred. The variance says how widely it is spread around that centre. This lesson builds both from small tables, so you can check every number by hand.

The expectation: a weighted average

Let XX be a discrete random variable with PMF p(x)=P(X=x)p(x)=\mathbb{P}(X=x) (P1.D2). Its expectation, also called its expected value or mean, is

E[X]=∑xx p(x).\mathbb{E}[X]=\sum_x x\,p(x).

Multiply each value by its probability and add. People often write μ\mu (the Greek letter mu) for it. Read E[X]\mathbb{E}[X] as “the expectation of XX”.

For a fair die, every face has probability 16\frac16:

E[X]=1+2+3+4+5+66=216=3.5.\begin{aligned} \mathbb{E}[X]&=\frac{1+2+3+4+5+6}{6}\\ &=\frac{21}{6}=3.5 . \end{aligned}

Here is a smaller made-up example. Let XX take the values 0,1,2,30,1,2,3 with probabilities 0.1, 0.4, 0.3, 0.20.1,\,0.4,\,0.3,\,0.2. Then E[X]=0⋅0.1+1⋅0.4+2⋅0.3+3⋅0.2=1.6\mathbb{E}[X]=0\cdot0.1+1\cdot0.4+2\cdot0.3+3\cdot0.2=1.6. The plain average of the four values is 1.51.5, not 1.61.6: the values that are more likely get more say.

Why this is the average of many draws. Suppose you draw XX a thousand times and about 100100 draws give 00, 400400 give 11, 300300 give 22 and 200200 give 33. The ordinary average of the thousand numbers is (0⋅100+1⋅400+2⋅300+3⋅200)/1000=0⋅0.1+1⋅0.4+2⋅0.3+3⋅0.2(0\cdot100+1\cdot400+2\cdot300+3\cdot200)/1000=0\cdot0.1+1\cdot0.4+2\cdot0.3+3\cdot0.2. Each value is weighted by the fraction of draws that gave it, and in the long run that fraction is its probability. So E[X]\mathbb{E}[X] is what the ordinary average settles to. The law of large numbers (P1.D8) makes that precise.

The mean need not be a possible value. The die never shows 3.53.5, and the made-up example never gives 1.61.6. The mean is a property of the whole distribution, not a prediction of the next draw.

A fair price. A game pays you the number a die shows. The expected payment is 3.53.5, so over many plays you collect about 3.53.5 per play. If a play costs 44, you lose about 0.50.5 per play on average, though some single plays do win.

Two special cases. A constant cc (a variable with all its probability on one value) has E[c]=c\mathbb{E}[c]=c. A Bernoulli variable is 11 with probability pp and 00 otherwise: E[X]=1⋅p+0⋅(1−p)=p\mathbb{E}[X]=1\cdot p+0\cdot(1-p)=p. A special Bernoulli variable is the indicator of an event AA, written 1A1_A, which is 11 when AA happens and 00 when it does not. Its expectation is the probability of the event:

E[1A]=P(A).\mathbb{E}[1_A]=\mathbb{P}(A).

This small fact becomes powerful once you know linearity (below).

The mean as a balance point

Picture the number line as a plank, with a weight of size p(x)p(x) at each value xx. The expectation is the point where a fulcrum (the pivot a seesaw rests on) must sit for the plank to balance. Try it. Drag the bars, then use the button to move the fulcrum away from the mean and watch the plank tip.

Balance the histogram

Drag a bar up or down, or focus it and press the arrow keys (Shift for bigger steps). The other bars shrink or grow together so the total stays 1.

Balanced: the fulcrum is at the mean. The mean is 3.5 and the standard deviation (the typical distance from the mean) is 1.71. No bar stands at 3.5: the mean does not have to be a value X can take.
00.250.50.751012345678910mean 3.5 ± sd 1.71fulcrum = mean

probability of each value mean, with a bracket of one standard deviation each side (cut off at the edge of the plot)

mean 𝔼[X] = Σ x·p(x) = 3.5 𝔼[X²] = Σ x²·p(x) = 15.167 Var(X) = 𝔼[(X − mean)²] = 2.917 standard deviation = 1.708 check: 𝔼[X²] − 𝔼[X]² = 2.917
All the probabilities
xp(x)
00
10.167
20.167
30.167
40.167
50.167
60.167
70
80
90
100
A probability distribution on the values 0 to 10, as bars and as weights on a plank. Drag a bar (or focus it and use the arrow keys); the other bars rescale so the total stays 1. The fulcrum sits at the mean, and the dashed line and bracket show the mean and one standard deviation each side. “Move the fulcrum myself” lets you put the fulcrum anywhere, and the plank tips towards the mean. “Show Y = aX + b” shows how the mean and standard deviation change, by the rules and computed directly.

What to try:

  • Fair die. The weights sit on 11 to 66 and the fulcrum is at 3.53.5, between two faces: nothing is there, and it balances anyway.
  • Two humps. Put weight near 11 to 22 and near 88 to 99. The mean lands in the empty middle, at 55.
  • One bar. All the weight on one value: the mean is that value, and the bracket vanishes (no spread).
  • Move the fulcrum. Leave the mean and set the fulcrum to a smaller value. The plank tips to the right: each side may hold about the same total weight, but the pulls no longer cancel, because the weights on the right are, together, further from the fulcrum (weight times distance). Press “Put the fulcrum at the mean” to see it balance again; the fulcrum slider moves in steps of 0.10.1, so the button is the way to land exactly on a mean such as 1.471.47.

The balance has a one-line statement. The weight on each side pulls with strength (weight) ×\times (distance from the fulcrum), and the fulcrum is at the mean exactly when the pulls cancel:

∑xp(x) (x−μ)=0.\sum_x p(x)\,(x-\mu)=0 .

To check, expand: ∑xx p(x)−μ∑xp(x)=μ−μ⋅1=0\sum_x x\,p(x)-\mu\sum_x p(x)=\mu-\mu\cdot1=0. And no other point works, because ∑xp(x)(x−c)=μ−c\sum_x p(x)(x-c)=\mu-c is zero only when c=μc=\mu. The analogy to a physical seesaw (a center of mass) is exact for a discrete distribution; it breaks only in that a real plank has weight of its own, and ours does not.

Expectation of a continuous variable

For a continuous variable with density p(x)p(x) (P1.D2), the sum becomes an integral (P1.C9). Each thin strip of width dxdx at xx holds probability p(x) dxp(x)\,dx, and the expectation adds up xx times that:

E[X]=∫−∞∞x p(x) dx.\mathbb{E}[X]=\int_{-\infty}^{\infty}x\,p(x)\,dx .

For the uniform density on [0,1][0,1] (equal to 11 there, and 00 elsewhere): E[X]=∫01x dx=12\mathbb{E}[X]=\int_0^1 x\,dx=\tfrac12, the middle, as balance suggests. P1.C9 quoted the mean 11 for the density e−x\mathrm{e}^{-x} on x≥0x\ge0. Integration by parts confirms it: ∫0∞x e−xdx=[−xe−x]0∞+∫0∞e−xdx=0+1=1\int_0^\infty x\,\mathrm{e}^{-x}dx=\bigl[-x\mathrm{e}^{-x}\bigr]_0^\infty+\int_0^\infty\mathrm{e}^{-x}dx=0+1=1. The balance-point picture still works: the density is a plate of varying thickness, and the mean is where it balances.

Everything below is stated for discrete variables, with sums. For a continuous variable, replace ∑x…p(x)\sum_x\ldots p(x) by ∫…p(x) dx\int\ldots p(x)\,dx; the rules are the same.

Averaging a function of XX

Often you need the expected value of something computed from XX: its square, a loss, a score. You could work out the distribution of g(X)g(X) first, but you do not have to. The rule, sometimes called the “law of the unconscious statistician” (LOTUS), is

E[g(X)]=∑xg(x) p(x),\mathbb{E}[g(X)]=\sum_x g(x)\,p(x),

or, for a continuous variable, ∫g(x) p(x) dx\int g(x)\,p(x)\,dx.

Apply gg to each value, then weight by the probability of the original value. For a die, with g(x)=x2g(x)=x^2:

E[X2]=12+22+32+42+52+626=916≈15.17.\begin{aligned} \mathbb{E}[X^2]&=\frac{1^2+2^2+3^2+4^2+5^2+6^2}{6}\\ &=\frac{91}{6}\approx15.17 . \end{aligned}

Notice that E[X]2=3.52=12.25\mathbb{E}[X]^2=3.5^2=12.25. So E[g(X)]\mathbb{E}[g(X)] is not g(E[X])g(\mathbb{E}[X]) in general. Squaring before averaging gives more weight to the large values than squaring the average does. For the uniform density on [0,1][0,1] it is the same story: E[X2]=∫01x2dx=13\mathbb{E}[X^2]=\int_0^1x^2dx=\frac13, but E[X]2=14\mathbb{E}[X]^2=\frac14. The two agree for a straight-line gg (next section), and for a constant XX.

Go deeper Jensen’s inequality: which side is bigger

If gg is convex (its graph curves upward, like x2x^2 or ex\mathrm{e}^x), then E[g(X)]≥g(E[X])\mathbb{E}[g(X)]\ge g(\mathbb{E}[X]), for any XX whose expectations exist. If gg is concave (curves downward, like ln⁡x\ln x), the inequality reverses. This is Jensen’s inequality.

Check it for a die. With g(x)=exg(x)=\mathrm{e}^x: E[g(X)]≈106.1\mathbb{E}[g(X)]\approx106.1 and g(3.5)≈33.1g(3.5)\approx33.1. With g(x)=ln⁡xg(x)=\ln x: E[ln⁡X]=ln⁡(720)/6≈1.097\mathbb{E}[\ln X]=\ln(720)/6\approx1.097 and ln⁡3.5≈1.253\ln 3.5\approx1.253, smaller, as expected for a concave gg. For g(x)=x2g(x)=x^2 the gap is exactly the variance (defined below): 15.17−12.25=2.9215.17-12.25=2.92.

Jensen’s inequality appears in the derivation of the evidence lower bound (ELBO) used to train variational autoencoders (P8.3).

Losses are expectations. A model with parameters θ\boldsymbol{\theta} makes an error L(θ;x,y)L(\boldsymbol{\theta};x,y) on one example. If examples come from a distribution, the expected loss (also called the risk) is E[L]\mathbb{E}[L], the average error over everything the world can throw at the model. You cannot compute it, but you have NN examples, and the training loss L=1N∑iLi\mathcal{L}=\frac1N\sum_i L_i is the same formula with probability 1N\frac1N on each example. Training minimizes that average as a stand-in for the expected loss (P3.A2, P1.F3).

Linearity of expectation

Two rules make expectations easy to compute.

Scale and shift. For constants aa and bb,

E[aX+b]=a E[X]+b.\mathbb{E}[aX+b]=a\,\mathbb{E}[X]+b .

Change from Celsius to Fahrenheit: F=1.8C+32F=1.8C+32. If the mean temperature is 20 ∘20\,^\circC, the mean is 1.8⋅20+32=68 ∘1.8\cdot20+32=68\,^\circF. You can convert the mean, or convert every reading and then average: the same answer.

Sums. For any two random variables XX and YY with finite means,

E[X+Y]=E[X]+E[Y].\mathbb{E}[X+Y]=\mathbb{E}[X]+\mathbb{E}[Y].

This holds whether or not XX and YY are independent. Nothing about how they relate to each other is needed. Two dice give 3.5+3.5=73.5+3.5=7 for the expected total. If the second die were secretly always 77 minus the first, the total would be exactly 77 every time: still 77.

Go deeper Why sums need no independence (a short proof)

Let the sample space have outcomes ω\omega with probabilities P(ω)\mathbb{P}(\omega), and let XX and YY be numbers attached to each outcome (P1.D2). The expectation is E[X]=∑ωX(ω) P(ω)\mathbb{E}[X]=\sum_\omega X(\omega)\,\mathbb{P}(\omega), the same sum with outcomes in place of values. Then

E[X+Y]=∑ω(X(ω)+Y(ω))×P(ω)=∑ωX(ω)P(ω)+∑ωY(ω)P(ω)=E[X]+E[Y].\begin{aligned} \mathbb{E}[X+Y]&=\sum_\omega\bigl(X(\omega)+Y(\omega)\bigr)\\ &\qquad\times\mathbb{P}(\omega)\\ &=\sum_\omega X(\omega)\mathbb{P}(\omega)\\ &\quad+\sum_\omega Y(\omega)\mathbb{P}(\omega)\\ &=\mathbb{E}[X]+\mathbb{E}[Y]. \end{aligned}

The proof splits one sum into two and never asks how XX and YY move together. The same argument gives E[aX+b]=aE[X]+b\mathbb{E}[aX+b]=a\mathbb{E}[X]+b. Products are different: E[XY]=E[X]E[Y]\mathbb{E}[XY]=\mathbb{E}[X]\mathbb{E}[Y] needs independence (or at least zero covariance, P1.D7). For Y=XY=X it fails: E[X2]≠E[X]2\mathbb{E}[X^2]\ne\mathbb{E}[X]^2.

Counting with indicators. Linearity turns hard counting problems into sums of small probabilities. Write the count as a sum of indicators, take the expectation of each, and add.

  • Sixes in nn rolls. Let Ik=1I_k=1 if roll kk is a six. Then E[Ik]=16\mathbb{E}[I_k]=\frac16, and the number of sixes is I1+⋯+InI_1+\dots+I_n, with expectation n/6n/6. In 6060 rolls: 1010 sixes on average. (For independent rolls this is the binomial variable of P1.D3, whose mean is npnp.)
  • Fixed points of a shuffle. Shuffle nn hats and hand them back at random. Let Ik=1I_k=1 if person kk gets their own hat. Then E[Ik]=1n\mathbb{E}[I_k]=\frac1n, and the expected number of people with their own hat is n⋅1n=1n\cdot\frac1n=1, for any nn. The indicators are not independent: if n−1n-1 people have their own hat, the last one does too. Linearity does not care. (Enumerating all 120120 shuffles of 55 hats gives exactly 11.)

Variance and standard deviation: how spread out?

Two variables can have the same mean and very different behaviour. A die and a coin that pays 33 or 44 (each with probability 12\frac12) both have mean 3.53.5, but the die strays much further. The variance measures the typical squared distance from the mean:

Var(X)=E[(X−μ)2]=∑x(x−μ)2 p(x),\begin{aligned} \mathrm{Var}(X)&=\mathbb{E}\bigl[(X-\mu)^2\bigr]\\ &=\sum_x (x-\mu)^2\,p(x), \end{aligned} σ=Var(X).\sigma=\sqrt{\mathrm{Var}(X)} .

The square root σ\sigma (sigma) is the standard deviation. It has the same units as XX (metres, not square metres), so it is the number to quote. Roughly, it is how far a draw typically lies from the mean.

For the die, μ=3.5\mu=3.5, the distances from the mean are ±2.5,±1.5,±0.5\pm2.5,\pm1.5,\pm0.5, and

Var(X)=2(2.52+1.52+0.52)6=12.5+4.5+0.56=3512≈2.917,\begin{aligned} \mathrm{Var}(X)&=\frac{2(2.5^2+1.5^2+0.5^2)}{6}\\ &=\frac{12.5+4.5+0.5}{6}\\ &=\frac{35}{12}\approx2.917, \end{aligned}

so σ≈1.708\sigma\approx1.708.

There is a shortcut. Expand the square and use linearity:

Var(X)=E[X2−2μX+μ2]=E[X2]−2μ E[X]+μ2=E[X2]−μ2.\begin{aligned} \mathrm{Var}(X)&=\mathbb{E}[X^2-2\mu X+\mu^2]\\ &=\mathbb{E}[X^2]-2\mu\,\mathbb{E}[X]+\mu^2\\ &=\mathbb{E}[X^2]-\mu^2 . \end{aligned}

For the die: 916−494=182−14712=3512\frac{91}{6}-\frac{49}{4}=\frac{182-147}{12}=\frac{35}{12}, the same. In words: the mean of the squares minus the square of the mean. The widget above shows both ways, and they agree for every setting. (The shortcut can lose accuracy on a computer when the mean is huge and the spread is small, because subtracting two nearly equal numbers throws away digits; computers store numbers with limited precision, which P1.G1 covers.)

Facts worth knowing:

  • Var(X)≥0\mathrm{Var}(X)\ge0, because it averages squares. It is 00 exactly when XX is a constant (strictly: has a single value with probability 11). The one-bar preset shows it.
  • For a Bernoulli variable with P(X=1)=p\mathbb{P}(X=1)=p: E[X2]=p\mathbb{E}[X^2]=p, so Var(X)=p−p2=p(1−p)\mathrm{Var}(X)=p-p^2=p(1-p). It is largest, 14\frac14, at p=12p=\frac12.
  • For the uniform density on [0,1][0,1]: Var(X)=13−14=112≈0.083\mathrm{Var}(X)=\frac13-\frac14=\frac1{12}\approx0.083 and σ≈0.289\sigma\approx0.289.
  • Why squares, not absolute distances? The mean absolute deviation E∣X−μ∣\mathbb{E}|X-\mu| is also a spread, but the square is smooth (it has a derivative everywhere), and, as shown below, variances add in a clean way. The standard deviation is not “the average distance”: it is the square root of the average squared distance, and it is at least as large as the average absolute distance.
  • The standard deviation alone does not tell you how likely a draw is to be far from the mean; that depends on the distribution (for a Gaussian, about 4.6%4.6\% of draws lie more than 2σ2\sigma from the mean; P1.D3).

Rules for variance, and standardizing

Adding a constant slides every value the same distance, so the spread does not change. Multiplying by aa stretches every distance by ∣a∣|a|, so the variance grows by a2a^2:

Var(aX+b)=a2 Var(X),\mathrm{Var}(aX+b)=a^2\,\mathrm{Var}(X),

so the standard deviation of aX+baX+b is ∣a∣ σ|a|\,\sigma.

Check with the made-up example (E[X]=1.6\mathbb{E}[X]=1.6, E[X2]=3.4\mathbb{E}[X^2]=3.4, so Var(X)=0.84\mathrm{Var}(X)=0.84). For Y=2X+1Y=2X+1: E[Y]=4.2\mathbb{E}[Y]=4.2 and Var(Y)=4⋅0.84=3.36\mathrm{Var}(Y)=4\cdot0.84=3.36. The widget’s “Show Y = aX + b” button computes both the rule and the direct value for any setting. The unit conversion again: Celsius readings with σ=5 ∘\sigma=5\,^\circC become Fahrenheit readings with σ=1.8⋅5=9 ∘\sigma=1.8\cdot5=9\,^\circF, and the +32+32 does nothing to the spread.

Standardizing. Subtract the mean, then divide by the standard deviation:

Z=X−μσ.Z=\frac{X-\mu}{\sigma}.

By the rules, E[Z]=0\mathbb{E}[Z]=0 and Var(Z)=1σ2Var(X)=1\mathrm{Var}(Z)=\frac{1}{\sigma^2}\mathrm{Var}(X)=1. The value ZZ counts how many standard deviations XX lies from its mean, so a score of 8585 when the mean is 7070 and σ=10\sigma=10 has Z=1.5Z=1.5. This puts quantities with different units on one scale.

Intuition

The mean is where the distribution balances. The variance is how hard it would be to turn the plank: weight far from the fulcrum counts a lot, because distances are squared. Adding a constant to XX slides the plank without changing its shape, so the mean moves and the spread does not. Multiplying by aa stretches the plank, so the spread stretches too.

The analogy of a seesaw is a picture of the mean. Variance is the moment of inertia about the balance point in physics (with total weight 11), which is a little less familiar; if the picture does not help, use the plain description: the mean of the squared distances from the mean.

Math

For a variable with finite mean and variance:

E[X]=∑xx p(x)E[g(X)]=∑xg(x) p(x)E[aX+b]=a E[X]+b\begin{aligned} \mathbb{E}[X]&=\sum_x x\,p(x)\\ \mathbb{E}[g(X)]&=\sum_x g(x)\,p(x)\\ \mathbb{E}[aX+b]&=a\,\mathbb{E}[X]+b \end{aligned}Var(X)=E[(X−μ)2]=E[X2]−μ2Var(aX+b)=a2 Var(X)\begin{aligned} \mathrm{Var}(X)&=\mathbb{E}[(X-\mu)^2]\\ &=\mathbb{E}[X^2]-\mu^2\\ \mathrm{Var}(aX+b)&=a^2\,\mathrm{Var}(X) \end{aligned}

For any X,YX,Y, E[X+Y]=E[X]+E[Y]\mathbb{E}[X+Y]=\mathbb{E}[X]+\mathbb{E}[Y]. For independent X,YX,Y,

Var(X+Y)=Var(X)+Var(Y).\begin{aligned} \mathrm{Var}(X+Y)&=\mathrm{Var}(X)\\ &\quad+\mathrm{Var}(Y). \end{aligned}

Code

NumPy computes means and variances of data with np.mean and np.var. For a PMF, write the sums yourself: weight the values by the probabilities.

import numpy as np

x = np.array([0, 1, 2, 3])
p = np.array([0.1, 0.4, 0.3, 0.2])

mean = (x * p).sum()                  # 1.6
var = ((x - mean) ** 2 * p).sum()     # 0.84
print(mean, var, (x**2 * p).sum() - mean**2)

Variances of sums, and the average of many draws

Do variances add? Not always. If Y=XY=X, then X+Y=2XX+Y=2X has variance 4 Var(X)4\,\mathrm{Var}(X), not 2 Var(X)2\,\mathrm{Var}(X). If Y=−XY=-X, then X+Y=0X+Y=0 has no spread at all. The general rule is

Var(X+Y)=Var(X)+Var(Y)+2 Cov(X,Y),\begin{aligned} \mathrm{Var}(X+Y)&=\mathrm{Var}(X)+\mathrm{Var}(Y)\\ &\quad+2\,\mathrm{Cov}(X,Y), \end{aligned}

where the covariance measures how XX and YY move together (P1.D7). When XX and YY are independent (knowing one tells nothing about the other; P1.D5), the covariance is zero and the variances add. Zero covariance is enough, and weaker than independence. The expectation of a sum needed none of this; the variance of a sum does.

Go deeper Where the cross term comes from

Write X−μX=X~X-\mu_X=\tilde X and Y−μY=Y~Y-\mu_Y=\tilde Y for the deviations from the means. The deviation of X+YX+Y from its mean is X~+Y~\tilde X+\tilde Y, so

Var(X+Y)=E[(X~+Y~)2]=E[X~2]+E[Y~2]+2 E[X~Y~].\begin{aligned} \mathrm{Var}(X+Y)&=\mathbb{E}[(\tilde X+\tilde Y)^2]\\ &=\mathbb{E}[\tilde X^2]+\mathbb{E}[\tilde Y^2]\\ &\quad+2\,\mathbb{E}[\tilde X\tilde Y]. \end{aligned}

The last expectation is the covariance, Cov(X,Y)=E[(X−μX)(Y−μY)]\mathrm{Cov}(X,Y)=\mathbb{E}[(X-\mu_X)(Y-\mu_Y)]. It is 00 when XX and YY are independent, because then E[X~Y~]=E[X~]E[Y~]=0⋅0\mathbb{E}[\tilde X\tilde Y]=\mathbb{E}[\tilde X]\mathbb{E}[\tilde Y]=0\cdot0. For two independent dice, Var(X+Y)=3512+3512=356≈5.83\mathrm{Var}(X+Y)=\frac{35}{12}+\frac{35}{12}=\frac{35}{6}\approx5.83 (a simulation gives 5.825.82). For Y=7−XY=7-X the two dice move in opposite directions: the sum is always 77 and the variance is 00.

The average of nn independent draws. Let X1,…,XnX_1,\dots,X_n be independent draws from the same distribution, each with mean μ\mu and standard deviation σ\sigma (the same finite σ\sigma). Their sum S=X1+⋯+XnS=X_1+\dots+X_n and their average Xˉ=S/n\bar X=S/n have

E[S]=nμVar(S)=nσ2sd(S)=σn\begin{aligned} \mathbb{E}[S]&=n\mu\\ \mathrm{Var}(S)&=n\sigma^2\\ \text{sd}(S)&=\sigma\sqrt n \end{aligned} E[Xˉ]=μVar(Xˉ)=nσ2n2=σ2nsd(Xˉ)=σn\begin{aligned} \mathbb{E}[\bar X]&=\mu\\ \mathrm{Var}(\bar X)&=\frac{n\sigma^2}{n^2}=\frac{\sigma^2}{n}\\ \text{sd}(\bar X)&=\frac{\sigma}{\sqrt n} \end{aligned}

The first line uses linearity and the addition of variances; the second divides by nn, and dividing by nn divides the variance by n2n^2. So:

  • The average is centred on the truth, E[Xˉ]=μ\mathbb{E}[\bar X]=\mu: it is an unbiased estimate of the mean (on average it is right, whatever nn).
  • Its noise shrinks like 1/n1/\sqrt n. A die has σ≈1.708\sigma\approx1.708. The average of n=4n=4 rolls has spread 0.8540.854, of 100100 rolls 0.1710.171, and of 10,00010{,}000 rolls 0.0170.017. To halve the noise you need four times the data.

Delivering a promise from P1.D1. That lesson said the typical gap between the number of heads and n/2n/2 is about 55 for 100100 flips and about 5050 for 10,00010{,}000. Here is why. A flip is a Bernoulli variable with p=12p=\frac12, so σ2=p(1−p)=14\sigma^2=p(1-p)=\frac14 and σ=12\sigma=\frac12. The number of heads is the sum of nn independent flips, with standard deviation 12n\frac12\sqrt n: that is 55 for n=100n=100 and 5050 for n=10,000n=10{,}000. The count gap grows like n\sqrt n. The relative frequency is the sum divided by nn, with standard deviation 12n\frac{1}{2\sqrt n}: 0.050.05 and 0.0050.005, the frequency gaps quoted there. (The standard deviation is the usual yardstick for “typical”. The average gap, ignoring its sign, is a bit smaller, about 0.80.8 of it: about 44 and 4040.) P1.D8 shows that the shape of this wobble is a bell curve, and that it shrinks to zero.

Mini-batch gradients. Let gig_i be the gradient of the loss on example ii and gˉ=1N∑igi\bar g=\frac1N\sum_i g_i the full gradient. A mini-batch of BB examples drawn at random gives the estimate g^=1B∑j=1BgIj\hat g=\frac1B\sum_{j=1}^B g_{I_j}. By linearity, E[g^]=gˉ\mathbb{E}[\hat g]=\bar g: the estimate is unbiased, so on average a step goes the right way. If the BB examples are drawn independently (with replacement, or from a dataset much larger than BB), each coordinate has variance σg2/B\sigma_g^2/B, so the noise shrinks like 1/B1/\sqrt B. Quadrupling the batch halves the noise and quadruples the work per step. P1.F4 uses exactly this trade-off.

The mean is the best constant guess

Suppose you must predict XX with a single number cc, and you are charged the squared error (X−c)2(X-c)^2. Which cc is cheapest on average? Write X−c=(X−μ)+(μ−c)X-c=(X-\mu)+(\mu-c) and expand the square. The cross term has expectation 2(μ−c) E[X−μ]=02(\mu-c)\,\mathbb{E}[X-\mu]=0, so

E[(X−c)2]=Var(X)+(μ−c)2.\mathbb{E}\bigl[(X-c)^2\bigr]=\mathrm{Var}(X)+(\mu-c)^2 .

The second term is never negative and is 00 only at c=μc=\mu. The mean is the constant with the smallest expected squared error, and that smallest error is the variance. For a die with c=3c=3: E[(X−3)2]=196≈3.17=2.92+0.25\mathbb{E}[(X-3)^2]=\frac{19}{6}\approx3.17=2.92+0.25. Turn on “Move the fulcrum myself” in the widget: the average squared distance is smallest exactly at the balance point, and equals the variance there.

This is why mean squared error leads to averages. A regression model trained with MSE (P3.A2) is pushed towards predicting the average target for inputs like the one in front of it.

A different cost gives a different answer. Under the absolute error ∣X−c∣|X-c|, a best constant is a median (a middle value; P1.D12). For a discrete variable it need not be unique: for a fair coin on {0,1}\{0,1\}, every cc from 00 to 11 gives the same expected absolute error, 12\frac12. For the data 1,2,101,2,10: the mean is 4.334.33 and the median is 22. Squared error is smallest at c=4.33c=4.33 (value 16.216.2) and absolute error at c=2c=2 (value 33). The large value 1010 pulls the mean towards itself; the median ignores how large it is. The widget shows both distances.

Mean and variance inside neural networks

The same two formulas appear inside networks, with “probability” replaced by equal weights on the entries of a vector.

  • Normalization (P4.19). A layer-normalization step takes the dd numbers of one example, computes their mean μ\mu and variance σ2\sigma^2, and outputs (x−μ)/σ2+ϵ(x-\mu)/\sqrt{\sigma^2+\epsilon}, a standardized vector, where ϵ\epsilon is a tiny constant that avoids dividing by zero. For (2,4,6,8)(2,4,6,8): μ=5\mu=5, σ2=5\sigma^2=5, and the output is about (−1.342,−0.447,0.447,1.342)(-1.342,-0.447,0.447,1.342), with mean 00 and variance 11 (nearly: ϵ\epsilon shifts it a hair).
  • Initialization (P4.12). A neuron computes y=∑i=1dwixiy=\sum_{i=1}^d w_ix_i. If the weights and inputs are independent, have mean 00, and the dd terms are independent, then Var(y)=d Var(w) Var(x)\mathrm{Var}(y)=d\,\mathrm{Var}(w)\,\mathrm{Var}(x). With d=1000d=1000 inputs of variance 11 and weights of variance 11, the output variance is 10001000: the signal explodes. Choosing Var(w)=1/d\mathrm{Var}(w)=1/d keeps it near 11 (a simulation gives about 10211021 and 1.031.03). Practical schemes refine this idea.
  • Dropout (P4.17). Dropout keeps each activation with probability 1−p1-p and sets it to 00 otherwise. If the survivors are scaled by 11−p\frac{1}{1-p}, the output x m/(1−p)x\,m/(1-p), with mm the keep-or-drop indicator, has expectation x⋅(1−p)/(1−p)=xx\cdot(1-p)/(1-p)=x by linearity: the expected value is unchanged. The variance is not: it becomes x2 p/(1−p)x^2\,p/(1-p), which is 33 for x=3x=3 and p=0.25p=0.25. Dropout adds noise, but no bias.
Go deeper When the mean does not exist

The definition ∑x p(x)\sum x\,p(x) needs the sum (or integral) to converge when you use ∣x∣|x| in place of xx. Some distributions fail that test.

The St. Petersburg game. Flip a fair coin until the first head, which appears on flip kk with probability 2−k2^{-k}, and win 2k2^k dollars. Each term of the expectation is 2k⋅2−k=12^k\cdot2^{-k}=1, so the sum 1+1+1+…1+1+1+\dots is infinite: the expected winnings are infinite, though a typical play pays little. No finite price per play is fair in the long-run-average sense, and the average of many plays keeps drifting upward instead of settling.

The Cauchy distribution, with density 1π(1+x2)\frac{1}{\pi(1+x^2)}, is bell-shaped but has very heavy tails. The integral of ∣x∣ p(x)|x|\,p(x) diverges (like a logarithm), so it has no mean. The average of nn Cauchy draws has the same distribution as a single draw, however large nn is (a simulation of the middle half of the averages gives roughly −1-1 to 11 for n=10n=10, 1,0001{,}000 and 100,000100{,}000). The law of large numbers needs a finite mean (P1.D8).

Heavy tails also occur in real data (incomes and file sizes are common examples), so the mean and variance are not always the right summary. A variable can also have a finite mean and an infinite variance.

Go deeper Sample variance: why divide by one less

Everything above describes a distribution. With data you only have a sample, and you compute xˉ=1n∑xi\bar x=\frac1n\sum x_i and a sample variance from it. If you measure distances from xˉ\bar x (not from the unknown true mean μ\mu), the squared distances are a little too small on average, because xˉ\bar x was chosen to fit those same points. Dividing the sum of squares by n−1n-1 instead of nn corrects this, and the result is an unbiased estimate of σ2\sigma^2 (it is Bessel’s correction). The sample mean itself needs no such correction.

For the data 2,5,3,6,42,5,3,6,4: the mean is 44, the sum of squared distances is 1010, so dividing by n=5n=5 gives 22 and dividing by n−1=4n-1=4 gives 2.52.5. NumPy’s np.var divides by nn unless you pass ddof=1, and PyTorch’s torch.var divides by n−1n-1 unless you pass correction=0 (the older spelling is unbiased=False). Layer normalization (P4.19) divides by dd, the biased variance, as in the (2,4,6,8)(2,4,6,8) example above. For big samples the difference is small. P1.D12 and P1.D13 cover this properly.

Try it: tables, averages and spreads in code

The first cell computes the die’s mean, E[X2]\mathbb{E}[X^2] and variance from the table, then checks that the average of nn rolls has standard deviation σ/n\sigma/\sqrt n (a simulation, with a fixed seed), and finds which constant has the smallest squared and absolute error. The second cell checks linearity for dependent variables (the fixed points of a shuffle), shows variances adding for independent variables but not dependent ones, simulates dropout and standardizes a vector. Predict before you run: what will Var(X+Z)\mathrm{Var}(X+Z) be when Z=7−XZ=7-X?

Try it: mean, variance, the spread of an average, the best constant

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: linearity, dependent variables, dropout, standardizing

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

With seed 00 the first cell gives the standard deviations of the averages 1.7111.711, 0.8540.854, 0.3420.342, 0.1710.171 and 0.0850.085, next to the theory values 1.7081.708, 0.8540.854, 0.3420.342, 0.1710.171 and 0.0850.085. Other seeds give slightly different simulated numbers. Challenge: change the die into a loaded die (change p) and check that the variance rule and the σ/n\sigma/\sqrt n rule still hold.

Common mistakes

Check your understanding

  1. A variable takes the values 00, 22 and 44 with probabilities 0.50.5, 0.30.3 and 0.20.2. What is its expectation?

  2. A die shows XX, and Y=7−XY=7-X is the number on the opposite face, so the two are completely dependent. Which statement is true?

  3. If Var(X)=4\mathrm{Var}(X)=4, what is Var(3X−2)\mathrm{Var}(3X-2)?

  4. Each measurement has standard deviation 22. You average 100100 independent measurements. What is the standard deviation of the average?

  5. You must predict the targets 11, 22 and 1010 with one constant cc and you are scored by mean squared error. Which cc is best?

Exercises

  1. A variable takes the values 0,1,2,30,1,2,3 with probabilities 0.1,0.4,0.3,0.20.1,0.4,0.3,0.2. Find E[X]\mathbb{E}[X], E[X2]\mathbb{E}[X^2], Var(X)\mathrm{Var}(X) and σ\sigma.
    Show answerE[X]=0.4+0.6+0.6=1.6\mathbb{E}[X]=0.4+0.6+0.6=1.6. E[X2]=0.4+1.2+1.8=3.4\mathbb{E}[X^2]=0.4+1.2+1.8=3.4. Var(X)=3.4−1.62=3.4−2.56=0.84\mathrm{Var}(X)=3.4-1.6^2=3.4-2.56=0.84, so σ=0.84≈0.917\sigma=\sqrt{0.84}\approx0.917.
  2. A game costs 44 to play. You roll a die and receive the number shown. What is your expected profit per play?
    Show answer3.5−4=−0.53.5-4=-0.5: you lose half a unit per play on average.
  3. A fair die is rolled 6060 times. What is the expected number of sixes, and (for independent rolls) the standard deviation of that number?
    Show answerExpected number: 60/6=1060/6=10. Each roll is a Bernoulli indicator with variance 16⋅56=536\frac16\cdot\frac56=\frac5{36}, so the sum has variance 60⋅536=253≈8.3360\cdot\frac5{36}=\frac{25}3\approx8.33 and standard deviation ≈2.89\approx2.89.
  4. Daily temperatures have mean 20 ∘20\,^\circC and standard deviation 5 ∘5\,^\circC. Find the mean and standard deviation in ∘^\circF, using F=1.8C+32F=1.8C+32.
    Show answerMean 1.8⋅20+32=68 ∘1.8\cdot20+32=68\,^\circF. Standard deviation 1.8⋅5=9 ∘1.8\cdot5=9\,^\circF (the +32+32 does not change the spread).
  5. An exam has mean 7070 and standard deviation 1010. What is the standardized score ZZ of a mark of 8585, and of 5555?
    Show answerZ=85−7010=1.5Z=\frac{85-70}{10}=1.5 and Z=55−7010=−1.5Z=\frac{55-70}{10}=-1.5.
  6. For XX uniform on [0,1][0,1] (density 11), compute E[X2]\mathbb{E}[X^2] and Var(X)\mathrm{Var}(X).
    Show answerE[X2]=∫01x2dx=13\mathbb{E}[X^2]=\int_0^1x^2dx=\frac13, and Var(X)=13−(12)2=112≈0.083\mathrm{Var}(X)=\frac13-\left(\frac12\right)^2=\frac1{12}\approx0.083.
  7. You flip a fair coin 400400 times. What is the standard deviation of the fraction of heads?
    Show answer12400=140=0.025\frac{1}{2\sqrt{400}}=\frac1{40}=0.025. Quadrupling to 16001600 flips would halve it to 0.01250.0125.
  8. Ten people throw their hats in a pile and take one back at random. What is the expected number who get their own hat, and why does the answer not depend on dependence between people?
    Show answerEach person gets their own hat with probability 110\frac1{10}, so by linearity the expected number is 10⋅110=110\cdot\frac1{10}=1. Linearity of expectation holds for dependent indicators, so no independence is needed.
  9. Dropout with p=0.25p=0.25 is applied to an activation x=3x=3 (survivors scaled by 10.75\frac1{0.75}). Find the mean and variance of the output.
    Show answerThe output is 44 with probability 0.750.75 and 00 with probability 0.250.25. The mean is 33, and E[out2]=16⋅0.75=12\mathbb{E}[\text{out}^2]=16\cdot0.75=12, so the variance is 12−9=312-9=3.
  10. True or false: Var(X+Y)=Var(X)+Var(Y)\mathrm{Var}(X+Y)=\mathrm{Var}(X)+\mathrm{Var}(Y) when Y=2XY=2X.
    Show answerFalse. X+Y=3XX+Y=3X has variance 9 Var(X)9\,\mathrm{Var}(X), while Var(X)+Var(2X)=5 Var(X)\mathrm{Var}(X)+\mathrm{Var}(2X)=5\,\mathrm{Var}(X). The variables are dependent, so the cross term 2 Cov(X,2X)=4 Var(X)2\,\mathrm{Cov}(X,2X)=4\,\mathrm{Var}(X) is missing.
  11. For the data 1,2,101,2,10, compute the mean squared error and the mean absolute error of the constant guesses c=4.33c=4.33 and c=2c=2.
    Show answerFor c=133c=\frac{13}3: squared error ≈16.22\approx16.22 (the variance) and absolute error ≈3.78\approx3.78. For c=2c=2: squared error ≈21.67\approx21.67 and absolute error =3=3. The mean wins on squared error, the median on absolute error.
  12. Write a function gg for which E[g(X)]\mathbb{E}[g(X)] is less than g(E[X])g(\mathbb{E}[X]) for a die, and say which property of gg makes that happen.
    Show answerTake g(x)=ln⁡xg(x)=\ln x: E[ln⁡X]≈1.097<ln⁡3.5≈1.253\mathbb{E}[\ln X]\approx1.097<\ln3.5\approx1.253. The function ln⁡\ln is concave (curves downward), so Jensen’s inequality is reversed.

Next: P1.D5 studies how knowing one variable changes what you expect of another (joint, marginal and conditional probability, and independence), and P1.D7 turns the covariance term above into correlation and the multivariate Gaussian. P1.D8 proves the law of large numbers and shows that averages become bell-shaped, which makes the σ/n\sigma/\sqrt n spread exact. P1.D10 uses expectations to build maximum likelihood, and P1.F4 uses the variance of a mini-batch gradient.

Key takeaways

  • The expectation (mean) of a discrete variable is E[X]=∑xx p(x)\mathbb{E}[X]=\sum_x x\,p(x), a probability-weighted average; for a continuous variable it is ∫x p(x) dx\int x\,p(x)\,dx. It is the balance point of the distribution, and the value that averages of many independent draws settle near (the law of large numbers, P1.D8). It need not be a value XX can take: a fair die has mean 3.53.5.
  • For a function, E[g(X)]=∑xg(x) p(x)\mathbb{E}[g(X)]=\sum_x g(x)\,p(x): weight the values of gg, with no need to find the distribution of g(X)g(X). In general E[g(X)]≠g(E[X])\mathbb{E}[g(X)]\ne g(\mathbb{E}[X]): for a die E[X2]=15.17\mathbb{E}[X^2]=15.17 but E[X]2=12.25\mathbb{E}[X]^2=12.25. A training loss is an average of gg over the data, so it is an expectation.
  • Linearity: E[aX+b]=a E[X]+b\mathbb{E}[aX+b]=a\,\mathbb{E}[X]+b and E[X+Y]=E[X]+E[Y]\mathbb{E}[X+Y]=\mathbb{E}[X]+\mathbb{E}[Y] for any two variables with finite means, dependent or not. With an indicator 1A1_A (1 if AA happens, else 0), E[1A]=P(A)\mathbb{E}[1_A]=\mathbb{P}(A), so expected counts are sums of probabilities: n/6n/6 sixes in nn rolls, and one fixed point in a random shuffle of any size.
  • The variance Var(X)=E[(X−μ)2]=E[X2]−μ2\mathrm{Var}(X)=\mathbb{E}[(X-\mu)^2]=\mathbb{E}[X^2]-\mu^2 measures spread, and the standard deviation σ=Var(X)\sigma=\sqrt{\mathrm{Var}(X)} has the units of XX. It is at least 0, and 0 only for a constant. Var(aX+b)=a2Var(X)\mathrm{Var}(aX+b)=a^2\mathrm{Var}(X): shifting changes nothing, scaling by aa scales σ\sigma by ∣a∣|a|. The standardized variable (X−μ)/σ(X-\mu)/\sigma has mean 0 and variance 1.
  • Variances add, Var(X+Y)=Var(X)+Var(Y)\mathrm{Var}(X+Y)=\mathrm{Var}(X)+\mathrm{Var}(Y), when XX and YY are independent (or just uncorrelated); in general a covariance term appears (P1.D7). So nn independent draws with standard deviation σ\sigma have a sum with spread σn\sigma\sqrt{n} and an average with spread σ/n\sigma/\sqrt{n}: to halve the noise of an average you need four times the data. This is why mini-batch gradients get less noisy like 1/B1/\sqrt{B}.
  • E[(X−c)2]=Var(X)+(μ−c)2\mathbb{E}[(X-c)^2]=\mathrm{Var}(X)+(\mu-c)^2, so the mean is the constant guess with the smallest expected squared error (and a median has the smallest expected absolute error). Some distributions have no mean at all (Cauchy), or an infinite one (the St. Petersburg game), and then averages do not settle.
Found a mistake? Tell us