TExcelTAD
Home › Math for Machine Learning › Change of Variables

Change of Variables

If XX has a known density and Y=g(X)Y = g(X), what is the density of YY? Simply plugging in is wrong: a transformation stretches some regions and squeezes others, and the density must compensate so that probabilities still add to 1. The correction factor is the derivative (in many dimensions, the Jacobian determinant). This formula drives sampling algorithms and normalizing flows.

One dimension

For an invertible, differentiable gg with Y=g(X)Y = g(X):

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

Intuition: probability mass in a small interval is conserved, pY(y) ∣dy∣=pX(x) ∣dx∣p_Y(y)\,\lvert dy \rvert = p_X(x)\,\lvert dx \rvert. Where gg stretches the line, the density of YY gets thinner.

Example. X∼Uniform⁡(0,1)X \sim \operatorname{Uniform}(0, 1) and Y=X2Y = X^2. Then g−1(y)=yg^{-1}(y) = \sqrt{y} and ddyy=12y\frac{d}{dy}\sqrt{y} = \frac{1}{2\sqrt{y}}, so pY(y)=12yp_Y(y) = \frac{1}{2\sqrt{y}} on (0,1)(0, 1): squares of uniform numbers pile up near 0.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
y = rng.uniform(size=1_000_000) ** 2
edges = np.array([0.0, 0.01, 0.1, 0.25, 0.5, 1.0])
counts, _ = np.histogram(y, bins=edges)
for lo, hi, c in zip(edges[:-1], edges[1:], counts):
    exact = np.sqrt(hi) - np.sqrt(lo)          # integral of 1/(2 sqrt y) from lo to hi
    print(f"P({lo} < Y < {hi}): simulated {c / len(y):.4f}, formula {exact:.4f}")
P(0.0 < Y < 0.01): simulated 0.1002, formula 0.1000
P(0.01 < Y < 0.1): simulated 0.2158, formula 0.2162
P(0.1 < Y < 0.25): simulated 0.1842, formula 0.1838
P(0.25 < Y < 0.5): simulated 0.2065, formula 0.2071
P(0.5 < Y < 1.0): simulated 0.2933, formula 0.2929

Many dimensions

For an invertible, differentiable g:RD→RD\mathbf{g}: \mathbb{R}^D \to \mathbb{R}^D with y=g(x)\mathbf{y} = \mathbf{g}(\mathbf{x}):

pY(y)=pX(x) ∣det⁡∂g∂x∣−1,x=g−1(y)p_Y(\mathbf{y}) = p_X(\mathbf{x})\,\left\lvert \det\frac{\partial \mathbf{g}}{\partial \mathbf{x}} \right\rvert^{-1}, \qquad \mathbf{x} = \mathbf{g}^{-1}(\mathbf{y})

The Jacobian determinant measures how much g\mathbf{g} scales a tiny volume (Determinant and Trace). For a linear map y=Ax+b\mathbf{y} = A\mathbf{x} + \mathbf{b} the Jacobian is AA everywhere, and applying the formula to a standard normal x\mathbf{x} gives exactly the Gaussian N(b,AAT)\mathcal{N}(\mathbf{b}, AA^T).

python · try it yourself
import numpy as np

def std_normal_logpdf(x): return -0.5 * len(x) * np.log(2 * np.pi) - 0.5 * x @ x
A = np.array([[2.0, 0.0], [1.0, 0.5]]); b = np.array([1.0, -1.0])
y = np.array([2.0, 0.3])
x = np.linalg.solve(A, y - b)
via_flow = std_normal_logpdf(x) - np.log(abs(np.linalg.det(A)))
S = A @ A.T
via_gauss = -np.log(2 * np.pi) - 0.5 * np.linalg.slogdet(S)[1] - 0.5 * (y - b) @ np.linalg.solve(S, y - b)
print("change of variables:", round(via_flow, 6), "  Gaussian N(b, A A^T):", round(via_gauss, 6))
change of variables: -3.242877   Gaussian N(b, A A^T): -3.242877

Normalizing flows

