TExcelTAD
Home › Calculus in Depth › Probability Densities in AI

Probability Densities in AI

Generative models, variational autoencoders, diffusion models and the loss functions of classifiers are all statements about probability densities, and a density is just a non-negative function whose integral is 1. This lesson uses integrals to normalise densities, compute expectations, transform densities under a change of variables, measure the gap between two distributions with the KL divergence, and push gradients through random sampling with the reparameterisation trick.

Background: Probability, Improper Integrals and Double Integrals in Polar Coordinates (the Gaussian integral). Related courses: Statistics, Probability Theory and Information Theory.

Densities, normalisation and expectation

A probability density on R\mathbb{R} is a function p(x)≥0p(x) \ge 0 with ∫p(x) dx=1\int p(x)\,dx = 1; the probability of an interval is P(a≤X≤b)=∫abp(x) dxP(a \le X \le b) = \int_a^b p(x)\,dx. Expectations are integrals weighted by pp:

Quantity Integral
normalising constant of an unnormalised ff Z=∫f(x) dxZ = \int f(x)\,dx, then p=f/Zp = f/Z
mean E[X]=∫x⋅p(x) dx\mathbb{E}[X] = \int x \cdot p(x)\,dx
expectation of g(X)g(X) E[g(X)]=∫g(x)⋅p(x) dx\mathbb{E}[g(X)] = \int g(x) \cdot p(x)\,dx
variance Var⁡X=E[X2]−(E[X])2\operatorname{Var} X = \mathbb{E}[X^2] - (\mathbb{E}[X])^2
entropy H=−∫p(x)⋅ln⁡p(x) dxH = -\int p(x) \cdot \ln p(x)\,dx

The most important integral in ML is the Gaussian one, ∫e−x2/2 dx=2π\int e^{-x^2/2}\,dx = \sqrt{2\pi} over R\mathbb{R}, proved by squaring it and switching to polar coordinates. Computing ZZ is the hard part of many models: energy-based models and Boltzmann machines define p(x)=e−E(x)/Zp(x) = e^{-E(x)}/Z, and ZZ is an integral over a huge space.

python · try it yourself
import sympy as sp

x = sp.symbols('x', real=True)
print("Gaussian integral :", sp.integrate(sp.exp(-x**2 / 2), (x, -sp.oo, sp.oo)))

f = x**2 * sp.exp(-x)                       # unnormalised, on [0, oo)
Z = sp.integrate(f, (x, 0, sp.oo))
p = f / Z
mean = sp.integrate(x * p, (x, 0, sp.oo))
var = sp.integrate(x**2 * p, (x, 0, sp.oo)) - mean**2
print("Z =", Z, "  p(x) =", p, "  mean =", mean, "  variance =", var)
print("P(X < 2) =", sp.integrate(p, (x, 0, 2)), "≈", round(float(sp.integrate(p, (x, 0, 2))), 6))
Gaussian integral : sqrt(2)*sqrt(pi)
Z = 2   p(x) = x**2*exp(-x)/2   mean = 3   variance = 3
P(X < 2) = 1 - 5*exp(-2) ≈ 0.323324

Change of variables

If Y=g(X)Y = g(X) with gg increasing and differentiable, probability is conserved on matching intervals, so pY(y)⋅dy=pX(x)⋅dxp_Y(y) \cdot dy = p_X(x) \cdot dx and

pY(y)=pX(x)⋅∣dxdy∣,x=g−1(y)in n dimensions:pY(y)=pX(x)⋅∣det⁡Jg−1(y)∣\begin{aligned} &p_Y(y) = p_X(x) \cdot \left\lvert \frac{dx}{dy} \right\rvert, \qquad x = g^{-1}(y) \\ &\text{in } n \text{ dimensions:} \quad p_Y(y) = p_X(x) \cdot \lvert \det J_{g^{-1}}(y) \rvert \end{aligned}

