Random variables: PMF, PDF, CDF, expectation and variance
Before this lesson: lesson 01 (events, conditional probability, independence). For the continuous part you need integrals and the substitution rule in one variable (calculus, lesson 10). Time: about 70 minutes, plus the notebook.
Why this matters #
Almost every quantity in machine learning is an expectation. The risk of a model is , the expected loss on a new example. Cross-entropy, the ELBO of a variational autoencoder and the value function of reinforcement learning are expectations too.
Linearity of expectation is the reason why a minibatch gradient is an unbiased estimate of the full gradient (optimization, lesson 5). It needs no independence, so it holds even when the examples of a batch are related.
Every sampler, from a Monte Carlo study to a diffusion model, starts from simple noise and transforms it. The density of the result follows the change-of-variables rule of this lesson. The reparameterisation trick of a VAE, , is the simplest case. The probability integral transform of section 3 is the standard calibration check for probabilistic forecasts, from weather ensembles to the predictive distributions of a neural network.
1. Predict first #
2. The picture #
A random variable is a function #
Roll two fair dice. The sample space has 36 equally likely outcomes (lesson 01). Let be the sum of the two dice. Then is a function on : it maps to 7, to 8, and so on.
A random variable is a function . It is not random in itself; the outcome is random, and reads a number from it. We write for the event "the sum is 7", the set of outcomes that maps to 7. It has 6 outcomes, so .
The distribution of says how the probability mass on lands on the real line. All 36 outcomes carry mass . The function moves each of them to a point of the line, and the masses pile up: 6 outcomes land on 7, only one lands on 2.
There are two simple cases.
- Discrete: the mass sits on separate points. We draw a bar chart, and the bar heights are probabilities. The sum of two dice is discrete.
- Continuous: the mass is spread over an interval. We draw a curve, and areas under the curve are probabilities. The height is probability per unit length, so it can be larger than 1. The waiting time until the next customer is continuous.
The cumulative distribution function (CDF) is the mass collected from the left up to . It works for both cases: it is a staircase for a discrete and a smooth curve for a continuous one. The mass between and is the rise of the CDF:
Move and , then switch the distribution. The top panel shows the distribution in orange: bars for the sum of two dice, a curve for the exponential and the normal. The probability of the interval is yellow: the sum of the shaded bars, or the shaded area. In the CDF below, the same number is the rise of the curve from to (the thick yellow bar). For the exponential with rate 2, notice that the curve starts at height 2: a density value is not a probability.
For the dice, . For a continuous , a single point has no width, so it has no area: for every . This is why and are the same number for a continuous , but not for the dice.
is uniform on , so its density is constant on that interval. What is the value of the density, and what is ?
The total area must be 1, and the interval has width 0.5, so the height is . A density is probability per unit length, so it can be larger than 1. A single point has width 0, so its probability is 0. Only areas (integrals of the density) are probabilities.
The expectation is a balance point #
Put the probability masses on a light beam, at their values. The expectation is the point where the beam balances. For a discrete ,
For two dice, the distribution is symmetric around 7, so the beam balances at 7, and indeed . A far mass has a long lever arm: it pulls the balance point toward itself, even when its probability is small. This is why the mean is sensitive to outliers.
Predict where the beam balances, then drag the dark triangle (the fulcrum) there. The orange discs are the probabilities , placed at the values . The readout shows the torque ; the beam is level when it is 0. Press "Show the mean" to see (yellow) and the band (violet). Then try "one far mass": a mass of 0.1 at moves the balance point from 1 to 1.7 and makes the variance much larger.
The torque about a point is , because the add up to 1. It is zero only at . The variance is the average squared lever arm, . Squaring makes far masses count much more.
Reading the CDF backwards #
The CDF maps every value to a level between 0 and 1. Now go the other way. Pick a level uniformly at random in and find the where the CDF reaches . This is a sample from the distribution. This method is called inverse-CDF sampling.
Why does it work? Where the CDF is steep, the density is high. A steep part of the CDF covers a long range of levels over a short range of . Many uniform levels therefore land on that short range, and the samples pile up exactly where the density is high.
Move the level , then press "Draw 500". The yellow path goes from on the vertical axis across to the orange CDF and down to . Each draw uses a new uniform . The blue histogram of the samples matches the orange density below. Notice that for the CDF is steepest at , and most samples land there. Try "discrete": the CDF is a staircase, and each step catches the levels that belong to one value.
For a continuous random variable, the CDF is very steep near and almost flat near . Where do inverse-CDF samples land most often?
A steep part of the CDF covers many levels over a short range of . Uniform levels fall on it often, so many samples land there. The slope of the CDF is the density, . A flat part covers almost no levels, so almost no samples land there.
3. Definitions and main results #
PMF, PDF and CDF #
- The probability mass function (PMF) of a discrete is . It satisfies and .
- A continuous has a probability density function (PDF) with and for all . Then for every .
- The cumulative distribution function (CDF) is for every real .
Properties of a CDF. is nondecreasing, it tends to 0 at and to 1 at , and it is right-continuous. For all , : the event is the disjoint union of and . For a continuous , wherever is continuous. For a discrete , jumps by at each value .
We use , or just , for both the PMF and the PDF. The context says which one.
Expectation, LOTUS and linearity #
Definition. The expectation (or mean) of is
It exists when (or the integral version is finite). Most distributions in this track have a mean, but not all of them.
A distribution without a mean: the Cauchy distribution
The Cauchy density is . It is symmetric around 0 and looks like a normal curve with heavy tails. But grows without bound as , so does not exist. The consequence is real: the average of independent Cauchy samples is again Cauchy, with the same spread. It never settles down, however large is. The law of large numbers (lesson 06) needs a finite mean.
We often need the mean of a function of , such as or a cost . The next theorem says that we do not need the distribution of for it.
Theorem (LOTUS, the law of the unconscious statistician). For any function ,
whenever the sum (or integral) of is finite.
Proof (discrete).
- takes the value when takes any with . So .
- By the definition of the mean, , because inside the inner sum.
- Every belongs to exactly one group (the group of ). So the double sum is a sum over all : .
Theorem (linearity of expectation). For random variables with finite means and constants ,
No independence is needed.
Proof (discrete).
- Let be the joint PMF (lesson 04 studies it). LOTUS for the pair gives .
- Split the sum into two parts: .
- The inner sums are the PMFs of and of alone: by the law of total probability. So the total is .
- LOTUS with gives . Combine the two results.
We never wrote as a product . That is why the result holds for dependent variables.
A warning. In general . It is equal for every only when is linear plus a constant. For a convex (such as or ), Jensen's inequality says (information theory, lesson 3). For example, , and the gap is the variance.
Indicator variables #
The indicator of an event is the random variable that is 1 when happens and 0 otherwise. Its mean is a probability:
The indicator method. To find the mean of a count, write the count as a sum of indicators and add their probabilities. Linearity does the rest. You never need to know how the indicators depend on each other.
Example 1: fixed points. Shuffle cards numbered . A fixed point is a card that ends in its own position. Let be the indicator of "card is in position ". By symmetry, card is equally likely to be in each of the positions, so . The number of fixed points is , and
The indicators are dependent (if cards are fixed, card must be fixed too), but linearity does not care.
Example 2: records. Daily values are independent and identically distributed (i.i.d.) and continuous, so there are no ties. Day is a record if is larger than all earlier values. By symmetry, each of the first days is equally likely to hold the largest of the first values, so . Hence
For a year of daily temperatures with no trend (), this is records. Many more records than this are evidence of a trend.
10 people put their hats in a box, and each one takes back a hat at random (a random permutation). What is the expected number of people who get their own hat?
Let indicate that person gets their own hat. Each person is equally likely to get any of the 10 hats, so , and linearity gives . The indicators are dependent, but linearity needs no independence. is a different quantity: the probability that nobody gets their own hat (for large ).
Variance and standardising #
Definition. With , the variance is , and the standard deviation is . The standard deviation has the same unit as .
Theorem. (a) . (b) .
Proof.
- (a) Expand the square: .
- Use linearity: .
- (b) has mean , so . Square it and take the mean: .
A shift moves the distribution but does not change its spread. A scale multiplies the spread by , so the variance by .
Standardising. The z-score has mean 0 and variance 1, by (b) with and . It measures a value in standard deviations from the mean. If exam scores have mean 70 and standard deviation 10, a score of 85 has . Feature standardisation in ML ("StandardScaler") applies this to every input feature.
Sums. Random variables and are independent if for all sets of values. For independent and , the variances add: . For dependent variables there is an extra covariance term; lesson 04 proves both. One consequence: for i.i.d. with variance , the sample mean has variance (use (b) with ). Averages are less noisy than single values.
The density of #
We often transform a random variable: , , . What is the density of ? The answer is not . There is an extra factor, because stretches or squeezes the axis.
Move the interval, then switch the map . is uniform on . The yellow interval on the -axis holds probability equal to its width. The map (orange curve) sends it to the yellow interval on the -axis, which holds the same probability. Where is wide, the density of is low; where it is narrow, the density is high. The blue histogram of simulated values of matches the orange formula for . For , the values pile up near 0.
The rule is conservation of probability. A short interval of length around holds probability . The map sends it to an interval of length around that holds the same probability. So , and .
Theorem (change of variables in one dimension). Let have density , and let be strictly monotone and differentiable, with on the set where . Then has density
for in the image of that set, and elsewhere.
Proof.
- Let be increasing. Then exactly when . So .
- Differentiate with the chain rule: . Here .
- Let be decreasing. Then exactly when . So ( because is continuous).
- Differentiate: . This is positive, because . Both cases give the absolute value in the theorem.
Example. and . Then and , so for . The density is large near 0: the map squeezes the interval into .
Example (affine map). with . Then , so . With , this gives the density of . This is the reparameterisation trick.
When is not monotone, use the CDF method. Compute directly, then differentiate. Let be uniform on , with density , and . For :
In general, add the contributions of all branches: for , . Lesson 05 extends the rule to vectors, where the factor becomes the absolute determinant of a Jacobian matrix.
and . Which is the density of ?
, so and on . Check: the area is . Stretching the axis by 3 makes the density 3 times lower. The first option multiplies instead of dividing; the second forgets the factor, and then the total area would be 3.
Inverse-CDF sampling and the probability integral transform #
Theorem. Let be a continuous, strictly increasing CDF, and let .
- (a) Inverse-CDF sampling: has CDF .
- (b) Probability integral transform (PIT): if has CDF , then .
Proof.
- is strictly increasing, so exactly when .
- (a) , because for .
- (b) For : . This is the CDF of .
Example. has CDF for . Solve : . So is an exponential sample. With and , it gives .
Discrete distributions. For a CDF with jumps or flat parts, use the generalised inverse
. Step 1 still holds, because is right-continuous, so (a)
still holds. In practice: compute the cumulative sums of the probabilities and return the first
value whose cumulative sum reaches . A binary search does this in steps for
values (np.searchsorted). Part (b) needs a continuous : for a discrete , takes only
the values , so it cannot be uniform.
PIT histograms check calibration. A model predicts a full distribution, with CDF , for each future value (tomorrow's temperature, a delivery time, the next sales number). If the model is calibrated (its predicted distributions are correct), the values are uniform by part (b). So you plot a histogram of the PIT values:
- flat: consistent with calibration (necessary, but not sufficient);
- U-shaped: the observations fall too often in the tails, so the predicted distributions are too narrow (overconfident);
- hump-shaped: the predicted distributions are too wide (underconfident).
For example, if the observations are but the model predicts , the five bins of the PIT histogram have masses : a clear U.
Answers to section 1. (1) No. , and piles up near 0. (2) . Write the count as a sum of 50 indicators and use linearity. Independence is not needed: dependence changes the variance of the count, not its mean. (3) Yes. A density is probability per unit length; has density 3 on its interval.
4. Worked example #
A. Discrete. A small support team gets urgent tickets per day, with
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0.4 | 0.3 | 0.2 | 0.1 |
- CDF. Add from the left: , , , (a staircase). So .
- Mean. .
- Second moment (LOTUS with ). .
- Variance. , so .
- A cost. Each day costs (overtime grows fast). LOTUS gives . But . Planning with the average number of tickets underestimates the average cost by half (Jensen, is convex).
This is the "worked example" preset of the balance-point figure in section 2.
B. Continuous. for two independent uniforms on (the better of two random scores).
- CDF. exactly when both and . By independence, for .
- Density. on . Large values are more likely, as expected for a maximum.
- Mean. .
- Variance. , so .
- Inverse CDF. Solve : . So has the same distribution as : one uniform number is enough. (The "density 2x" preset of the inverse-CDF figure.)
- PIT check. . With and , the change-of-variables rule gives on . Uniform, as the theorem says.
In part A, the team lead plans with ticket per day. Each ticket takes 2 hours, plus a fixed 1 hour for the daily meeting, so the time is . What are and ?
Linearity: . Variance: . The scale is squared, and the shift does not change the spread. The first option forgets to square the 2; the third adds the shift to the variance.
5. In code #
SciPy checks the hand computations of the worked example. Then a simulation checks the indicator results and the PIT histogram. Simulated numbers carry a Monte Carlo error: for the mean number of records, about with 20,000 simulated years.
import numpy as np
from scipy import stats, integrate
# A. discrete: a distribution from a table
X = stats.rv_discrete(values=([0, 1, 2, 3], [0.4, 0.3, 0.2, 0.1]))
print(X.cdf([0, 1, 2, 3]), X.mean(), X.moment(2), X.var())
# [0.4 0.7 0.9 1. ] 1.0 2.0 1.0
print(X.expect(lambda t: 10 * t**2)) # 20.0 (LOTUS), while c(E[X]) = 10
# B. continuous: density 2x on [0, 1]
m1 = integrate.quad(lambda t: t * 2 * t, 0, 1)[0]
m2 = integrate.quad(lambda t: t**2 * 2 * t, 0, 1)[0]
print(round(m1, 4), round(m2 - m1**2, 4)) # 0.6667 0.0556 (2/3 and 1/18)
rng = np.random.default_rng(1)
u = rng.random(100_000)
mx = np.maximum(rng.random(100_000), rng.random(100_000)) # max of two uniforms
print(stats.ks_2samp(np.sqrt(u), mx).pvalue > 0.01) # True: same law
# inverse CDF of Exp(lam): -log(1 - U) / lam
lam = 2.0
x = -np.log(1 - rng.random(100_000)) / lam
print(round(x.mean(), 3), round(x.var(), 3)) # 0.502 0.252 (exact 0.5, 0.25)
# indicators: fixed points of 20,000 random permutations of 10 items
perms = np.argsort(rng.random((20_000, 10)), axis=1)
print(round((perms == np.arange(10)).sum(axis=1).mean(), 2)) # 1.0 (exact 1)
# indicators: records in 365 i.i.d. daily values, 20,000 simulated years
temps = rng.standard_normal((20_000, 365))
records = (temps >= np.maximum.accumulate(temps, axis=1)).sum(axis=1)
print(round(records.mean(), 2), round((1 / np.arange(1, 366)).sum(), 2))
# 6.47 6.48
# PIT histograms: observations y ~ N(0, 1), two forecasts
y = rng.standard_normal(100_000)
for sd in (1.0, 0.5):
pit = stats.norm(0, sd).cdf(y)
print(sd, np.round(np.histogram(pit, bins=5, range=(0, 1))[0] / y.size, 2))
# 1.0 [0.2 0.2 0.2 0.2 0.2] calibrated: flat
# 0.5 [0.34 0.11 0.1 0.11 0.34] too narrow: U-shaped
The ks_2samp line is a two-sample Kolmogorov–Smirnov test: a p-value above 0.01 means the
two samples are consistent with one distribution (tests are lesson 11).
6. Where it shows up #
- Risk and minibatch gradients. Training minimises the average loss , an estimate of the risk . By linearity, the gradient on a random minibatch has the full gradient as its mean, whatever the dependence between the examples.
- Reparameterisation and flows. A VAE samples with , a monotone change of variables, so gradients can flow through the sample (generative models, lesson 2). Normalising flows chain many invertible maps and track the density with the multivariate version of the rule.
- Transport maps. In one dimension, sends a continuous to a variable with CDF (PIT, then inverse CDF). Quantile normalisation of features and quantile mapping of climate-model output use this map. Diffusion and flow-matching models learn such noise-to-data maps in high dimension.
- Forecast calibration. PIT histograms (and rank histograms of ensembles) are the standard check of probabilistic weather and climate forecasts, and of the predictive distributions of regression models. A U-shape means overconfidence.
- A/B tests. A conversion is an indicator; the conversion rate is a mean of indicators, with mean and, for independent users, variance .
- Records and extremes. In a series without trend, the expected number of records grows only like . Counting records is a simple test for a trend in temperature series.
7. Common mistakes #
- . False in general. For a convex , (Jensen). In the worked example: .
- Reading a density value as a probability. has density 2. Only areas under the density are probabilities.
- Forgetting the factor when you transform a density. Check that the new density integrates to 1.
- Using the change-of-variables formula for a non-monotone . For with on both sides of 0, add both branches, or use the CDF method.
- Adding variances of dependent variables. needs zero covariance. And for independent , is also the sum , not the difference.
- in floating point. With values near , both terms are huge and nearly equal, and the difference loses all its digits. Compute instead (two passes over the data).
- with .
rng.random()returns values in and can return exactly 0. Use , which is always finite. - Expecting to be uniform for a discrete . It takes only the values .
8. Check yourself #
- . Give the density, , and .
Answer
The density is on . . (the middle). , so (in general for ). - . Find , and for
an independent copy of .
Answer
. . - 30 people have independent birthdays, uniform over 365 days. What is the expected number of
pairs of people with the same birthday?
Answer
One indicator per pair. Each pair shares a birthday with probability . There are pairs, so the mean is . The pair indicators are dependent, but linearity does not need independence. - and . Find the density of .
Answer
is increasing, and . So for , where is the standard normal density. This is the **log-normal** distribution. - Observations come from , but a model predicts . What shape
does the PIT histogram have?
Answer
A hump: the predicted distribution is too wide, so the observations fall mostly in its middle, where is near 0.5. With 5 bins the masses are about . - You want samples of a discrete with , and you draw
. Which value does the inverse-CDF method return?
Answer
The cumulative sums are . The first value whose cumulative sum reaches is (because ).
What is the difference between a PMF value and a PDF value?
A PMF value is a probability. A PDF value is probability per unit length: only areas are probabilities, and the value can exceed 1.
How do you get from the CDF?
.
State LOTUS.
(or ): you do not need the distribution of .
Does linearity of expectation need independence? Give the formula.
No. for any with finite means.
What is the expected number of fixed points of a random permutation of items, and why?
- Each item is in its own place with probability ; sum the indicators by linearity.
Give the shortcut formula for the variance, and .
, and .
What is the density of for a strictly monotone, differentiable ?
.
How do you sample from ?
Invert the CDF : .
What is the probability integral transform, and what is it used for?
For a continuous CDF and , . A histogram of PIT values checks whether predicted distributions are calibrated.
A PIT histogram is U-shaped. What is wrong with the forecasts?
They are too narrow (overconfident): the observations fall too often in their tails.
9. Interview angle #
- "You only have a uniform random number generator. How do you sample from a distribution with CDF ?" — Inverse CDF: return . For a discrete distribution, binary search in the cumulative sums, per draw. If has no closed form: a transformation such as Box–Muller (lesson 05) or rejection sampling (lesson 14).
- "What is for two independent uniforms?" — , from the CDF . In general, the maximum of uniforms has CDF and mean .
- "Expected number of fixed points, records, empty boxes or shared birthdays?" — Write the count as a sum of indicators, and use linearity.
- "Is ?" — No. For a positive , is convex, so by Jensen, with equality only for a constant .
- "Why does a minibatch gradient work?" — It is an unbiased estimate of the full gradient by linearity of expectation; its variance shrinks like for independent samples.
10. Practice #
The notebook for this lesson runs in Colab or in your browser. It has five exercises, each with a check cell and a folded solution:
mean_var(xs, ps): the mean and the variance from a PMF table, checked withscipy.stats.rv_discrete.sample_exponential(lam, n, rng): an inverse-CDF sampler for , checked with a Kolmogorov–Smirnov test against SciPy.sample_categorical(p, n, rng): the discrete inverse CDF with cumulative sums andnp.searchsorted.density_x_squared(y): the density of for , compared with a histogram.mean_fixed_points(n, trials, rng): simulate random permutations and compare the mean number of fixed points with 1.
11. Watch and read #
- Joseph Blitzstein and Jessica Hwang, Introduction to Probability, 2nd edition, free PDF: ch. 3 (random variables, PMF, CDF), ch. 4 (expectation, linearity, indicators, LOTUS, variance), ch. 5 (continuous random variables, "universality of the uniform" = inverse-CDF sampling) and §8.1 (change of variables).
- Art Owen, Monte Carlo theory, methods and examples, ch. 4 "Non-uniform random variables", §4.1–4.4: inversion, also for discrete distributions.
- Tilmann Gneiting, Fadoua Balabdaoui and Adrian Raftery, Probabilistic forecasts, calibration and sharpness, JRSS B 2007, §3.1: PIT histograms and their shapes.
- MIT 6.041, Probabilistic Systems Analysis and Applied Probability (OpenCourseWare): lectures 5–9 cover discrete and continuous random variables.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.