Transformations of random variables and change of variables
How a density changes when its variable is transformed: the Jacobian as a volume-change factor, sums of log-determinants in transformation chains (the exact basis of normalizing flows), convolution for sums of independent variables, Box–Muller and order statistics.
After this lesson you can
- Derive the density of Y = g(X) in one and several dimensions, including non-injective transformations.
- Calculate log-densities of composed transformations by summing each layer’s log|det J|.
- Obtain the law of sums of independent variables by convolution.
- Derive the Box–Muller transform and gamma–beta relationships by change of variables.
- Calculate the laws of the minimum, maximum and k-th order statistic.
Before you start
- 04Probability densityLaw of a random variable (pushforward measure)Joint law and marginalsIndependent random variablesFubini-Tonelli theoremsCumulative distribution functionUnivariate normal distributionExponential, gamma and chi-squared distributionsBeta and Dirichlet distributions
- 03Jacobian matrixChange of variables formulaInverse function theorem
- 02Determinant
Motivation: an exact-density model built from changes of variables
You want a generative model of data in with two properties at once: you can sample from it and evaluate its density exactly, without bounds or approximations, to train it by maximum likelihood. The normalizing-flow recipe is surprisingly short. Start with a variable of known law, , and apply an invertible, differentiable function parameterized by a neural network. Sampling means evaluating . Evaluating the density uses this lesson’s formula: the density of at is that of at , corrected for how much stretches volume around that point.
That correction, the Jacobian, appears everywhere a random variable is transformed:
- Reparameterization. A variational autoencoder writes with and needs to know the resulting law.
- Sampling. Your library’s random-number generator only knows how to produce uniform variables. Everything else (normal, exponential, categorical) comes from transforming them.
- Sums and accumulation. A system’s total error is a sum of independent errors. What density does that sum have?
- Ordering. The maximum of scores, the sample median, the largest in a batch: laws of order statistics.
This lesson answers four connected questions.
- One dimension. If , what is the density of ? We must count how much stretches and what to do when folds the line onto itself.
- Several dimensions. What role does the Jacobian determinant play, and why do the log-determinants in a chain of layers add?
- Sums and coordinate changes. Convolution is a change of variables with Jacobian 1; polar coordinates give Box–Muller, followed by ratios, the beta law, Student’s and the Cauchy law.
- Order statistics. The laws of the minimum, maximum and -th statistic, and an identity between binomial tails and the beta distribution function proved without integration.
Everything that follows applies a single calculus theorem, change of variables in integrals (calculus lesson), to the pushforward law you already know.
One dimension: density dilutes where stretches
Let be a random variable with density and let . The law of is the pushforward measure , and our task is to read off its density. Start with the clean case: is differentiable and monotone.
Proof
Let be Borel. Since ,
The last equality is the change of variables in an integral, valid because is and its derivative does not vanish; the absolute value accounts for the fact that, if is decreasing, the change reverses the limits of integration. A function whose integral over every Borel set gives the law of is, by uniqueness in the Radon–Nikodym theorem, a density of (unique up to sets of measure zero).
∎Using distribution functions, the same result takes one line. If is increasing, , and differentiating gives . If it is decreasing, and the derivative changes sign, so the absolute value appears automatically.
The interpretation matters more than the formula. A density is not a probability but a probability per unit length. The mass of a tiny interval is , and sends it to an interval of length with the same mass. If stretches by a factor of , the same mass spreads across more length and the density is divided by that factor:
The first figure shows this. Take eight bands of with exactly the same probability (hence narrow where is high and wide in the tails), transport them through , and measure each band’s width in .
What you should have seen:
- The bars on the right match the curve. Each bar is an average density (mass divided by width), and the continuous curve is the exact density; they agree ever more closely as the bands become thinner, and the simulated points fall on the curve.
- Where is almost flat, the density of shoots up. With “Sigmoid” the tails of are compressed against the endpoints and the density of accumulates there (bars extending outside the panel have an mark). With “Flat center” the entire central part of piles up around .
- If is decreasing, the density is the same as with the reflected function. The absolute value of distinguishes only how much it stretches, not its direction.
- The probe reads the formula. divided by gives , the value read from the right panel at .
When is not injective: sum over the preimages
Many useful transformations fold the line: , , . Then each value can come from several , and the probability of a neighborhood of is the sum of the masses arriving through all branches.
Proof
For Borel , by countable additivity. Each term is by the previous theorem applied to the branch . Sum the integrals and exchange the sum and integral (everything is nonnegative, by Tonelli).
∎Divergent densities are not peculiar to this example. They occur precisely at the critical values of , those with . Near a critical point with , : the two preimages are away from , and equals there. Each branch’s contribution grows like , an integrable singularity: the total mass is still one. The second figure stacks the branches so you can see where each piece of the density comes from.
What you should have seen:
- The density of is the sum of the branches. In with the two contributions are equal; moving makes the branch closer to the maximum of dominate.
- The peaks are at critical values. For they appear at , for at , and for the cubic at . Between two critical values there are more preimages than outside them, and the density’s height jumps.
- The simulation validates the sum, not its individual terms. The simulated points match the outline of the sum, but each color separately is not observable: seeing does not tell you which branch it came from.
Several dimensions: the Jacobian as a volume-change factor
In the derivative of is a matrix. The Jacobian matrix (calculus lesson) of at is , the best linear approximation of near . Its determinant has a geometric interpretation: the linear map multiplies volumes by (the determinant is the signed volume of the image of the unit cube). Thus takes a tiny cube with side and volume to a set of volume with the same mass. The density is divided by that factor, just as in one dimension.
Proof
This is the one-dimensional proof using the change-of-variables theorem for multiple integrals. For Borel ,
and uniqueness of the density finishes the proof. The second form follows from the chain rule applied to : , hence .
∎The two forms serve different purposes. If you know the inverse in closed form, use and multiply. If you know and have at hand, divide by : there is no need to invert a matrix, only evaluate a determinant.
A practical consequence is the auxiliary-variable trick. If you only want the law of a function taking values in fewer dimensions, there is no square Jacobian to use. Extend to a diffeomorphism by adding convenient auxiliary variables, apply the theorem, and integrate out the auxiliaries (Fubini–Tonelli). That is exactly what convolution, the ratio of normals and the gamma–beta relationship do below.
The third figure lets you push a Gaussian through a chain of invertible layers and see how mass is distributed. Each grid cell in the base space keeps its mass, and its density is that mass divided by its area, which changes from layer to layer.
What you should have seen:
- Each cell’s mass stays the same; its area changes. The “cell mass” readings show that the sum of density times area remains (the Gaussian mass inside the square ) after any chain: the theorem is a conservation law.
- Log-determinants add. The bars are each layer’s contributions at the probe and the line is their cumulative sum; the ellipse-to-circle area ratio is (with a small error only because the circle is not infinitesimal).
- An affine layer is boring on purpose. Its Jacobian is constant, in the figure, and all cells change area together. A flow’s power lies in nonlinear layers whose Jacobian depends on the point.
- Density and volume compensate for each other. Where the log-determinant color indicates “contraction”, the corresponding density rises, and vice versa.
Composition: log-determinants add
A flow is a composition of layers, each a simple diffeomorphism. Write and , so . The previous theorem applies to as a whole, but requires , which the chain rule reduces to the layers.
Proof
The chain rule gives . The determinant is multiplicative, so and taking logarithms converts the product into a sum. Substitute into .
∎This formula is all that is needed to train a flow (Papamakarios et al., 2021): evaluate on the data, sum and maximize. To evaluate density, traverse the chain backwards (, hence “normalizing”); to sample, go forwards. A good layer therefore has a cheap inverse and a cheap . A general determinant costs , and in dimension that is prohibitive for every layer, data point and training step, so architectures are designed to make it trivial.
- Diagonal or triangular. If is triangular, is the product of its diagonal and costs . Autoregressive flows work this way: output depends only on inputs .
- Orthogonal. : rotations and permutations contribute nothing to the log-determinant.
- Rank-one update. The planar layer has , and the matrix determinant lemma gives : a scalar instead of a determinant. With it is invertible if (Rezende and Mohamed, 2015), and is the one shown in the previous figure.
- Coupling layers. Those used by RealNVP (Dinh et al., 2017) split the vector into two halves and apply
The Jacobian is block triangular,
The block is a complicated dense matrix (it depends on the derivatives of networks and ), but does not enter the determinant. And the inverse is : there is no need to invert the networks, only evaluate them. That is why and can be arbitrary multilayer perceptrons.
Sums of independent variables: convolution
Let and be independent with densities and . What is the density of ? This is a change of variables with the auxiliary-variable trick: complete to the linear diffeomorphism , with matrix and determinant one.
Proof
By independence, has joint density (independence lesson). The transformation has inverse with determinant , so the pair has density . The marginal of is obtained by integrating over , justified by Fubini–Tonelli because the integrand is nonnegative. The discrete case uses the same argument with sums.
∎Read the formula as an animation: reflect (), slide it to position and calculate the area of the pointwise product. Convolution is commutative and associative, the mean and variance of the sum are the sums of the means and variances (expectation by linearity, variance by independence), and the support of the sum is the sum of the supports.
Convolution smooths: the density of the sum is at least as regular as the more regular of the two. The sum of two uniform variables is a continuous triangle, even though each has jumps, and the sum of three is already a piecewise parabola with a continuous derivative. The next figure shows this progression of shapes, anticipating the central limit theorem.
What you should have seen:
- The product’s area is the height of the curve below. It is the formula, nothing more: the point sliding in the lower panel is at the height of that area.
- A sum of variables with different tails inherits the worst of each. An exponential plus anything has infinite support on the right and an exponential tail.
- Repeating moves the shape toward the bell. The more symmetric the starting law, the sooner it arrives: the uniform is already within a few hundredths with , while the exponential, with skewness and excess kurtosis , reduces them to and .
Polar coordinates and Box–Muller
Polar coordinates are a diffeomorphism from onto the plane without a half-axis, with Jacobian
That factor is the area of the polar element , and with it we can finally evaluate the Gaussian normalizing integral:
hence (Fubini–Tonelli in the first equality). But there is more: the same calculation gives the laws of and when . Their density in is the planar density multiplied by the Jacobian,
which factorizes: and are independent, is uniform on and has tail . Invert that tail using the inverse transform: is uniform on (because ). Reversing the reasoning produces normals from uniforms.
Proof
This is a composition of two changes of variables; follow the mass of a tiny square. First from to . Its inverse is , , with diagonal Jacobian of determinant , so . Next , with determinant , which divides the density: . This is , the product of two standard normals.
∎The result has a particular beauty: the factor in the second step exactly compensates in the first. The area of a tiny square is multiplied overall by and its density by the inverse, so density times area does not change. Check it.
What you should have seen:
- Each level set of is a circle. The three verticals in the first panel (the values for ) become straight lines in the second and circles in the third; the rays play the role of the horizontal lines.
- Areas grow, mass does not. The measured area ratio and agree, with a small error that increases with the size of the square; the third reading (density area) is the same in all three panels.
- The center of the plane is nearly empty of uniform points. Few points have close to (radii near zero), but those few spread over a tiny circle of area : that is why the density at the origin, , is highest.
In practice, Box–Muller is not the most commonly used method today. Marsaglia’s polar variant avoids sines and cosines by accepting only points in a disk, and numpy.random.Generator.standard_normal uses the much faster ziggurat algorithm. Box–Muller remains the canonical example because its correctness is proved with a Jacobian, and because its structure is the pattern of “moving to coordinates where the law factorizes”.
Ratios and products: Cauchy, beta, Student’s
The same pattern (complete with an auxiliary variable, apply the Jacobian, integrate out the auxiliary) solves the other derived laws in the catalogue.
The gamma–beta relationship is the most fruitful example, which you prove in the first exercise: if and are independent, then , , and . The surprising part is independence. It gives two constantly used facts: a sum of independent gammas with the same scale is gamma (a convolution solved without integrating), and a Dirichlet vector is sampled by normalizing independent gammas.
Using the same technique, if and are independent, has Student’s density,
Obtain it by completing with and using Jacobian ; the integral over is another gamma. With this is the earlier Cauchy, and as it tends to the normal.
Order statistics
Given a sample , its order statistics are its sorted values . is the minimum, the maximum, and the -th smallest. They are not independent (they are ordered by construction), but their marginal law can be obtained without a double integral, by a counting argument.
The maximum is the simplest case: happens if and only if all are , and by independence
The minimum of exponentials of rate satisfies : it is a . For the -th statistic, the key is an equivalence of events: the -th smallest is if and only if at least of the variables are . And the number of variables falling to the left of is a sum of independent indicators with probability :
Proof
The distribution formula is what we just argued. To differentiate it with respect to , use and :
Summing over , the second term for each cancels the first for , leaving only the first with (the second with has ): . Multiply by (chain rule) and .
∎It suffices to understand the uniform case. If is continuous, is uniform (probability integral transform) and, since is increasing, : all order statistics of a continuous law are an increasing transformation of those of uniforms. And with the density is . Since , it is exactly the density . Its mean is : the uniforms divide into gaps that are equal on average.
The same event equivalence, applied to uniforms, gives an identity from analysis without integrating anything.
Proof
Let . The number of them falling in is , and . Therefore , and by the previous theorem.
∎The final figure brings all three together: the ordered sample, the histogram of the -th statistic, and the two probabilities in the identity.
What you should have seen:
- The minimum approaches and the maximum as grows. Their means are and , and their densities are and .
- The median concentrates. With the beta narrows around , with standard deviation of order : that is why the sample median is a good estimator.
- The two probabilities do not merely look alike; they are the same. One uses only a finite sum; the other, an integral. This identity makes
scipy.stats.binom.sfandscipy.stats.beta.cdfreturn the same value.
Implementation from scratch
The cells check the results you have just proved. The first compares the change-of-variables formula against a simulation, including the non-injective case and the mistake of forgetting a branch.
import numpy as np
from scipy import stats
rng = np.random.default_rng(0)
x = rng.standard_normal(400_000)
def hist_density(y, edges):
counts, _ = np.histogram(y, bins=edges)
return counts / (len(y) * np.diff(edges))
# 1) Y = exp(X): g inyectiva, p_Y(y) = p_X(log y) / y
edges = np.linspace(0.1, 6, 40)
mid = 0.5 * (edges[1:] + edges[:-1])
p_formula = stats.norm.pdf(np.log(mid)) / mid
p_sim = hist_density(np.exp(x), edges)
print("exp(X): máx |simulación - fórmula| =", np.abs(p_sim - p_formula).max().round(4))
print(" máx |scipy.lognorm - fórmula| =", np.abs(stats.lognorm.pdf(mid, 1) - p_formula).max())
# 2) Y = X²: no inyectiva, se suman las dos preimágenes ±√y
edges = np.linspace(0.3, 6, 40)
mid = 0.5 * (edges[1:] + edges[:-1])
root = np.sqrt(mid)
p_formula = (stats.norm.pdf(root) + stats.norm.pdf(-root)) / (2 * root)
p_sim = hist_density(x**2, edges)
print("X²: máx |simulación - fórmula| =", np.abs(p_sim - p_formula).max().round(4))
print(" máx |chi2(1) de scipy - fórmula| =", np.abs(stats.chi2.pdf(mid, 1) - p_formula).max())
# 3) si se olvida la segunda preimagen, falta exactamente la mitad de la masa
p_una = stats.norm.pdf(root) / (2 * root)
print("una sola preimagen: cociente con la simulación =", (p_una / p_sim).mean().round(3))Differences from the simulation are of order or (histogram noise, not an error in the theorem), and differences from SciPy are rounding: the lognormal and are the formula. With only one preimage the ratio is , as theory says.
The second cell is the main laboratory: a normalizing flow in NumPy using the layers in this lesson, with their analytic log-determinants checked against the Jacobian’s numerical determinant. Each layer implements forward, inverse and log_abs_det_jacobian evaluated at its input. The planar layer is the one in the grid figure; its inverse has no closed form, but since is parallel to , it suffices to solve a scalar increasing equation for , using bisection. Class Flow sums log-determinants while traversing the chain backwards, and log_prob is the previous section’s formula.
import numpy as np
import matplotlib.pyplot as plt
LOG2PI = np.log(2 * np.pi)
class Affine:
"""x = z·exp(a) + b por componentes. El jacobiano es diagonal: log|det| = Σ a_i."""
def __init__(self, a, b):
self.a, self.b = np.asarray(a, float), np.asarray(b, float)
def forward(self, z): return z * np.exp(self.a) + self.b
def inverse(self, x): return (x - self.b) * np.exp(-self.a)
def log_abs_det_jacobian(self, z): return np.full(len(z), self.a.sum())
class Sinh:
"""x = sinh(z) por componentes: no lineal, con inversa arcsinh. log|det| = Σ log cosh(z_i)."""
def forward(self, z): return np.sinh(z)
def inverse(self, x): return np.arcsinh(x)
def log_abs_det_jacobian(self, z): return np.log(np.cosh(z)).sum(axis=1)
class Rotation:
"""Giro de ángulo θ: ortogonal, así que |det| = 1 y la inversa es la traspuesta."""
def __init__(self, theta):
c, s = np.cos(theta), np.sin(theta)
self.R = np.array([[c, -s], [s, c]])
def forward(self, z): return z @ self.R.T
def inverse(self, x): return x @ self.R
def log_abs_det_jacobian(self, z): return np.zeros(len(z))
class Planar:
"""x = z + u·tanh(wᵀz + b) (Rezende y Mohamed): J = I + h'·u wᵀ, así que det J = 1 + h'(wᵀz + b)·wᵀu.
Invertible si wᵀu > −1. La inversa no es explícita, pero se reduce a una ecuación escalar monótona."""
def __init__(self, w, u, b):
self.w, self.u, self.b = np.asarray(w, float), np.asarray(u, float), float(b)
self.wu = float(self.w @ self.u)
assert self.wu > -1, "con wᵀu ≤ −1 la capa deja de ser invertible"
def forward(self, z): return z + np.outer(np.tanh(z @ self.w + self.b), self.u)
def inverse(self, x):
# α = wᵀz + b cumple wᵀx + b = α + wᵀu·tanh(α), creciente en α: bisección en [c − |wᵀu|, c + |wᵀu|]
c = x @ self.w + self.b
lo, hi = c - abs(self.wu) - 1e-9, c + abs(self.wu) + 1e-9
for _ in range(60):
mid = 0.5 * (lo + hi)
below = mid + self.wu * np.tanh(mid) < c
lo, hi = np.where(below, mid, lo), np.where(below, hi, mid)
return x - np.outer(np.tanh(0.5 * (lo + hi)), self.u)
def log_abs_det_jacobian(self, z):
return np.log(np.abs(1 + (1 - np.tanh(z @ self.w + self.b) ** 2) * self.wu))
class Coupling:
"""Acoplamiento afín (RealNVP) en R²: la coordenada `cond` pasa intacta y decide la afín de la otra.
Jacobiano triangular: log|det| = s(z_cond). La red que da s y t NUNCA se invierte."""
def __init__(self, W1, W2, cond):
self.W1, self.W2, self.cond, self.oth = W1, W2, cond, 1 - cond
def _st(self, c):
out = np.tanh(c @ self.W1) @ self.W2 # (n, 2)
return np.tanh(out[:, :1]), out[:, 1:] # s acotada en (-1, 1), t libre
def forward(self, z):
x = z.copy()
s, t = self._st(z[:, [self.cond]])
x[:, [self.oth]] = z[:, [self.oth]] * np.exp(s) + t
return x
def inverse(self, x):
z = x.copy()
s, t = self._st(x[:, [self.cond]]) # la coordenada cond no cambió: se recalculan s y t
z[:, [self.oth]] = (x[:, [self.oth]] - t) * np.exp(-s)
return z
def log_abs_det_jacobian(self, z): return self._st(z[:, [self.cond]])[0][:, 0]
class Flow:
"""Base N(0, I) en R² seguida de una lista de capas, de z hacia x."""
def __init__(self, layers): self.layers = layers
def forward(self, z):
ld = np.zeros(len(z))
for layer in self.layers:
ld += layer.log_abs_det_jacobian(z) # el jacobiano se evalúa en la ENTRADA de la capa
z = layer.forward(z)
return z, ld
def inverse(self, x):
ld = np.zeros(len(x))
for layer in reversed(self.layers):
z = layer.inverse(x)
ld += layer.log_abs_det_jacobian(z)
x = z
return x, ld
def log_prob(self, x):
z, ld = self.inverse(x)
return -0.5 * (z**2).sum(axis=1) - LOG2PI - ld # log p_X = log p_Z(z) - Σ log|det J_k|
def sample(self, n, rng): return self.forward(rng.standard_normal((n, 2)))[0]
rng = np.random.default_rng(1)
flow = Flow([
Affine([-0.6, -0.6], [0.0, 0.0]),
Coupling(rng.normal(size=(1, 8)), rng.normal(size=(8, 2)), cond=0),
Sinh(),
Planar([1.2, -0.6], [0.7, 0.5], 0.3),
Rotation(0.6),
Coupling(rng.normal(size=(1, 8)), rng.normal(size=(8, 2)), cond=1),
Affine([0.2, -0.1], [0.5, -0.3]),
])
# 1) la inversa deshace a la directa
z = rng.standard_normal((1000, 2))
x, _ = flow.forward(z)
print("ida y vuelta: error máximo =", np.abs(flow.inverse(x)[0] - z).max())
# 2) el log-det analítico frente al determinante numérico del jacobiano (diferencias finitas centradas)
def numeric_logdet(f, z, eps=1e-6):
J = np.zeros((2, 2))
for j in range(2):
e = np.zeros((1, 2)); e[0, j] = eps
J[:, j] = (f(z + e) - f(z - e))[0] / (2 * eps)
return np.linalg.slogdet(J)[1]
errs = [abs(flow.forward(zi[None])[1][0] - numeric_logdet(lambda q: flow.forward(q)[0], zi[None])) for zi in z[:200]]
print("log|det J|: error máximo analítico frente a numérico =", max(errs))
# 3) la densidad integra 1 (suma de Riemann en una rejilla)
g = np.linspace(-10, 10, 321)
X, Y = np.meshgrid(g, g)
pts = np.column_stack([X.ravel(), Y.ravel()])
dens = np.exp(flow.log_prob(pts)).reshape(X.shape)
h = g[1] - g[0]
print("∫ p_X dx ≈", round(dens.sum() * h * h, 4), "(el resto está en las colas, fuera de la rejilla)")
# 4) log_prob en la dirección inversa frente a la directa, calculada con los z originales
x, ld = flow.forward(z)
print("log_prob(x) frente a la dirección directa: error máximo =", np.abs(flow.log_prob(x) - (-0.5 * (z**2).sum(1) - LOG2PI - ld)).max())
fig, ax = plt.subplots(1, 2, figsize=(9, 3.6))
ax[0].contourf(X, Y, dens, 14, cmap="Blues")
ax[0].set_title("densidad exacta $p_X$ (cambio de variables)")
xs = flow.sample(3000, rng)
ax[1].scatter(xs[:, 0], xs[:, 1], s=2, alpha=0.4)
ax[1].set_title("3000 muestras $x = f(z)$")
for a in ax:
a.set_xlim(-5, 5); a.set_ylim(-5, 5); a.set_aspect("equal")
plt.tight_layout()What matters about the cell is what it does not do: it computes no matrix determinant except in the numerical check. The four checks close the theorem’s loop. The round trip, analytical versus numerical log-det, and normalization to (less the tail outside the grid) are precisely what the hypotheses guarantee: bijectivity, differentiability and the Jacobian formula at each layer’s input. And the samples flow.sample (forward direction) and exact density flow.log_prob (inverse direction) describe the same law, making the model useful. Training this flow by maximizing is left for the generative-models module (normalizing flows, coupling layers).
The third cell implements Box–Muller and its polar variant and checks the properties asserted by the theorem: normality, independence (the correlation of squares, the test that truly distinguishes “uncorrelated” from “independent”), the law of and Marsaglia’s acceptance rate .
import numpy as np
from scipy import stats
rng = np.random.default_rng(7)
def box_muller(n, rng):
u1 = 1.0 - rng.random(n) # en (0, 1]: así log(u1) nunca es log(0)
u2 = rng.random(n)
r = np.sqrt(-2.0 * np.log(u1))
t = 2.0 * np.pi * u2
return np.stack([r * np.cos(t), r * np.sin(t)], axis=1)
z = box_muller(200_000, rng)
print("medias:", z.mean(axis=0).round(3), " covarianza:\n", np.cov(z.T).round(3))
print("KS de cada columna frente a N(0,1): p-valores", [round(float(stats.kstest(z[:, j], "norm").pvalue), 3) for j in range(2)])
print("KS de R² frente a chi2(2): p-valor ", round(float(stats.kstest((z**2).sum(axis=1), "chi2", args=(2,)).pvalue), 3))
print("corr(Z1², Z2²) =", np.corrcoef(z[:, 0]**2, z[:, 1]**2)[0, 1].round(4), "(0 si son independientes; con Z2 = |Z1| saldría 1)")
def marsaglia(n, rng):
"""Versión polar: sin senos ni cosenos, a cambio de rechazar los puntos fuera del disco unidad."""
out, tried, kept = [], 0, 0
while kept < n:
v = rng.uniform(-1, 1, size=(n, 2))
s = (v**2).sum(axis=1)
ok = (s > 0) & (s < 1)
out.append(v[ok] * np.sqrt(-2.0 * np.log(s[ok]) / s[ok])[:, None])
tried += n
kept += int(ok.sum())
return np.concatenate(out)[:n], kept / tried
w, acc = marsaglia(100_000, rng)
print("Marsaglia: aceptación =", round(acc, 3), " frente a π/4 =", round(np.pi / 4, 3), "; KS p =", round(float(stats.kstest(w[:, 0], "norm").pvalue), 3))The -values should not be small (with a fixed seed they are reproducible), and correlation between and is zero up to noise of order . Marsaglia’s variant does the same without trigonometry: if is uniform in the unit disk and , then is uniform on and the angle is uniform and independent, so has the Box–Muller law without evaluating sines or cosines; the acceptance rate is the ratio of disk to square areas.
The fourth cell checks convolution and compares with closed-form formulas. Discrete convolution is np.convolve, which is ; on a very fine grid scipy.signal.fftconvolve is preferable, using the FFT.
import numpy as np
from scipy import stats
h = 0.002
t = np.arange(0, 14, h)
# Exp(1) + Exp(2): la convolución numérica frente a la fórmula cerrada 2(e^-t - e^-2t)
fx, fy = np.exp(-t), 2 * np.exp(-2 * t)
conv = np.convolve(fx, fy)[: len(t)] * h
exact = 2 * (np.exp(-t) - np.exp(-2 * t))
print("Exp(1)+Exp(2): máx |convolución - exacta| =", np.abs(conv - exact).max().round(5), " p(1) =", conv[int(1 / h)].round(4), " exacta =", exact[int(1 / h)].round(4))
# suma de uniformes (Irwin-Hall): tres convoluciones de la densidad de U(0,1)
tt = np.arange(0, 3, h)
u = (tt < 1).astype(float)
s2 = np.convolve(u, u)[: len(tt)] * h
s3 = np.convolve(s2, u)[: len(tt)] * h
def ih3_exact(x): # x²/2 en [0,1]; (-2x²+6x-3)/2 en [1,2]; (3-x)²/2 en [2,3]
return np.where(x < 1, x**2 / 2, np.where(x < 2, (-2 * x**2 + 6 * x - 3) / 2, (3 - x) ** 2 / 2))
print("U+U+U: máx |convolución - Irwin-Hall| =", np.abs(s3 - ih3_exact(tt)).max().round(4))
print(" máx |U+U+U - N(1.5, 1/4)| =", np.abs(s3 - stats.norm.pdf(tt, 1.5, 0.5)).max().round(4), f" (el pico vale {s3.max():.3f} frente a {stats.norm.pdf(0, 0, 0.5):.3f}: con tres sumandos ya parece una campana)")
# pmf: la suma de Poisson independientes es Poisson, por convolución de las funciones de masa
k = np.arange(0, 60)
pm = np.convolve(stats.poisson.pmf(k, 2.0), stats.poisson.pmf(k, 3.0))[: len(k)]
print("Poisson(2)+Poisson(3): máx |pmf convolucionada - Poisson(5)| =", np.abs(pm - stats.poisson.pmf(k, 5.0)).max())
# la suma de variables DEPENDIENTES no se obtiene convolucionando: X + X no es X + X' con X' independiente
x = np.random.default_rng(0).uniform(0, 1, 200_000)
print("Var(X + X) =", np.var(x + x).round(4), " (4 Var X = 1/3); Var(X + X') =", np.var(x + np.random.default_rng(1).uniform(0, 1, 200_000)).round(4), " (2 Var X = 1/6)")The error in the first comparison comes from the Riemann rule itself (order ), not the theorem; halving halves it. For pmfs, by contrast, convolution is exact: sums are finite, and the error is rounding.
The fifth cell checks order statistics: the binomial–beta identity using SciPy, the beta law of the -th statistic, the expected maximum, and the Gumbel-max trick.
import numpy as np
from scipy import stats
rng = np.random.default_rng(3)
n, k, p = 10, 4, 0.3
# la identidad: P(Bin(n, p) >= k) = P(Beta(k, n-k+1) <= p)
print("P(Bin(10, 0.3) >= 4) =", stats.binom.sf(k - 1, n, p))
print("P(Beta(4, 7) <= 0.3) =", stats.beta.cdf(p, k, n - k + 1))
# el k-ésimo menor de n uniformes simulado
u = np.sort(rng.random((200_000, n)), axis=1)
kth = u[:, k - 1]
print("E[X_(4)] = k/(n+1) =", round(k / (n + 1), 4), " simulado:", kth.mean().round(4), "; KS frente a Beta(4, 7): p =", round(float(stats.kstest(kth, "beta", args=(k, n - k + 1)).pvalue), 3))
print("E[máximo de 10 uniformes] = n/(n+1) =", round(n / (n + 1), 4), " simulado:", u[:, -1].mean().round(4))
print("P(mínimo > 0.1) = 0.9^10 =", round(0.9**10, 4), " simulado:", (u[:, 0] > 0.1).mean().round(4))
# cualquier ley continua: X_(k) = F^{-1}(U_(k)). Máximo de 5 exponenciales: F_max(x) = (1 - e^-x)^5
m = rng.exponential(size=(200_000, 5)).max(axis=1)
x0 = 2.0
print("P(máx de 5 Exp(1) <= 2) =", round((1 - np.exp(-x0)) ** 5, 4), " simulado:", (m <= x0).mean().round(4))
# truco de Gumbel-max: argmax(logits + G) con G = -log(-log U) muestrea de softmax(logits)
logits = np.log([0.5, 0.3, 0.15, 0.05])
g = -np.log(-np.log(rng.random((400_000, 4))))
freq = np.bincount(np.argmax(logits + g, axis=1), minlength=4) / 400_000
print("frecuencias Gumbel-max:", freq.round(3), " frente a softmax:", np.exp(logits).round(3))The first two lines agree to the last decimal, as the theorem says (this is not an approximation). The rest check the section’s formulas: the -th statistic is beta, the mean of the maximum is , and the maximum of nonuniform variables is obtained from .
Using libraries
The affine relationship in the multivariate section, using SciPy. The cell computes of in two ways and shows why slogdet is used: the determinant of an upper triangular matrix with factors on the diagonal overflows.
import numpy as np
from scipy.stats import multivariate_normal as mvn
rng = np.random.default_rng(0)
# Y = A X + b con X ~ N(0, I): log p_Y(y) = log p_X(A^-1 (y - b)) - log|det A|
d = 3
A = rng.normal(size=(d, d)) + 2 * np.eye(d)
b = rng.normal(size=d)
y = rng.normal(size=d)
x = np.linalg.solve(A, y - b) # A^-1 (y - b), sin formar la inversa
sign, logabsdet = np.linalg.slogdet(A)
lp_formula = mvn(np.zeros(d)).logpdf(x) - logabsdet
lp_scipy = mvn(mean=b, cov=A @ A.T).logpdf(y) # la ley N(b, A Aᵀ) que scipy conoce
print("log p_Y(y) por cambio de variables:", round(lp_formula, 8))
print("log p_Y(y) con N(b, A Aᵀ) de scipy:", round(lp_scipy, 8))
# el determinante desborda en dimensión alta; slogdet no
n = 500
M = 5 * np.eye(n) + 0.05 * np.triu(rng.normal(size=(n, n)), 1)
sign, ld = np.linalg.slogdet(M)
with np.errstate(over="ignore"):
det = np.linalg.det(M)
print(f"n = {n}: det(M) = {det} slogdet = ({sign:+.0f}, {ld:.3f}) (n log 5 = {n * np.log(5):.3f})")The first two lines match because they are the same formula, one with the explicit Jacobian and the other with covariance . In the third, det gives inf, while slogdet returns the correct logarithm, (a triangular determinant is the product of its diagonal).
PyTorch provides the pieces of a flow in torch.distributions: TransformedDistribution applies a list of Transform to a base distribution and computes log_prob exactly as in the composition theorem. This cell, which runs on CPU with minimal sizes, reproduces a lognormal and a logit-normal with PyTorch transformations and checks log_prob against the hand formula and the log-determinant against the autograd Jacobian.
import torch
from torch.distributions import Independent, Normal, TransformedDistribution, AffineTransform, ExpTransform, SigmoidTransform
torch.manual_seed(0)
loc, scale = torch.tensor([0.5, -0.5]), torch.tensor([1.5, 0.7])
base = Independent(Normal(torch.zeros(2), torch.ones(2)), 1) # N(0, I) en R², un evento = un vector
# dos cadenas: z -> exp(scale·z + loc) (lognormal multivariante) y z -> sigmoide(scale·z + loc) (logit-normal)
lognormal = TransformedDistribution(base, [AffineTransform(loc, scale), ExpTransform()])
logitnormal = TransformedDistribution(base, [AffineTransform(loc, scale), SigmoidTransform()])
x = lognormal.sample((4,))
z = (torch.log(x) - loc) / scale # la inversa, a mano
manual = base.log_prob(z) - torch.log(scale).sum() - torch.log(x).sum(dim=-1) # log p_Z(z) - Σ log|det J_k|
print("lognormal: log_prob de torch frente a la fórmula a mano, máx |dif| =", (lognormal.log_prob(x) - manual).abs().max().item())
# el log-det de torch frente al determinante del jacobiano calculado por autograd
affine, sig = logitnormal.transforms
y = logitnormal.sample((3,))
for yi in y:
zi = affine.inv(torch.logit(yi))
J = torch.autograd.functional.jacobian(lambda q: torch.sigmoid(q * scale + loc), zi)
ld_auto = torch.linalg.slogdet(J)[1]
w = zi * scale + loc
ld_torch = affine.log_abs_det_jacobian(zi, w).sum() + sig.log_abs_det_jacobian(w, yi).sum()
print(f"logit-normal: log|det J| autograd = {ld_auto.item():+.6f} transformaciones de torch = {ld_torch.item():+.6f}")npm run lab and open the connection link.The difference in float32 is , the accuracy of single precision. Each PyTorch Transform implements exactly the contract of our layers: forward, inverse (_inverse) and log_abs_det_jacobian.
Common mistakes
Exercises
Step 1 of 5. What is the joint density of and where should you start?
Step 1 of 4. is not injective on . How do you proceed?
More than one answer may be correct.
flow_log_prob(layers, x, base_logpdf). layers is a list of layers in the order , each with methods forward(z), inverse(x) and log_abs_det_jacobian(z), which returns an array of shape (n,) with evaluated at the layer's input $\vb{z}$ (arrays of shape (n, d)). x is an array (n, d) and base_logpdf(z) returns (n,) with . The function must return . Tests compare it with the analytical density of an affine transformation, a lognormal and the numerical Jacobian determinant of a chain.import numpy as np
def flow_log_prob(layers, x, base_logpdf):
# recorre las capas al revés: z = capa.inverse(x), acumula log|det J| en la entrada de la capa
passSummary
- One dimension: for and monotone. Density dilutes where stretches and accumulates where it compresses. For non-injective , sum contributions over all preimages; integrable singularities appear at critical values.
- Several dimensions: with . The determinant is the local volume-change factor; in the affine case, .
- Composition: , evaluating each determinant at its layer’s input. Use structures with cheap determinants (triangular, rank one, coupling) and
slogdetinstead ofdet. - Sums of independents: the density of is convolution (Jacobian and marginalization); means and variances add, and repeated convolution approaches the bell.
- Polar coordinates and Box–Muller: with Jacobian , the two variables and are independent normals. The ratio of normals is Cauchy, and the gamma–beta relationship gives beta, Dirichlet and .
- Order statistics: ; for uniforms, , giving .