This is the substitution rule from single-variable calculus and the Jacobian from Change of Variables in Multiple Integrals, read as a statement about densities. Normalizing flows are generative models built on it: an invertible neural network gg maps a simple Gaussian to the data distribution, and the log-likelihood is ln⁡pX(x)−ln⁡∣det⁡Jg(x)∣\ln p_X(x) - \ln \lvert \det J_g(x) \rvert. Inverse-transform sampling (Exercise 4) is the one-dimensional case.

KL divergence as an integral

The Kullback-Leibler divergence measures how much a distribution qq differs from pp:

KL⁡(p∥q)=∫p(x)⋅ln⁡p(x)q(x) dx≥0,with equality only when p=q\operatorname{KL}(p \parallel q) = \int p(x) \cdot \ln\frac{p(x)}{q(x)}\,dx \ge 0, \qquad \text{with equality only when } p = q

It is not symmetric. For two Gaussians it has a closed form, which is what the KL term of a variational autoencoder's loss uses:

KL⁡(N(μ1,σ12)∥N(μ2,σ22))=ln⁡σ2σ1+σ12+(μ1−μ2)22σ22−12\operatorname{KL}\big(\mathcal{N}(\mu_1, \sigma_1^2) \parallel \mathcal{N}(\mu_2, \sigma_2^2)\big) = \ln\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac{1}{2}

Cross-entropy loss is closely related: −∫pln⁡q=H(p)+KL⁡(p∥q)-\int p \ln q = H(p) + \operatorname{KL}(p \parallel q), so minimising cross-entropy with a fixed data distribution pp is minimising the KL divergence.

python · try it yourself
import numpy as np
from scipy.integrate import quad
from scipy.stats import norm

def kl_numeric(m1, s1, m2, s2):
    integrand = lambda x: norm.pdf(x, m1, s1) * (norm.logpdf(x, m1, s1) - norm.logpdf(x, m2, s2))
    return quad(integrand, -np.inf, np.inf)[0]

def kl_formula(m1, s1, m2, s2):
    return np.log(s2 / s1) + (s1**2 + (m1 - m2)**2) / (2 * s2**2) - 0.5

for args in [(0, 1, 1, 2), (1, 2, 0, 1), (0, 1, 0, 1)]:
    print(f"KL(N{args[:2]} || N{args[2:]}):  integral = {kl_numeric(*args):.6f}   formula = {kl_formula(*args):.6f}")
KL(N(0, 1) || N(1, 2)):  integral = 0.443147   formula = 0.443147
KL(N(1, 2) || N(0, 1)):  integral = 1.306853   formula = 1.306853
KL(N(0, 1) || N(0, 1)):  integral = 0.000000   formula = 0.000000

The program writes each Gaussian as N(μ,σ)\mathcal{N}(\mu, \sigma) with the standard deviation, as SciPy does, so N(1,2)\mathcal{N}(1, 2) has variance 4. The first two lines are the same pair of Gaussians in both orders: 0.443 against 1.307, so the order matters. KL⁡(p∥q)\operatorname{KL}(p \parallel q) punishes qq heavily where pp has mass and qq has almost none.

The reparameterisation trick

A VAE needs the gradient of an expectation whose distribution depends on the parameters: ∇θEz∼N(μ,σ2)[f(z)]\nabla_\theta \mathbb{E}_{z \sim \mathcal{N}(\mu, \sigma^2)}[f(z)] with θ=(μ,σ)\theta = (\mu, \sigma). The gradient cannot be pushed through a random draw directly. The trick is to write the sample as a deterministic function of the parameters and parameter-free noise:

