Course contents 07 / 22

07 / 22 · Random Variables

Functions of random variables

If X has a known distribution, what is the distribution of g(X)? Summing over preimages for counts, the distribution-function method, the change-of-variables formula f_Y = f_X / |g′| with probability conserved band by band, inverse transform sampling (how simulations and language models draw random values), and the one-dimensional normalizing flow.

On this page 11

A temperature in Celsius becomes one in Fahrenheit, a measurement is standardized, a log-price is exponentiated back to a price, a uniform random number is turned into an exponential waiting time. Each time a random variable XX with a known distribution is passed through a function gg, and the question is the distribution of Y=g(X)Y = g(X). For counts the answer is a sum; for densities it is the change-of-variables formula, which says that probability is conserved while density is squeezed or stretched. The same formula, read backwards, is how computers sample from any distribution and how normalizing flows compute likelihoods.

Notation. Y=g(X)Y = g(X). For an invertible gg, x=g−1(y)x = g^{-1}(y) is the preimage of yy, and g′g' the derivative. fX,FXf_X, F_X and fY,FYf_Y, F_Y are the densities and CDFs of XX and YY.

The discrete case#

If XX takes countably many values, so does YY, and Y=yY = y happens exactly when XX lands on one of the values that gg sends to yy:

P(Y=y)=∑x : g(x)=yP(X=x).P(Y = y) = \sum_{x \,:\, g(x) = y} P(X = x) .

For a fair die XX and Y=(X−3)2Y = (X - 3)^2, the value Y=1Y = 1 comes from X=2X = 2 and X=4X = 4, so P(Y=1)=2/6P(Y = 1) = 2/6. Nothing more is needed: probabilities of values are carried along and added up where values merge.

The distribution function method#

For a continuous XX the safe general method goes through the CDF, because {Y≤y}\{Y \le y\} is an event about XX:

FY(y)=P(g(X)≤y),F_Y(y) = P(g(X) \le y) ,

and the density of YY is the derivative of the result.

A square. Let X∼U(−1,1)X \sim U(-1, 1) and Y=X2Y = X^2. For 0≤y≤10 \le y \le 1, Y≤yY \le y means −y≤X≤y-\sqrt y \le X \le \sqrt y, an interval of length 2y2\sqrt y out of 2:

FY(y)=y,fY(y)=12y.F_Y(y) = \sqrt y, \qquad f_Y(y) = \frac{1}{2 \sqrt y} .

Half the time X2X^2 is below 1/41/4, although 1/41/4 is only a quarter of its range; the density of YY is infinite at 0, where the parabola is flat and many values of XX crowd into a few values of YY.

A linear map. For Y=aX+bY = aX + b with a>0a > 0, FY(y)=P(X≤(y−b)/a)=FX((y−b)/a)F_Y(y) = P(X \le (y - b)/a) = F_X((y - b)/a), so

fY(y)=1∣a∣fX(y−ba),f_Y(y) = \frac{1}{\lvert a \rvert} f_X\Big(\frac{y - b}{a}\Big) ,

and the same holds for a<0a < 0. Applied to X∼N(μ,σ2)X \sim N(\mu, \sigma^2) with a=1/σa = 1/\sigma, b=−μ/σb = -\mu/\sigma, it gives the density of N(0,1)N(0, 1): the standardization Z=(X−μ)/σZ = (X - \mu)/\sigma promised in the previous note. The other direction also holds: aX+baX + b of a normal XX is normal, so a temperature of N(20,32)N(20, 3^2) °C is one of N(68,5.42)N(68, 5.4^2) °F.

The change-of-variables formula#

For a strictly increasing differentiable gg, FY(y)=FX(g−1(y))F_Y(y) = F_X(g^{-1}(y)), and differentiating gives the density of YY directly; for a decreasing gg the derivative changes sign, which the absolute value absorbs:

fY(y)=fX(x)∣g′(x)∣,x=g−1(y).f_Y(y) = \frac{f_X(x)}{\lvert g'(x) \rvert}, \qquad x = g^{-1}(y) .

The formula says that probability is conserved band by band. A short interval of length dxdx around xx carries probability fX(x) dxf_X(x)\, dx, and gg maps it to an interval of length dy=∣g′(x)∣ dxdy = \lvert g'(x) \rvert\, dx around yy that must carry the same probability, fY(y) dy=fX(x) dxf_Y(y)\, dy = f_X(x)\, dx. Where gg squeezes (∣g′∣<1\lvert g' \rvert < 1), the density rises; where it stretches, the density falls:

Figure

Change of variables: probability is kept, density changes

