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 with a known distribution is passed through a function , and the question is the distribution of . 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. . For an invertible , is the preimage of , and the derivative. and are the densities and CDFs of and .
The discrete case#
If takes countably many values, so does , and happens exactly when lands on one of the values that sends to :
For a fair die and , the value comes from and , so . Nothing more is needed: probabilities of values are carried along and added up where values merge.
The distribution function method#
For a continuous the safe general method goes through the CDF, because is an event about :
and the density of is the derivative of the result.
A square. Let and . For , means , an interval of length out of 2:
Half the time is below , although is only a quarter of its range; the density of is infinite at 0, where the parabola is flat and many values of crowd into a few values of .
A linear map. For with , , so
and the same holds for . Applied to with , , it gives the density of : the standardization promised in the previous note. The other direction also holds: of a normal is normal, so a temperature of °C is one of °F.
The change-of-variables formula#
For a strictly increasing differentiable , , and differentiating gives the density of directly; for a decreasing the derivative changes sign, which the absolute value absorbs:
The formula says that probability is conserved band by band. A short interval of length around carries probability , and maps it to an interval of length around that must carry the same probability, . Where squeezes (), the density rises; where it stretches, the density falls:
Change of variables: probability is kept, density changes
The example is the log-normal distribution: with has and
Monotone maps carry quantiles along, so the median of is and . 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 is not monotone, every preimage contributes: . For above, the two preimages each contribute , which gives the same .
Inverse transform sampling#
Read in reverse, the CDF method turns uniform random numbers into any distribution. If and is a continuous, strictly increasing CDF, then has CDF , because
For any CDF, with flat stretches or jumps, the same holds with the quantile function of the previous note in place of : exactly when , because is non-decreasing and continuous from the right. The discrete sampler below is this .
For the exponential distribution, and :
Inverse transform sampling: from a uniform u to an exponential x
The same idea samples a discrete distribution. For a categorical distribution with probabilities , cut into consecutive pieces of lengths and return the piece in which lands; that is one lookup in the cumulative sums. A language model samples its next token exactly this way, after temperature or top- have reshaped the probabilities.
The converse is the probability integral transform: if has a continuous CDF , then . It is how probabilistic forecasts are checked, since the values 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, : in the two-sided test of 100 coin flips of the hypothesis tests note, a fair coin gives with probability . 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, with . Applying the change-of-variables formula once per map gives the exact log-density of a data point:
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#
| Before | With the change-of-variables formula | |
|---|---|---|
| Distribution of | simulate and look at a histogram | exact: , or through |
| Standardizing a normal | assumed | proved: |
| Sampling a distribution | needs a special trick per distribution | for any CDF; cumulative sums for a categorical |
| Density of a flow | — | exact log-likelihood, one per map |
Limitations#
- 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 . A function with flat pieces, such as rounding or clipping, puts positive probability on single values, and 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: sums over the preimages of .
- Continuous, general: compute , then differentiate.
- Continuous, monotone : at ; probability is conserved, density is squeezed or stretched.
- Linear maps keep normals normal; ; of a normal is log-normal.
- , in general , has CDF (inverse transform sampling); is uniform when 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 can be computed without finding the distribution of at all, and derives the rule for averages from the opening note.
References#
- J. K. Blitzstein, J. Hwang. Introduction to Probability, 2nd ed. CRC Press, 2019. Chapter 5 (universality of the uniform), Chapter 8 (transformations, change of variables).
- L. Devroye. Non-Uniform Random Variate Generation. Springer, 1986. Chapter II (the inversion method).
- D. Rezende, S. Mohamed. Variational Inference with Normalizing Flows. ICML, 2015.