z=μ+σ⋅ε,ε∼N(0,1)∇θE[f(z)]=Eε[∇θf(μ+σε)]=Eε[f′(z)⋅(1,ε)]for θ=(μ,σ)\begin{aligned} &z = \mu + \sigma \cdot \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, 1) \\ &\nabla_\theta \mathbb{E}[f(z)] = \mathbb{E}_\varepsilon[\nabla_\theta f(\mu + \sigma\varepsilon)] = \mathbb{E}_\varepsilon[f'(z) \cdot (1, \varepsilon)] && \text{for } \theta = (\mu, \sigma) \end{aligned}

Now the derivative moves inside the expectation (it is an integral over ε\varepsilon with a fixed density), and ordinary backpropagation handles f′f'. The older alternative, the score-function (REINFORCE) estimator E[f(z)⋅∇θln⁡pθ(z)]\mathbb{E}[f(z) \cdot \nabla_\theta \ln p_\theta(z)], is also unbiased but much noisier. Test both on f(z)=z2f(z) = z^2, where E[z2]=μ2+σ2\mathbb{E}[z^2] = \mu^2 + \sigma^2 and the exact gradient is (2μ,2σ)(2\mu, 2\sigma):

python · try it yourself
import numpy as np

rng = np.random.default_rng(11)
mu, sigma, N = 1.0, 0.5, 10_000
eps = rng.standard_normal(N)
z = mu + sigma * eps
f = z**2

reparam = np.column_stack([2*z, 2*z*eps])                        # f'(z) * dz/dtheta
score = np.column_stack([f * (z - mu) / sigma**2,                 # f(z) * d log p / d mu
                         f * ((z - mu)**2 / sigma**3 - 1/sigma)])  # f(z) * d log p / d sigma
print("exact gradient        : [2. 1.]")
for name, g in [("reparameterisation", reparam), ("score function", score)]:
    print(f"{name:<22}: mean {np.round(g.mean(axis=0), 3)}   std per sample {np.round(g.std(axis=0), 2)}")
exact gradient        : [2. 1.]
reparameterisation    : mean [2.014 1.031]   std per sample [1.   2.46]
score function        : mean [2.043 1.029]   std per sample [4.72 9.56]

Both means approach (2,1)(2, 1), but the score-function samples spread several times wider, so they need many more samples for the same accuracy.

In software

  • VAEs and diffusion models use the reparameterisation trick to train an encoder that outputs (μ,σ)(\mu, \sigma), and the Gaussian KL formula as a regulariser.
  • Classifiers and LLMs minimise cross-entropy, that is a KL divergence to the data distribution; distillation minimises a KL divergence between a teacher's and a student's output distributions, and RLHF adds a KL penalty that keeps a fine-tuned model close to its base model.
  • Normalizing flows and inverse-transform sampling rely on the change-of-variables formula; numpy.random turns uniform bits into exponential and Gaussian samples this way.

Exercises

Exercise 1: Normalise a ramp

Find cc such that p(x)=c⋅xp(x) = c \cdot x on [0,2][0, 2] (zero elsewhere) is a density, and compute E[X]\mathbb{E}[X].

Answer

c=1/2c = 1/2, E[X]=4/3\mathbb{E}[X] = 4/3.

Solution
∫02c⋅x dx=c⋅2=1  →  c=12E[X]=∫02x⋅x2 dx=[x36]02=86=43\begin{aligned} &\int_0^2 c \cdot x\,dx = c \cdot 2 = 1 \;\to\; c = \tfrac{1}{2} \\ &\mathbb{E}[X] = \int_0^2 x \cdot \frac{x}{2}\,dx = \left[\frac{x^3}{6}\right]_0^2 = \frac{8}{6} = \frac{4}{3} \end{aligned}

Exercise 2: Mean of the exponential distribution

Show that p(x)=λe−λxp(x) = \lambda e^{-\lambda x} on [0,∞)[0, \infty) is a density and that its mean is 1/λ1/\lambda.

Answer

∫p=1\int p = 1 and E[X]=1/λ\mathbb{E}[X] = 1/\lambda.

Solution
∫0∞λe−λx dx=[−e−λx]0∞=0−(−1)=1E[X]=∫0∞x⋅λe−λx dx;by parts with u=x, dv=λe−λx dx:=[−xe−λx]0∞+∫0∞e−λx dx=0+1/λ\begin{aligned} \int_0^\infty \lambda e^{-\lambda x}\,dx &= \left[-e^{-\lambda x}\right]_0^\infty = 0 - (-1) = 1 \\ \mathbb{E}[X] &= \int_0^\infty x \cdot \lambda e^{-\lambda x}\,dx; && \text{by parts with } u = x,\ dv = \lambda e^{-\lambda x}\,dx\text{:} \\ &= \left[-x e^{-\lambda x}\right]_0^\infty + \int_0^\infty e^{-\lambda x}\,dx = 0 + 1/\lambda \end{aligned}

Exercise 3: KL between exponentials (code)

Derive KL⁡(Exp⁡(a)∥Exp⁡(b))=ln⁡(a/b)+b/a−1\operatorname{KL}(\operatorname{Exp}(a) \parallel \operatorname{Exp}(b)) = \ln(a/b) + b/a - 1 and check it for a=2a = 2, b=1b = 1 with scipy.integrate.quad.

Answer

ln⁡2−12≈0.193147\ln 2 - \frac{1}{2} \approx 0.193147.

Solution
ln⁡(p/q)=ln⁡(a/b)−(a−b)xKL⁡=∫ae−ax[ln⁡(a/b)−(a−b)x] dx=ln⁡(a/b)−(a−b)⋅1a=ln⁡(a/b)+b/a−1a=2, b=1:ln⁡2+12−1≈0.193147\begin{aligned} \ln(p/q) &= \ln(a/b) - (a - b)x \\ \operatorname{KL} &= \int a e^{-ax} [\ln(a/b) - (a - b)x]\,dx = \ln(a/b) - (a - b) \cdot \frac{1}{a} = \ln(a/b) + b/a - 1 \\ a = 2,\ b = 1{:}\quad &\ln 2 + \tfrac{1}{2} - 1 \approx 0.193147 \end{aligned}
python · try it yourself
import numpy as np
from scipy.integrate import quad
a, b = 2.0, 1.0
kl = quad(lambda x: a*np.exp(-a*x) * (np.log(a/b) - (a - b)*x), 0, np.inf)[0]
print(round(kl, 6), round(np.log(a/b) + b/a - 1, 6))
0.193147 0.193147

Exercise 4: Inverse-transform sampling

XX is uniform on (0,1)(0, 1) and Y=−ln⁡(X)/λY = -\ln(X)/\lambda. Use the change-of-variables formula to find the density of YY.

Answer

pY(y)=λe−λyp_Y(y) = \lambda e^{-\lambda y} for y>0y > 0: YY is exponential with rate λ\lambda.

Solution
y=−ln⁡(x)/λ  ⟺  x=e−λy,dxdy=−λe−λypY(y)=pX(x)⋅∣dxdy∣=1⋅λe−λy(x∈(0,1)  ⟺  y∈(0,∞))\begin{aligned} &y = -\ln(x)/\lambda \iff x = e^{-\lambda y}, \qquad \frac{dx}{dy} = -\lambda e^{-\lambda y} \\ &p_Y(y) = p_X(x) \cdot \left\lvert \frac{dx}{dy} \right\rvert = 1 \cdot \lambda e^{-\lambda y} && (x \in (0, 1) \iff y \in (0, \infty)) \end{aligned}

Test yourself

What does KL⁡(p∥q)=0\operatorname{KL}(p \parallel q) = 0 tell you?

  1. pp and qq are equal (almost everywhere)
  2. pp and qq have the same mean
  3. qq is uniform
  4. pp is Gaussian

Why does the reparameterisation z=μ+σεz = \mu + \sigma\varepsilon make the gradient computable by backpropagation?

  1. It removes all randomness
  2. The randomness ε\varepsilon no longer depends on the parameters, so the derivative can move inside the expectation over ε\varepsilon
  3. It makes the KL divergence zero
  4. It normalises the density

XX has density pXp_X and Y=3XY = 3X. What is pY(y)p_Y(y)?

  1. 3⋅pX(3y)3 \cdot p_X(3y)
  2. pX(y/3)p_X(y/3)
  3. 13⋅pX(y/3)\frac{1}{3} \cdot p_X(y/3)
  4. pX(3y)p_X(3y)