Bands of x, their images under eˣ and the density of YThe curve y = eˣ, the normal density of X below the x-axis and the log-normal density of Y left of the y-axis; two bands of comparable probability (0.127 and 0.115) become a narrow tall and a wide low piece of the density of Y.-2-101135y = eˣdensity of Xdensity of Y0.1270.115120.1270.115f_Y(y) = f_X(x) / g′(x)3Bands of x, their images under eˣ and the density of YThe curve y = eˣ, the normal density of X below the x-axis and the log-normal density of Y left of the y-axis; two bands of comparable probability (0.127 and 0.115) become a narrow tall and a wide low piece of the density of Y.-2-101135y = eˣdensity of Xdensity of Y0.1270.115120.1270.115f_Y(y) = f_X(x) / g′(x)3
X is standard normal (density at the bottom), Y = eˣ (the curve), the density of Y on the left. The band of x from −1.2 to −0.7 carries probability 0.127, the band from 0.8 to 1.3 carries 0.115 (1). The exponential squeezes the first into a y-interval of length 0.195 and stretches the second into one of length 1.444 (2). The probability is the same, so the density of Y is high over the first interval and low over the second: f_Y(y) = f_X(x) / g′(x) (3).

The example is the log-normal distribution: Y=eXY = e^X with X∼N(0,1)X \sim N(0, 1) has g′(x)=ex=yg'(x) = e^x = y and

fY(y)=φ(ln⁡y)y,y>0.f_Y(y) = \frac{\varphi(\ln y)}{y}, \qquad y > 0 .

Monotone maps carry quantiles along, so the median of YY is e0=1e^0 = 1 and P(Y>e)=P(X>1)=0.159P(Y > e) = P(X > 1) = 0.159. Quantities that are products of many positive factors, such as incomes, file sizes or response times, are often close to log-normal: their logarithm is a sum, close to normal for the reasons of the central limit theorem.

If gg is not monotone, every preimage contributes: fY(y)=∑x:g(x)=yfX(x)/∣g′(x)∣f_Y(y) = \sum_{x : g(x) = y} f_X(x) / \lvert g'(x) \rvert. For Y=X2Y = X^2 above, the two preimages ±y\pm\sqrt y each contribute 1/22y\frac{1/2}{2\sqrt y}, which gives the same 1/(2y)1/(2\sqrt y).

Inverse transform sampling#

Read in reverse, the CDF method turns uniform random numbers into any distribution. If U∼U(0,1)U \sim U(0, 1) and FF is a continuous, strictly increasing CDF, then X=F−1(U)X = F^{-1}(U) has CDF FF, because

P(F−1(U)≤x)=P(U≤F(x))=F(x).P(F^{-1}(U) \le x) = P(U \le F(x)) = F(x) .

For any CDF, with flat stretches or jumps, the same holds with the quantile function Q(u)=inf⁡{x:F(x)≥u}Q(u) = \inf\{x : F(x) \ge u\} of the previous note in place of F−1F^{-1}: Q(u)≤xQ(u) \le x exactly when u≤F(x)u \le F(x), because FF is non-decreasing and continuous from the right. The discrete sampler below is this QQ.

For the exponential distribution, F(x)=1−e−xF(x) = 1 - e^{-x} and F−1(u)=−ln⁡(1−u)F^{-1}(u) = -\ln(1 - u):

Figure

Inverse transform sampling: from a uniform u to an exponential x

The distribution function and five pairs (u, x)Five values of u on the vertical axis are mapped by the curve to x: 0.105, 0.357, 0.693, 1.204, 2.303.01234100.10.30.50.70.9ux = −ln(1 − u)The distribution function and five pairs (u, x)Five values of u on the vertical axis are mapped by the curve to x: 0.105, 0.357, 0.693, 1.204, 2.303.01234100.10.30.50.70.9ux = −ln(1 − u)
The curve is the distribution function F(x) = 1 − e^(−x) of the exponential distribution. A uniform u on the vertical axis is mapped to x = F⁻¹(u) = −ln(1 − u). The equally spaced u = 0.1, 0.3, 0.5, 0.7, 0.9 give x = 0.105, 0.357, 0.693, 1.204, 2.303: where F rises slowly, in the tail, the gaps between the x are wide and few points land there.

The same idea samples a discrete distribution. For a categorical distribution with probabilities p1,…,pKp_1, \dots, p_K, cut [0,1][0, 1] into consecutive pieces of lengths p1,…,pKp_1, \dots, p_K and return the piece in which UU lands; that is one lookup in the cumulative sums. A language model samples its next token exactly this way, after temperature or top-pp have reshaped the probabilities.

The converse is the probability integral transform: if XX has a continuous CDF FF, then F(X)∼U(0,1)F(X) \sim U(0, 1). It is how probabilistic forecasts are checked, since the values F(x)F(x) of a well-calibrated forecaster at the observed outcomes must look uniform, and it is why the p-value of a test whose statistic has a continuous distribution under the null hypothesis is uniformly distributed when that hypothesis is true. For a discrete statistic the p-value is only super-uniform, P(p≤α)≤αP(p \le \alpha) \le \alpha: in the two-sided test of 100 coin flips of the hypothesis tests note, a fair coin gives p≤0.05p \le 0.05 with probability 0.0350.035. The test stays valid, but it is conservative.

Normalizing flows in one dimension#

A normalizing flow models a complicated density as a simple one pushed through a chain of invertible maps, Y=gK(⋯g1(Z))Y = g_K(\cdots g_1(Z)) with Z∼N(0,1)Z \sim N(0, 1). Applying the change-of-variables formula once per map gives the exact log-density of a data point:

log⁡fY(y)=log⁡φ(z)−∑k=1Klog⁡∣gk′(zk−1)∣,z0=z=g−1(y),  zk=gk(zk−1).\log f_Y(y) = \log \varphi(z) - \sum_{k=1}^{K} \log \lvert g_k'(z_{k-1}) \rvert, \qquad z_0 = z = g^{-1}(y), \; z_k = g_k(z_{k-1}) .

Training maximizes this log-likelihood over the parameters of the maps. In more than one dimension the derivative becomes the determinant of the Jacobian, and making that determinant cheap is the design problem of the normalizing flows note in the generative models course.

What changed#

BeforeWith the change-of-variables formula
Distribution of g(X)g(X)simulate and look at a histogramexact: fX(x)/∣g′(x)∣f_X(x) / \lvert g'(x) \rvert, or FYF_Y through FXF_X
Standardizing a normalassumedproved: (X−μ)/σ∼N(0,1)(X - \mu)/\sigma \sim N(0, 1)
Sampling a distributionneeds a special trick per distributionF−1(U)F^{-1}(U) for any CDF; cumulative sums for a categorical
Density of a flow—exact log-likelihood, one log⁡∣g′∣\log \lvert g' \rvert per map

Limitations#

  • F−1F^{-1} is not always available in closed form. The normal CDF has no elementary inverse; samplers use other transformations (Box–Muller, which needs two variables) or numerical inversion.
  • The formula needs a differentiable, locally invertible gg. A function with flat pieces, such as rounding or clipping, puts positive probability on single values, and YY is then not continuous: rounding makes it discrete, clipping makes it a mixture of masses and a density.
  • Functions of several variables need their joint distribution. The distribution of the sum or the ratio of two random variables depends on how they depend on each other, the subject of the joint distributions note.

What you should remember#

  • Discrete: P(g(X)=y)P(g(X) = y) sums P(X=x)P(X = x) over the preimages of yy.
  • Continuous, general: compute FY(y)=P(g(X)≤y)F_Y(y) = P(g(X) \le y), then differentiate.
  • Continuous, monotone gg: fY(y)=fX(x)/∣g′(x)∣f_Y(y) = f_X(x) / \lvert g'(x) \rvert at x=g−1(y)x = g^{-1}(y); probability is conserved, density is squeezed or stretched.
  • Linear maps keep normals normal; (X−μ)/σ∼N(0,1)(X - \mu)/\sigma \sim N(0, 1); eXe^X of a normal is log-normal.
  • F−1(U)F^{-1}(U), in general Q(U)Q(U), has CDF FF (inverse transform sampling); F(X)F(X) is uniform when FF is continuous (probability integral transform).

Code#

The two bands of the figure, the square of a uniform, and inverse transform sampling, checked numerically:

import numpy as np
from scipy import stats

rng = np.random.default_rng(0)
Z = stats.norm()

# Y = e^X for X ~ N(0, 1): each band keeps its probability over an interval of a different length
for a, b in [(-1.2, -0.7), (0.8, 1.3)]:
    p = Z.cdf(b) - Z.cdf(a)
    print(round(p, 3), round(np.exp(b) - np.exp(a), 3), round(p / (np.exp(b) - np.exp(a)), 3))
# 0.127 0.195 0.649   (squeezed: high density)
# 0.115 1.444 0.08    (stretched: low density)
print(round(Z.sf(1), 4), stats.lognorm(1).median())              # 0.1587 1.0

# Y = X^2 for X ~ U(-1, 1): P(Y <= 1/4) = sqrt(1/4)
y = rng.uniform(-1, 1, 1_000_000) ** 2
print(round((y <= 0.25).mean(), 3))                              # 0.5

# inverse transform: -ln(1 - U) is Exp(1)
u = np.array([0.1, 0.3, 0.5, 0.7, 0.9])
print((-np.log(1 - u)).round(3))                                 # [0.105 0.357 0.693 1.204 2.303]
x = -np.log(1 - rng.random(1_000_000))
print(round(x.mean(), 3), round((x > 2).mean(), 4))              # 1.0 0.1354; exactly 1 and e^-2 = 0.1353

# a categorical distribution sampled through cumulative sums, as for a next token
p = np.array([0.5, 0.3, 0.2])
k = np.searchsorted(np.cumsum(p), rng.random(1_000_000), side='right')
print((np.bincount(k) / 1_000_000).round(3))                     # [0.499 0.301 0.199]

# the probability integral transform: F(X) is uniform
print(np.quantile(Z.cdf(rng.normal(size=1_000_000)), [0.1, 0.5, 0.9]).round(3))   # [0.1   0.499 0.9  ]

Next#

A distribution is a whole function; often two or three numbers are enough to work with: where it is centred, how wide it is, how heavy its tails are. The next note defines the expectation and the variance, shows that the expectation of g(X)g(X) can be computed without finding the distribution of g(X)g(X) at all, and derives the 1/n1/\sqrt n rule for averages from the opening note.

References#