Type at least 2 letters. Enter opens the first result, Esc closes.

    Probability and Statistics · Lesson 2 · Chance, random variables and distributions

    Random variables: PMF, PDF, CDF, expectation and variance

    Beginner 70 min 4 interactive figures 3 videos Colab notebook

    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 E[ℓ(f(X),Y)]\mathbb{E}[\ell(f(X), Y)], 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, z=μ+σεz = \mu + \sigma \varepsilon, 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 Ω\Omega has 36 equally likely outcomes (i,j)(i, j) (lesson 01). Let XX be the sum of the two dice. Then XX is a function on Ω\Omega: it maps (1,6)(1, 6) to 7, (4,4)(4, 4) to 8, and so on.

    A random variable is a function X:Ω→RX : \Omega \to \mathbb{R}. It is not random in itself; the outcome is random, and XX reads a number from it. We write {X=7}\{X = 7\} for the event "the sum is 7", the set of outcomes that XX maps to 7. It has 6 outcomes, so P(X=7)=6/36P(X = 7) = 6/36.

    The distribution of XX says how the probability mass on Ω\Omega lands on the real line. All 36 outcomes carry mass 1/361/36. The function XX 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) FX(x)=P(X≤x)F_X(x) = P(X \le x) is the mass collected from the left up to xx. It works for both cases: it is a staircase for a discrete XX and a smooth curve for a continuous one. The mass between aa and bb is the rise of the CDF:

    P(a<X≤b)=FX(b)−FX(a).P(a < X \le b) = F_X(b) - F_X(a) .
    Interactive figure: loading…

    Move aa and bb, 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 (a,b](a, b] 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 F(a)F(a) to F(b)F(b) (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, P(4<X≤7)=P(X∈{5,6,7})=(4+5+6)/36=15/36≈0.417P(4 < X \le 7) = P(X \in \{5, 6, 7\}) = (4 + 5 + 6)/36 = 15/36 \approx 0.417. For a continuous XX, a single point has no width, so it has no area: P(X=x)=0P(X = x) = 0 for every xx. This is why P(a<X≤b)P(a < X \le b) and P(a≤X≤b)P(a \le X \le b) are the same number for a continuous XX, but not for the dice.

    Quick check

    XX is uniform on [0,0.5][0, 0.5], so its density is constant on that interval. What is the value of the density, and what is P(X=0.25)P(X = 0.25)?

    The expectation is a balance point #

    Put the probability masses on a light beam, at their values. The expectation E[X]\mathbb{E}[X] is the point where the beam balances. For a discrete XX,

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

    For two dice, the distribution is symmetric around 7, so the beam balances at 7, and indeed E[X]=7\mathbb{E}[X] = 7. 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.

    Interactive figure: loading…

    Predict where the beam balances, then drag the dark triangle (the fulcrum) there. The orange discs are the probabilities pip_i, placed at the values xix_i. The readout shows the torque ∑ipi(xi−f)\sum_i p_i (x_i - f); the beam is level when it is 0. Press "Show the mean" to see E[X]\mathbb{E}[X] (yellow) and the band E[X]±σ\mathbb{E}[X] \pm \sigma (violet). Then try "one far mass": a mass of 0.1 at x=10x = 10 moves the balance point from 1 to 1.7 and makes the variance much larger.

    The torque about a point ff is ∑ipi(xi−f)=E[X]−f\sum_i p_i (x_i - f) = \mathbb{E}[X] - f, because the pip_i add up to 1. It is zero only at f=E[X]f = \mathbb{E}[X]. The variance is the average squared lever arm, Var⁡(X)=∑ipi(xi−E[X])2\operatorname{Var}(X) = \sum_i p_i (x_i - \mathbb{E}[X])^2. Squaring makes far masses count much more.

    Reading the CDF backwards #

    The CDF maps every value xx to a level u=F(x)u = F(x) between 0 and 1. Now go the other way. Pick a level uu uniformly at random in (0,1)(0, 1) and find the xx where the CDF reaches uu. This xx 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 uu over a short range of xx. Many uniform levels therefore land on that short range, and the samples pile up exactly where the density is high.

    Interactive figure: loading…

    Move the level uu, then press "Draw 500". The yellow path goes from uu on the vertical axis across to the orange CDF and down to x=F−1(u)x = F^{-1}(u). Each draw uses a new uniform uu. The blue histogram of the samples matches the orange density below. Notice that for Exp(1)\text{Exp}(1) the CDF is steepest at x=0x = 0, and most samples land there. Try "discrete": the CDF is a staircase, and each step catches the levels uu that belong to one value.

    Quick check

    For a continuous random variable, the CDF is very steep near x=2x = 2 and almost flat near x=5x = 5. Where do inverse-CDF samples land most often?

    3. Definitions and main results #

    PMF, PDF and CDF #

    • The probability mass function (PMF) of a discrete XX is pX(x)=P(X=x)p_X(x) = P(X = x). It satisfies pX(x)≥0p_X(x) \ge 0 and ∑xpX(x)=1\sum_x p_X(x) = 1.
    • A continuous XX has a probability density function (PDF) pX≥0p_X \ge 0 with ∫−∞∞pX(x) dx=1\int_{-\infty}^{\infty} p_X(x)\,dx = 1 and P(a≤X≤b)=∫abpX(x) dxP(a \le X \le b) = \int_a^b p_X(x)\,dx for all a≤ba \le b. Then P(X=x)=0P(X = x) = 0 for every xx.
    • The cumulative distribution function (CDF) is FX(x)=P(X≤x)F_X(x) = P(X \le x) for every real xx.

    Properties of a CDF. FXF_X is nondecreasing, it tends to 0 at −∞-\infty and to 1 at +∞+\infty, and it is right-continuous. For all a<ba < b, P(a<X≤b)=FX(b)−FX(a)P(a < X \le b) = F_X(b) - F_X(a): the event {X≤b}\{X \le b\} is the disjoint union of {X≤a}\{X \le a\} and {a<X≤b}\{a < X \le b\}. For a continuous XX, pX=FX′p_X = F_X' wherever pXp_X is continuous. For a discrete XX, FXF_X jumps by pX(x)p_X(x) at each value xx.

    We use pX(x)p_X(x), or just p(x)p(x), for both the PMF and the PDF. The context says which one.

    Expectation, LOTUS and linearity #

    Definition. The expectation (or mean) of XX is

    E[X]=∑xx pX(x)(discrete),E[X]=∫−∞∞x pX(x) dx(continuous).\mathbb{E}[X] = \sum_x x\, p_X(x) \quad \text{(discrete)}, \qquad \mathbb{E}[X] = \int_{-\infty}^{\infty} x\, p_X(x)\,dx \quad \text{(continuous)} .

    It exists when ∑x∣x∣ pX(x)<∞\sum_x |x|\,p_X(x) < \infty (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 p(x)=1π(1+x2)p(x) = \dfrac{1}{\pi(1 + x^2)}. It is symmetric around 0 and looks like a normal curve with heavy tails. But ∫−cc∣x∣ p(x) dx=1πln⁡(1+c2)\int_{-c}^{c} |x|\, p(x)\,dx = \frac{1}{\pi} \ln(1 + c^2) grows without bound as c→∞c \to \infty, so E[X]\mathbb{E}[X] does not exist. The consequence is real: the average of nn independent Cauchy samples is again Cauchy, with the same spread. It never settles down, however large nn is. The law of large numbers (lesson 06) needs a finite mean.

    We often need the mean of a function of XX, such as X2X^2 or a cost c(X)c(X). The next theorem says that we do not need the distribution of g(X)g(X) for it.

    Theorem (LOTUS, the law of the unconscious statistician). For any function gg,

    E[g(X)]=∑xg(x) pX(x)or∫g(x) pX(x) dx,\mathbb{E}[g(X)] = \sum_x g(x)\, p_X(x) \quad \text{or} \quad \int g(x)\, p_X(x)\,dx ,

    whenever the sum (or integral) of ∣g(x)∣ pX(x)|g(x)|\,p_X(x) is finite.

    Proof (discrete).

    1. Y=g(X)Y = g(X) takes the value yy when XX takes any xx with g(x)=yg(x) = y. So P(Y=y)=∑x: g(x)=ypX(x)P(Y = y) = \sum_{x:\, g(x) = y} p_X(x).
    2. By the definition of the mean, E[Y]=∑yy P(Y=y)=∑y∑x: g(x)=yg(x) pX(x)\mathbb{E}[Y] = \sum_y y\,P(Y = y) = \sum_y \sum_{x:\, g(x) = y} g(x)\,p_X(x), because y=g(x)y = g(x) inside the inner sum.
    3. Every xx belongs to exactly one group (the group of y=g(x)y = g(x)). So the double sum is a sum over all xx: ∑xg(x) pX(x)\sum_x g(x)\,p_X(x). ■\blacksquare

    Theorem (linearity of expectation). For random variables X,YX, Y with finite means and constants a,b,ca, b, c,

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

    No independence is needed.

    Proof (discrete).

    1. Let p(x,y)=P(X=x,Y=y)p(x, y) = P(X = x, Y = y) be the joint PMF (lesson 04 studies it). LOTUS for the pair (X,Y)(X, Y) gives E[X+Y]=∑x,y(x+y) p(x,y)\mathbb{E}[X + Y] = \sum_{x, y} (x + y)\,p(x, y).
    2. Split the sum into two parts: ∑xx∑yp(x,y)+∑yy∑xp(x,y)\sum_x x \sum_y p(x, y) + \sum_y y \sum_x p(x, y).
    3. The inner sums are the PMFs of XX and of YY alone: ∑yp(x,y)=pX(x)\sum_y p(x, y) = p_X(x) by the law of total probability. So the total is E[X]+E[Y]\mathbb{E}[X] + \mathbb{E}[Y].
    4. LOTUS with g(x)=ax+cg(x) = ax + c gives E[aX+c]=a E[X]+c\mathbb{E}[aX + c] = a\,\mathbb{E}[X] + c. Combine the two results. ■\blacksquare

    We never wrote p(x,y)p(x, y) as a product pX(x) pY(y)p_X(x)\,p_Y(y). That is why the result holds for dependent variables.

    A warning. In general E[g(X)]≠g(E[X])\mathbb{E}[g(X)] \ne g(\mathbb{E}[X]). It is equal for every XX only when gg is linear plus a constant. For a convex gg (such as x2x^2 or exe^x), Jensen's inequality says E[g(X)]≥g(E[X])\mathbb{E}[g(X)] \ge g(\mathbb{E}[X]) (information theory, lesson 3). For example, E[X2]≥E[X]2\mathbb{E}[X^2] \ge \mathbb{E}[X]^2, and the gap is the variance.

    Indicator variables #

    The indicator of an event AA is the random variable IAI_A that is 1 when AA happens and 0 otherwise. Its mean is a probability:

    E[IA]=1⋅P(A)+0⋅P(Ac)=P(A).\mathbb{E}[I_A] = 1 \cdot P(A) + 0 \cdot P(A^c) = P(A) .

    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 nn cards numbered 1,…,n1, \dots, n. A fixed point is a card that ends in its own position. Let IiI_i be the indicator of "card ii is in position ii". By symmetry, card ii is equally likely to be in each of the nn positions, so P(Ii=1)=1/nP(I_i = 1) = 1/n. The number of fixed points is N=I1+⋯+InN = I_1 + \dots + I_n, and

    E[N]=∑i=1n1n=1for every n.\mathbb{E}[N] = \sum_{i=1}^n \frac1n = 1 \qquad \text{for every } n .

    The indicators are dependent (if cards 1,…,n−11, \dots, n-1 are fixed, card nn must be fixed too), but linearity does not care.

    Example 2: records. Daily values X1,…,XnX_1, \dots, X_n are independent and identically distributed (i.i.d.) and continuous, so there are no ties. Day kk is a record if XkX_k is larger than all earlier values. By symmetry, each of the first kk days is equally likely to hold the largest of the first kk values, so P(day k is a record)=1/kP(\text{day } k \text{ is a record}) = 1/k. Hence

    E[number of records]=∑k=1n1k=Hn≈ln⁡n+0.577.\mathbb{E}[\text{number of records}] = \sum_{k=1}^n \frac1k = H_n \approx \ln n + 0.577 .

    For a year of daily temperatures with no trend (n=365n = 365), this is H365≈6.48H_{365} \approx 6.48 records. Many more records than this are evidence of a trend.

    Quick check

    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?

    Variance and standardising #

    Definition. With μ=E[X]\mu = \mathbb{E}[X], the variance is Var⁡(X)=E[(X−μ)2]\operatorname{Var}(X) = \mathbb{E}[(X - \mu)^2], and the standard deviation is σ=Var⁡(X)\sigma = \sqrt{\operatorname{Var}(X)}. The standard deviation has the same unit as XX.

    Theorem. (a) Var⁡(X)=E[X2]−μ2\operatorname{Var}(X) = \mathbb{E}[X^2] - \mu^2. (b) Var⁡(aX+b)=a2Var⁡(X)\operatorname{Var}(aX + b) = a^2 \operatorname{Var}(X).

    Proof.

    1. (a) Expand the square: (X−μ)2=X2−2μX+μ2(X - \mu)^2 = X^2 - 2\mu X + \mu^2.
    2. Use linearity: E[X2]−2μ E[X]+μ2=E[X2]−2μ2+μ2=E[X2]−μ2\mathbb{E}[X^2] - 2\mu\,\mathbb{E}[X] + \mu^2 = \mathbb{E}[X^2] - 2\mu^2 + \mu^2 = \mathbb{E}[X^2] - \mu^2.
    3. (b) aX+baX + b has mean aμ+ba\mu + b, so aX+b−(aμ+b)=a(X−μ)aX + b - (a\mu + b) = a(X - \mu). Square it and take the mean: a2 E[(X−μ)2]=a2Var⁡(X)a^2\,\mathbb{E}[(X - \mu)^2] = a^2 \operatorname{Var}(X). ■\blacksquare

    A shift bb moves the distribution but does not change its spread. A scale aa multiplies the spread by ∣a∣|a|, so the variance by a2a^2.

    Standardising. The z-score Z=(X−μ)/σZ = (X - \mu)/\sigma has mean 0 and variance 1, by (b) with a=1/σa = 1/\sigma and b=−μ/σb = -\mu/\sigma. 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 z=(85−70)/10=1.5z = (85 - 70)/10 = 1.5. Feature standardisation in ML ("StandardScaler") applies this to every input feature.

    Sums. Random variables XX and YY are independent if P(X∈A,Y∈B)=P(X∈A) P(Y∈B)P(X \in A, Y \in B) = P(X \in A)\,P(Y \in B) for all sets A,BA, B of values. For independent XX and YY, the variances add: Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)\operatorname{Var}(X + Y) = \operatorname{Var}(X) + \operatorname{Var}(Y). For dependent variables there is an extra covariance term; lesson 04 proves both. One consequence: for i.i.d. X1,…,XnX_1, \dots, X_n with variance σ2\sigma^2, the sample mean Xˉn=1n∑iXi\bar X_n = \frac1n \sum_i X_i has variance σ2/n\sigma^2/n (use (b) with a=1/na = 1/n). Averages are less noisy than single values.

    The density of Y=g(X)Y = g(X) #

    We often transform a random variable: Y=X2Y = X^2, Y=eXY = e^X, Y=μ+σXY = \mu + \sigma X. What is the density of YY? The answer is not pX(g−1(y))p_X(g^{-1}(y)). There is an extra factor, because gg stretches or squeezes the axis.

    Interactive figure: loading…

    Move the interval, then switch the map gg. XX is uniform on (0,1)(0, 1). The yellow interval II on the xx-axis holds probability equal to its width. The map gg (orange curve) sends it to the yellow interval g(I)g(I) on the yy-axis, which holds the same probability. Where g(I)g(I) is wide, the density of YY is low; where it is narrow, the density is high. The blue histogram of simulated values of g(X)g(X) matches the orange formula for pYp_Y. For g(x)=x2g(x) = x^2, the values pile up near 0.

    The rule is conservation of probability. A short interval of length ∣dx∣|dx| around xx holds probability pX(x) ∣dx∣p_X(x)\,|dx|. The map gg sends it to an interval of length ∣dy∣|dy| around y=g(x)y = g(x) that holds the same probability. So pY(y) ∣dy∣=pX(x) ∣dx∣p_Y(y)\,|dy| = p_X(x)\,|dx|, and pY(y)=pX(x) ∣dx/dy∣p_Y(y) = p_X(x)\,|dx/dy|.

    Theorem (change of variables in one dimension). Let XX have density pXp_X, and let gg be strictly monotone and differentiable, with g′≠0g' \ne 0 on the set where pX>0p_X > 0. Then Y=g(X)Y = g(X) has density

    pY(y)=pX(g−1(y)) ∣ddyg−1(y)∣p_Y(y) = p_X\big(g^{-1}(y)\big)\, \left|\frac{d}{dy} g^{-1}(y)\right|

    for yy in the image of that set, and pY(y)=0p_Y(y) = 0 elsewhere.

    Proof.

    1. Let gg be increasing. Then g(X)≤yg(X) \le y exactly when X≤g−1(y)X \le g^{-1}(y). So FY(y)=FX(g−1(y))F_Y(y) = F_X(g^{-1}(y)).
    2. Differentiate with the chain rule: pY(y)=pX(g−1(y)) (g−1)′(y)p_Y(y) = p_X(g^{-1}(y))\,(g^{-1})'(y). Here (g−1)′>0(g^{-1})' > 0.
    3. Let gg be decreasing. Then g(X)≤yg(X) \le y exactly when X≥g−1(y)X \ge g^{-1}(y). So FY(y)=1−FX(g−1(y))F_Y(y) = 1 - F_X(g^{-1}(y)) (P(X=g−1(y))=0P(X = g^{-1}(y)) = 0 because XX is continuous).
    4. Differentiate: pY(y)=−pX(g−1(y)) (g−1)′(y)p_Y(y) = -p_X(g^{-1}(y))\,(g^{-1})'(y). This is positive, because (g−1)′<0(g^{-1})' < 0. Both cases give the absolute value in the theorem. ■\blacksquare

    Example. X∼U(0,1)X \sim U(0, 1) and Y=X2Y = X^2. Then g−1(y)=yg^{-1}(y) = \sqrt y and (g−1)′(y)=1/(2y)(g^{-1})'(y) = 1/(2\sqrt y), so pY(y)=1⋅12yp_Y(y) = 1 \cdot \frac{1}{2\sqrt y} for 0<y≤10 < y \le 1. The density is large near 0: the map x↦x2x \mapsto x^2 squeezes the interval (0,0.5)(0, 0.5) into (0,0.25)(0, 0.25).

    Example (affine map). Y=μ+σXY = \mu + \sigma X with σ>0\sigma > 0. Then g−1(y)=(y−μ)/σg^{-1}(y) = (y - \mu)/\sigma, so pY(y)=1σ pX(y−μσ)p_Y(y) = \frac1\sigma\, p_X\big(\frac{y - \mu}{\sigma}\big). With X∼N(0,1)X \sim \mathcal N(0, 1), this gives the density of N(μ,σ2)\mathcal N(\mu, \sigma^2). This is the reparameterisation trick.

    When gg is not monotone, use the CDF method. Compute FY(y)=P(g(X)≤y)F_Y(y) = P(g(X) \le y) directly, then differentiate. Let XX be uniform on (−1,1)(-1, 1), with density 1/21/2, and Y=X2Y = X^2. For 0<y<10 < y < 1:

    FY(y)=P(−y≤X≤y)=2y2=y,pY(y)=12y.F_Y(y) = P(-\sqrt y \le X \le \sqrt y) = \frac{2\sqrt y}{2} = \sqrt y , \qquad p_Y(y) = \frac{1}{2\sqrt y} .

    In general, add the contributions of all branches: for Y=X2Y = X^2, pY(y)=[pX(y)+pX(−y)]/(2y)p_Y(y) = \big[p_X(\sqrt y) + p_X(-\sqrt y)\big] / (2\sqrt y). Lesson 05 extends the rule to vectors, where the factor ∣dx/dy∣|dx/dy| becomes the absolute determinant of a Jacobian matrix.

    Quick check

    X∼U(0,1)X \sim U(0, 1) and Y=3XY = 3X. Which is the density of YY?

    Inverse-CDF sampling and the probability integral transform #

    Theorem. Let FF be a continuous, strictly increasing CDF, and let U∼U(0,1)U \sim U(0, 1).

    • (a) Inverse-CDF sampling: X=F−1(U)X = F^{-1}(U) has CDF FF.
    • (b) Probability integral transform (PIT): if XX has CDF FF, then F(X)∼U(0,1)F(X) \sim U(0, 1).

    Proof.

    1. FF is strictly increasing, so F−1(u)≤xF^{-1}(u) \le x exactly when u≤F(x)u \le F(x).
    2. (a) P(F−1(U)≤x)=P(U≤F(x))=F(x)P(F^{-1}(U) \le x) = P(U \le F(x)) = F(x), because P(U≤u)=uP(U \le u) = u for u∈[0,1]u \in [0, 1].
    3. (b) For u∈(0,1)u \in (0, 1): P(F(X)≤u)=P(X≤F−1(u))=F(F−1(u))=uP(F(X) \le u) = P(X \le F^{-1}(u)) = F(F^{-1}(u)) = u. This is the CDF of U(0,1)U(0, 1). ■\blacksquare

    Example. Exp(λ)\text{Exp}(\lambda) has CDF F(x)=1−e−λxF(x) = 1 - e^{-\lambda x} for x≥0x \ge 0. Solve u=F(x)u = F(x): x=−ln⁡(1−u)/λx = -\ln(1 - u)/\lambda. So −ln⁡(1−U)/λ-\ln(1 - U)/\lambda is an exponential sample. With λ=1\lambda = 1 and u=0.6u = 0.6, it gives x=−ln⁡0.4≈0.916x = -\ln 0.4 \approx 0.916.

    Discrete distributions. For a CDF with jumps or flat parts, use the generalised inverse F−1(u)=min⁡{x:F(x)≥u}F^{-1}(u) = \min\{x : F(x) \ge u\}. Step 1 still holds, because FF 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 uu. A binary search does this in O(log⁡K)O(\log K) steps for KK values (np.searchsorted). Part (b) needs a continuous FF: for a discrete XX, F(X)F(X) takes only the values F(xk)F(x_k), so it cannot be uniform.

    PIT histograms check calibration. A model predicts a full distribution, with CDF FtF_t, for each future value yty_t (tomorrow's temperature, a delivery time, the next sales number). If the model is calibrated (its predicted distributions are correct), the values Ft(yt)F_t(y_t) 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 N(0,1)\mathcal N(0, 1) but the model predicts N(0,0.52)\mathcal N(0, 0.5^2), the five bins of the PIT histogram have masses 0.337,0.113,0.101,0.113,0.3370.337, 0.113, 0.101, 0.113, 0.337: a clear U.

    Answers to section 1. (1) No. P(Y≤0.25)=P(X≤0.5)=0.5P(Y \le 0.25) = P(X \le 0.5) = 0.5, and pY(y)=1/(2y)p_Y(y) = 1/(2\sqrt y) piles up near 0. (2) 50⋅0.3=1550 \cdot 0.3 = 15. 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; U(0,1/3)U(0, 1/3) has density 3 on its interval.

    4. Worked example #

    A. Discrete. A small support team gets XX urgent tickets per day, with

    xx 0 1 2 3
    pX(x)p_X(x) 0.4 0.3 0.2 0.1
    1. CDF. Add from the left: F(0)=0.4F(0) = 0.4, F(1)=0.7F(1) = 0.7, F(2)=0.9F(2) = 0.9, F(3)=1F(3) = 1 (a staircase). So P(X≥2)=1−F(1)=0.3P(X \ge 2) = 1 - F(1) = 0.3.
    2. Mean. E[X]=0⋅0.4+1⋅0.3+2⋅0.2+3⋅0.1=0+0.3+0.4+0.3=1.0\mathbb{E}[X] = 0 \cdot 0.4 + 1 \cdot 0.3 + 2 \cdot 0.2 + 3 \cdot 0.1 = 0 + 0.3 + 0.4 + 0.3 = 1.0.
    3. Second moment (LOTUS with g(x)=x2g(x) = x^2). E[X2]=0⋅0.4+1⋅0.3+4⋅0.2+9⋅0.1=0.3+0.8+0.9=2.0\mathbb{E}[X^2] = 0 \cdot 0.4 + 1 \cdot 0.3 + 4 \cdot 0.2 + 9 \cdot 0.1 = 0.3 + 0.8 + 0.9 = 2.0.
    4. Variance. Var⁡(X)=2.0−1.02=1.0\operatorname{Var}(X) = 2.0 - 1.0^2 = 1.0, so σ=1.0\sigma = 1.0.
    5. A cost. Each day costs c(X)=10X2c(X) = 10X^2 (overtime grows fast). LOTUS gives E[c(X)]=10⋅2.0=20\mathbb{E}[c(X)] = 10 \cdot 2.0 = 20. But c(E[X])=10⋅12=10c(\mathbb{E}[X]) = 10 \cdot 1^2 = 10. Planning with the average number of tickets underestimates the average cost by half (Jensen, x2x^2 is convex).

    This is the "worked example" preset of the balance-point figure in section 2.

    B. Continuous. X=max⁡(U1,U2)X = \max(U_1, U_2) for two independent uniforms on [0,1][0, 1] (the better of two random scores).

    1. CDF. X≤xX \le x exactly when both U1≤xU_1 \le x and U2≤xU_2 \le x. By independence, F(x)=x⋅x=x2F(x) = x \cdot x = x^2 for 0≤x≤10 \le x \le 1.
    2. Density. p(x)=F′(x)=2xp(x) = F'(x) = 2x on [0,1][0, 1]. Large values are more likely, as expected for a maximum.
    3. Mean. E[X]=∫01x⋅2x dx=[2x33]01=23\mathbb{E}[X] = \int_0^1 x \cdot 2x\,dx = \left[\tfrac{2x^3}{3}\right]_0^1 = \tfrac23.
    4. Variance. E[X2]=∫01x2⋅2x dx=[x42]01=12\mathbb{E}[X^2] = \int_0^1 x^2 \cdot 2x\,dx = \left[\tfrac{x^4}{2}\right]_0^1 = \tfrac12, so Var⁡(X)=12−49=118≈0.0556\operatorname{Var}(X) = \tfrac12 - \tfrac49 = \tfrac{1}{18} \approx 0.0556.
    5. Inverse CDF. Solve u=x2u = x^2: F−1(u)=uF^{-1}(u) = \sqrt u. So U\sqrt U has the same distribution as max⁡(U1,U2)\max(U_1, U_2): one uniform number is enough. (The "density 2x" preset of the inverse-CDF figure.)
    6. PIT check. Y=F(X)=X2Y = F(X) = X^2. With g−1(y)=yg^{-1}(y) = \sqrt y and (g−1)′(y)=1/(2y)(g^{-1})'(y) = 1/(2\sqrt y), the change-of-variables rule gives pY(y)=2y⋅12y=1p_Y(y) = 2\sqrt y \cdot \frac{1}{2\sqrt y} = 1 on (0,1)(0, 1). Uniform, as the theorem says.
    Quick check

    In part A, the team lead plans with E[X]=1\mathbb{E}[X] = 1 ticket per day. Each ticket takes 2 hours, plus a fixed 1 hour for the daily meeting, so the time is T=2X+1T = 2X + 1. What are E[T]\mathbb{E}[T] and Var⁡(T)\operatorname{Var}(T)?

    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 ±0.01\pm 0.01 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 1n∑iℓi\frac1n \sum_i \ell_i, an estimate of the risk E[ℓ]\mathbb{E}[\ell]. 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 z=μ+σεz = \mu + \sigma \varepsilon with ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1), 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, T=FY−1∘FXT = F_Y^{-1} \circ F_X sends a continuous XX to a variable with CDF FYF_Y (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 pp and, for nn independent users, variance p(1−p)/np(1 - p)/n.
    • Records and extremes. In a series without trend, the expected number of records grows only like ln⁡n\ln n. Counting records is a simple test for a trend in temperature series.

    7. Common mistakes #

    • E[g(X)]=g(E[X])\mathbb{E}[g(X)] = g(\mathbb{E}[X]). False in general. For a convex gg, E[g(X)]≥g(E[X])\mathbb{E}[g(X)] \ge g(\mathbb{E}[X]) (Jensen). In the worked example: 20≥1020 \ge 10.
    • Reading a density value as a probability. U(0,0.5)U(0, 0.5) has density 2. Only areas under the density are probabilities.
    • Forgetting the factor ∣dg−1/dy∣|dg^{-1}/dy| when you transform a density. Check that the new density integrates to 1.
    • Using the change-of-variables formula for a non-monotone gg. For Y=X2Y = X^2 with XX on both sides of 0, add both branches, or use the CDF method.
    • Adding variances of dependent variables. Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)\operatorname{Var}(X + Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) needs zero covariance. And for independent X,YX, Y, Var⁡(X−Y)\operatorname{Var}(X - Y) is also the sum Var⁡(X)+Var⁡(Y)\operatorname{Var}(X) + \operatorname{Var}(Y), not the difference.
    • E[X2]−E[X]2\mathbb{E}[X^2] - \mathbb{E}[X]^2 in floating point. With values near 10810^8, both terms are huge and nearly equal, and the difference loses all its digits. Compute E[(X−μ)2]\mathbb{E}[(X - \mu)^2] instead (two passes over the data).
    • log⁡U\log U with U=0U = 0. rng.random() returns values in [0,1)[0, 1) and can return exactly 0. Use −log⁡(1−U)-\log(1 - U), which is always finite.
    • Expecting F(X)F(X) to be uniform for a discrete XX. It takes only the values F(xk)F(x_k).

    8. Check yourself #

    1. X∼U(0,2)X \sim U(0, 2). Give the density, P(X≤0.5)P(X \le 0.5), E[X]\mathbb{E}[X] and Var⁡(X)\operatorname{Var}(X).
      AnswerThe density is 1/21/2 on [0,2][0, 2]. P(X≤0.5)=0.5⋅1/2=0.25P(X \le 0.5) = 0.5 \cdot 1/2 = 0.25. E[X]=1\mathbb{E}[X] = 1 (the middle). E[X2]=∫02x2/2 dx=4/3\mathbb{E}[X^2] = \int_0^2 x^2/2\,dx = 4/3, so Var⁡(X)=4/3−1=1/3\operatorname{Var}(X) = 4/3 - 1 = 1/3 (in general (b−a)2/12(b - a)^2/12 for U(a,b)U(a, b)).
    2. Var⁡(X)=4\operatorname{Var}(X) = 4. Find Var⁡(3X−2)\operatorname{Var}(3X - 2), and Var⁡(X−Y)\operatorname{Var}(X - Y) for an independent copy YY of XX.
      AnswerVar⁡(3X−2)=9⋅4=36\operatorname{Var}(3X - 2) = 9 \cdot 4 = 36. Var⁡(X−Y)=Var⁡(X)+(−1)2Var⁡(Y)=4+4=8\operatorname{Var}(X - Y) = \operatorname{Var}(X) + (-1)^2 \operatorname{Var}(Y) = 4 + 4 = 8.
    3. 30 people have independent birthdays, uniform over 365 days. What is the expected number of pairs of people with the same birthday?
      AnswerOne indicator per pair. Each pair shares a birthday with probability 1/3651/365. There are (302)=435\binom{30}{2} = 435 pairs, so the mean is 435/365≈1.19435/365 \approx 1.19. The pair indicators are dependent, but linearity does not need independence.
    4. X∼N(0,1)X \sim \mathcal N(0, 1) and Y=eXY = e^X. Find the density of YY.
      Answerg(x)=exg(x) = e^x is increasing, g−1(y)=ln⁡yg^{-1}(y) = \ln y and (g−1)′(y)=1/y(g^{-1})'(y) = 1/y. So pY(y)=φ(ln⁡y)/yp_Y(y) = \varphi(\ln y)/y for y>0y > 0, where φ\varphi is the standard normal density. This is the **log-normal** distribution.
    5. Observations come from N(0,1)\mathcal N(0, 1), but a model predicts N(0,22)\mathcal N(0, 2^2). What shape does the PIT histogram have?
      AnswerA hump: the predicted distribution is too wide, so the observations fall mostly in its middle, where FF is near 0.5. With 5 bins the masses are about 0.05,0.26,0.39,0.26,0.050.05, 0.26, 0.39, 0.26, 0.05.
    6. You want samples of a discrete XX with P(X=0,1,2,3)=0.4,0.3,0.2,0.1P(X = 0, 1, 2, 3) = 0.4, 0.3, 0.2, 0.1, and you draw u=0.75u = 0.75. Which value does the inverse-CDF method return?
      AnswerThe cumulative sums are 0.4,0.7,0.9,1.00.4, 0.7, 0.9, 1.0. The first value whose cumulative sum reaches 0.750.75 is x=2x = 2 (because 0.7<0.75≤0.90.7 < 0.75 \le 0.9).
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is the difference between a PMF value and a PDF value?

    2. How do you get P(a<X≤b)P(a < X \le b) from the CDF?

    3. State LOTUS.

    4. Does linearity of expectation need independence? Give the formula.

    5. What is the expected number of fixed points of a random permutation of nn items, and why?

    6. Give the shortcut formula for the variance, and Var⁡(aX+b)\operatorname{Var}(aX + b).

    7. What is the density of Y=g(X)Y = g(X) for a strictly monotone, differentiable gg?

    8. How do you sample Exp(λ)\text{Exp}(\lambda) from U∼U(0,1)U \sim U(0, 1)?

    9. What is the probability integral transform, and what is it used for?

    10. A PIT histogram is U-shaped. What is wrong with the forecasts?

    Open the review →

    9. Interview angle #

    • "You only have a uniform random number generator. How do you sample from a distribution with CDF FF?" — Inverse CDF: return F−1(U)F^{-1}(U). For a discrete distribution, binary search in the cumulative sums, O(log⁡K)O(\log K) per draw. If F−1F^{-1} has no closed form: a transformation such as Box–Muller (lesson 05) or rejection sampling (lesson 14).
    • "What is E[max⁡(U1,U2)]\mathbb{E}[\max(U_1, U_2)] for two independent uniforms?" — 2/32/3, from the CDF x2x^2. In general, the maximum of nn uniforms has CDF xnx^n and mean n/(n+1)n/(n + 1).
    • "Expected number of fixed points, records, empty boxes or shared birthdays?" — Write the count as a sum of indicators, and use linearity.
    • "Is E[1/X]=1/E[X]\mathbb{E}[1/X] = 1/\mathbb{E}[X]?" — No. For a positive XX, 1/x1/x is convex, so E[1/X]≥1/E[X]\mathbb{E}[1/X] \ge 1/\mathbb{E}[X] by Jensen, with equality only for a constant XX.
    • "Why does a minibatch gradient work?" — It is an unbiased estimate of the full gradient by linearity of expectation; its variance shrinks like 1/(batch size)1/(\text{batch size}) 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:

    1. mean_var(xs, ps): the mean and the variance from a PMF table, checked with scipy.stats.rv_discrete.
    2. sample_exponential(lam, n, rng): an inverse-CDF sampler for Exp(λ)\text{Exp}(\lambda), checked with a Kolmogorov–Smirnov test against SciPy.
    3. sample_categorical(p, n, rng): the discrete inverse CDF with cumulative sums and np.searchsorted.
    4. density_x_squared(y): the density of Y=X2Y = X^2 for X∼U(−1,1)X \sim U(-1, 1), compared with a histogram.
    5. mean_fixed_points(n, trials, rng): simulate random permutations and compare the mean number of fixed points with 1.

    11. Watch and read #

    Linearity of expectation and the indicator method, with several counting examples like those of section 3.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Why a continuous variable needs a density, and why single points have probability 0 (section 2).
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    PDFs, CDFs, expectation and variance for continuous random variables, at the level of section 3.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play