A normalizing flow is a generative model that pushes a simple base density (a standard normal) through a learned invertible network g\mathbf{g}. Training maximizes the log-likelihood, which the change-of-variables formula gives exactly:

log⁡p(y)=log⁡pbase(g−1(y))−log⁡∣det⁡Jg∣\log p(\mathbf{y}) = \log p_{\text{base}}\big(\mathbf{g}^{-1}(\mathbf{y})\big) - \log\left\lvert \det J_{\mathbf{g}} \right\rvert

Flows use layers whose Jacobians are triangular, so the determinant is the product of the diagonal and costs O(D)O(D) instead of O(D3)O(D^3).

In software

  • Inverse transform sampling (Discrete and Continuous Distributions) is the 1D change of variables run backwards.
  • Log-normal, softplus-transformed and "bijector" distributions in TensorFlow Probability and torch.distributions.TransformedDistribution apply this formula.
  • When a model predicts log⁡y\log y instead of yy, densities and likelihoods must include the Jacobian 1/y1/y to be comparable.

Exercises

Exercise 1: A linear map in 1D

X∼N(0,1)X \sim \mathcal{N}(0, 1) and Y=3X+2Y = 3X + 2. Use the formula to find pYp_Y.

Answer

N(2,9)\mathcal{N}(2, 9).

Solution

g−1(y)=(y−2)/3g^{-1}(y) = (y - 2)/3 with derivative 13\frac{1}{3}:

pY(y)=12πe−(y−2)218⋅13=12π⋅9e−(y−2)22⋅9p_Y(y) = \frac{1}{\sqrt{2\pi}}e^{-\frac{(y-2)^2}{18}} \cdot \frac{1}{3} = \frac{1}{\sqrt{2\pi \cdot 9}}e^{-\frac{(y-2)^2}{2 \cdot 9}}

Exercise 2: Exponential from uniform

U∼Uniform⁡(0,1)U \sim \operatorname{Uniform}(0, 1) and Y=−log⁡UY = -\log U. Find pYp_Y.

Answer

pY(y)=e−yp_Y(y) = e^{-y} for y>0y > 0.

Solution

g−1(y)=e−yg^{-1}(y) = e^{-y}, derivative −e−y-e^{-y}, absolute value e−ye^{-y}, and pU=1p_U = 1 on (0,1)(0, 1). So YY is exponential with rate 1.

Exercise 3: Volume factor (code)

What is ∣det⁡J∣\lvert\det J\rvert for the polar-to-Cartesian map (r,θ)↦(rcos⁡θ,rsin⁡θ)(r, \theta) \mapsto (r\cos\theta, r\sin\theta) at r=2r = 2, θ=0.3\theta = 0.3? Compare with rr.

Answer

2, which equals rr.

Solution

J=[cos⁡θ−rsin⁡θsin⁡θrcos⁡θ]J = \begin{bmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{bmatrix}, det⁡J=r(cos⁡2θ+sin⁡2θ)=r\det J = r(\cos^2\theta + \sin^2\theta) = r: the familiar r dr dθr\,dr\,d\theta.

python · try it yourself
import numpy as np
r, t = 2.0, 0.3
J = np.array([[np.cos(t), -r * np.sin(t)], [np.sin(t), r * np.cos(t)]])
print(round(abs(np.linalg.det(J)), 10))
2.0

Test yourself

Why can't we just write pY(y)=pX(g−1(y))p_Y(y) = p_X(g^{-1}(y))?

  1. Because gg is not linear
  2. Because the transformation stretches or squeezes space, and the density must be corrected so it still integrates to 1
  3. Because YY is discrete
  4. We can; it is correct

Normalizing flows prefer layers with triangular Jacobians because…

  1. triangular matrices are invertible by definition
  2. their determinant is the product of the diagonal, cheap to compute
  3. they have no parameters
  4. they are orthogonal

If XX is uniform on (0,1)(0, 1), then Y=X2Y = X^2 has more probability…

  1. near 1
  2. near 0
  3. spread evenly
  4. at exactly 0.5