Roll a fair die thousands of times and add up the results. The average of the rolls creeps towards , a number that no single roll can show. Where does come from? And if you only roll times, how far from 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 be a discrete random variable with PMF (P1.D2). Its expectation, also called its expected value or mean, is
Multiply each value by its probability and add. People often write (the Greek letter mu) for it. Read as “the expectation of ”.
For a fair die, every face has probability :
Here is a smaller made-up example. Let take the values with probabilities . Then . The plain average of the four values is , not : the values that are more likely get more say.
Why this is the average of many draws. Suppose you draw a thousand times and about draws give , give , give and give . The ordinary average of the thousand numbers is . Each value is weighted by the fraction of draws that gave it, and in the long run that fraction is its probability. So 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 , and the made-up example never gives . 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 , so over many plays you collect about per play. If a play costs , you lose about per play on average, though some single plays do win.
Two special cases. A constant (a variable with all its probability on one value) has . A Bernoulli variable is with probability and otherwise: . A special Bernoulli variable is the indicator of an event , written , which is when happens and when it does not. Its expectation is the probability of the event:
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 at each value . 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.
What to try:
- Fair die. The weights sit on to and the fulcrum is at , between two faces: nothing is there, and it balances anyway.
- Two humps. Put weight near to and near to . The mean lands in the empty middle, at .
- 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 , so the button is the way to land exactly on a mean such as .
The balance has a one-line statement. The weight on each side pulls with strength (weight) (distance from the fulcrum), and the fulcrum is at the mean exactly when the pulls cancel:
To check, expand: . And no other point works, because is zero only when . 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 (P1.D2), the sum becomes an integral (P1.C9). Each thin strip of width at holds probability , and the expectation adds up times that:
For the uniform density on (equal to there, and elsewhere): , the middle, as balance suggests. P1.C9 quoted the mean for the density on . Integration by parts confirms it: . 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 by ; the rules are the same.
Averaging a function of
Often you need the expected value of something computed from : its square, a loss, a score. You could work out the distribution of first, but you do not have to. The rule, sometimes called the “law of the unconscious statistician” (LOTUS), is
or, for a continuous variable, .
Apply to each value, then weight by the probability of the original value. For a die, with :
Notice that . So is not in general. Squaring before averaging gives more weight to the large values than squaring the average does. For the uniform density on it is the same story: , but . The two agree for a straight-line (next section), and for a constant .
Go deeper Jensen’s inequality: which side is bigger
If is convex (its graph curves upward, like or ), then , for any whose expectations exist. If is concave (curves downward, like ), the inequality reverses. This is Jensen’s inequality.
Check it for a die. With : and . With : and , smaller, as expected for a concave . For the gap is exactly the variance (defined below): .
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 makes an error on one example. If examples come from a distribution, the expected loss (also called the risk) is , the average error over everything the world can throw at the model. You cannot compute it, but you have examples, and the training loss is the same formula with probability 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 and ,
Change from Celsius to Fahrenheit: . If the mean temperature is C, the mean is F. You can convert the mean, or convert every reading and then average: the same answer.
Sums. For any two random variables and with finite means,
This holds whether or not and are independent. Nothing about how they relate to each other is needed. Two dice give for the expected total. If the second die were secretly always minus the first, the total would be exactly every time: still .
Go deeper Why sums need no independence (a short proof)
Let the sample space have outcomes with probabilities , and let and be numbers attached to each outcome (P1.D2). The expectation is , the same sum with outcomes in place of values. Then
The proof splits one sum into two and never asks how and move together. The same argument gives . Products are different: needs independence (or at least zero covariance, P1.D7). For it fails: .
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 rolls. Let if roll is a six. Then , and the number of sixes is , with expectation . In rolls: sixes on average. (For independent rolls this is the binomial variable of P1.D3, whose mean is .)
- Fixed points of a shuffle. Shuffle hats and hand them back at random. Let if person gets their own hat. Then , and the expected number of people with their own hat is , for any . The indicators are not independent: if people have their own hat, the last one does too. Linearity does not care. (Enumerating all shuffles of hats gives exactly .)
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 or (each with probability ) both have mean , but the die strays much further. The variance measures the typical squared distance from the mean:
The square root (sigma) is the standard deviation. It has the same units as (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, , the distances from the mean are , and
so .
There is a shortcut. Expand the square and use linearity:
For the die: , 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:
- , because it averages squares. It is exactly when is a constant (strictly: has a single value with probability ). The one-bar preset shows it.
- For a Bernoulli variable with : , so . It is largest, , at .
- For the uniform density on : and .
- Why squares, not absolute distances? The mean absolute deviation 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 of draws lie more than 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 stretches every distance by , so the variance grows by :
so the standard deviation of is .
Check with the made-up example (, , so ). For : and . 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 C become Fahrenheit readings with F, and the does nothing to the spread.
Standardizing. Subtract the mean, then divide by the standard deviation:
By the rules, and . The value counts how many standard deviations lies from its mean, so a score of when the mean is and has . 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 slides the plank without changing its shape, so the mean moves and the spread does not. Multiplying by 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 ), 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:
For any , . For independent ,
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 , then has variance , not . If , then has no spread at all. The general rule is
where the covariance measures how and move together (P1.D7). When and 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 and for the deviations from the means. The deviation of from its mean is , so
The last expectation is the covariance, . It is when and are independent, because then . For two independent dice, (a simulation gives ). For the two dice move in opposite directions: the sum is always and the variance is .
The average of independent draws. Let be independent draws from the same distribution, each with mean and standard deviation (the same finite ). Their sum and their average have
The first line uses linearity and the addition of variances; the second divides by , and dividing by divides the variance by . So:
- The average is centred on the truth, : it is an unbiased estimate of the mean (on average it is right, whatever ).
- Its noise shrinks like . A die has . The average of rolls has spread , of rolls , and of rolls . 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 is about for flips and about for . Here is why. A flip is a Bernoulli variable with , so and . The number of heads is the sum of independent flips, with standard deviation : that is for and for . The count gap grows like . The relative frequency is the sum divided by , with standard deviation : and , 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 of it: about and .) P1.D8 shows that the shape of this wobble is a bell curve, and that it shrinks to zero.
Mini-batch gradients. Let be the gradient of the loss on example and the full gradient. A mini-batch of examples drawn at random gives the estimate . By linearity, : the estimate is unbiased, so on average a step goes the right way. If the examples are drawn independently (with replacement, or from a dataset much larger than ), each coordinate has variance , so the noise shrinks like . 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 with a single number , and you are charged the squared error . Which is cheapest on average? Write and expand the square. The cross term has expectation , so
The second term is never negative and is only at . The mean is the constant with the smallest expected squared error, and that smallest error is the variance. For a die with : . 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 , 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 , every from to gives the same expected absolute error, . For the data : the mean is and the median is . Squared error is smallest at (value ) and absolute error at (value ). The large value 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 numbers of one example, computes their mean and variance , and outputs , a standardized vector, where is a tiny constant that avoids dividing by zero. For : , , and the output is about , with mean and variance (nearly: shifts it a hair).
- Initialization (P4.12). A neuron computes . If the weights and inputs are independent, have mean , and the terms are independent, then . With inputs of variance and weights of variance , the output variance is : the signal explodes. Choosing keeps it near (a simulation gives about and ). Practical schemes refine this idea.
- Dropout (P4.17). Dropout keeps each activation with probability and sets it to otherwise. If the survivors are scaled by , the output , with the keep-or-drop indicator, has expectation by linearity: the expected value is unchanged. The variance is not: it becomes , which is for and . Dropout adds noise, but no bias.
Go deeper When the mean does not exist
The definition needs the sum (or integral) to converge when you use in place of . Some distributions fail that test.
The St. Petersburg game. Flip a fair coin until the first head, which appears on flip with probability , and win dollars. Each term of the expectation is , so the sum 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 , is bell-shaped but has very heavy tails. The integral of diverges (like a logarithm), so it has no mean. The average of Cauchy draws has the same distribution as a single draw, however large is (a simulation of the middle half of the averages gives roughly to for , and ). 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 and a sample variance from it. If you measure distances from (not from the unknown true mean ), the squared distances are a little too small on average, because was chosen to fit those same points. Dividing the sum of squares by instead of corrects this, and the result is an unbiased estimate of (it is Bessel’s correction). The sample mean itself needs no such correction.
For the data : the mean is , the sum of squared distances is , so dividing by gives and dividing by gives . NumPy’s np.var divides by unless you pass ddof=1, and PyTorch’s torch.var divides by unless you pass correction=0 (the older spelling is unbiased=False). Layer normalization (P4.19) divides by , the biased variance, as in the 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, and variance from the table, then checks that the average of rolls has standard deviation (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 be when ?
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
With seed the first cell gives the standard deviations of the averages , , , and , next to the theory values , , , and . 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 rule still hold.
Common mistakes
Check your understanding
A variable takes the values , and with probabilities , and . What is its expectation?
Weight each value by its probability: . The value is the plain average of the three values, which ignores the probabilities. The value is the sum of the probabilities. The value is the largest value, and a weighted average cannot reach it unless all the probability is there.
A die shows , and is the number on the opposite face, so the two are completely dependent. Which statement is true?
The sum is always , so its mean is and its variance is . The statement with variance adds the two variances, which is only valid for independent variables. Expectations add with no condition, so the sum is computable and equals , not .
If , what is ?
Scaling by multiplies the variance by , and shifting by changes nothing: . The value subtracts the shift from the variance. The value treats the variance like a mean (). The value forgets to square the factor .
Each measurement has standard deviation . You average independent measurements. What is the standard deviation of the average?
The spread of an average of independent draws is . The value would mean averaging did nothing. The value divides by instead of . The value is the spread of the sum, .
You must predict the targets , and with one constant and you are scored by mean squared error. Which is best?
The constant with the smallest mean squared error is the mean, . The value is the median, which is best for absolute error, not squared error. The value is the midpoint of the range, with no optimality property. The value matches one target and is far from the others.
Exercises
- A variable takes the values with probabilities . Find , , and .
Show answer
. . , so . - A game costs to play. You roll a die and receive the number shown. What is your expected profit per play?
Show answer
: you lose half a unit per play on average. - A fair die is rolled times. What is the expected number of sixes, and (for independent rolls) the standard deviation of that number?
Show answer
Expected number: . Each roll is a Bernoulli indicator with variance , so the sum has variance and standard deviation . - Daily temperatures have mean C and standard deviation C. Find the mean and standard deviation in F, using .
Show answer
Mean F. Standard deviation F (the does not change the spread). - An exam has mean and standard deviation . What is the standardized score of a mark of , and of ?
Show answer
and . - For uniform on (density ), compute and .
Show answer
, and . - You flip a fair coin times. What is the standard deviation of the fraction of heads?
Show answer
. Quadrupling to flips would halve it to . - 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 answer
Each person gets their own hat with probability , so by linearity the expected number is . Linearity of expectation holds for dependent indicators, so no independence is needed. - Dropout with is applied to an activation (survivors scaled by ). Find the mean and variance of the output.
Show answer
The output is with probability and with probability . The mean is , and , so the variance is . - True or false: when .
Show answer
False. has variance , while . The variables are dependent, so the cross term is missing. - For the data , compute the mean squared error and the mean absolute error of the constant guesses and .
Show answer
For : squared error (the variance) and absolute error . For : squared error and absolute error . The mean wins on squared error, the median on absolute error. - Write a function for which is less than for a die, and say which property of makes that happen.
Show answer
Take : . The function 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 spread exact. P1.D10 uses expectations to build maximum likelihood, and P1.F4 uses the variance of a mini-batch gradient.