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 is a function with ; the probability of an interval is . Expectations are integrals weighted by :
| Quantity | Integral |
|---|---|
| normalising constant of an unnormalised | , then |
| mean | |
| expectation of | |
| variance | |
| entropy |
The most important integral in ML is the Gaussian one, over , proved by squaring it and switching to polar coordinates. Computing is the hard part of many models: energy-based models and Boltzmann machines define , and is an integral over a huge space.
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 with increasing and differentiable, probability is conserved on matching intervals, so and
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 maps a simple Gaussian to the data distribution, and the log-likelihood is . Inverse-transform sampling (Exercise 4) is the one-dimensional case.
KL divergence as an integral
The Kullback-Leibler divergence measures how much a distribution differs from :
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:
Cross-entropy loss is closely related: , so minimising cross-entropy with a fixed data distribution is minimising the KL divergence.
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 with the standard deviation, as SciPy does, so 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. punishes heavily where has mass and has almost none.
The reparameterisation trick
A VAE needs the gradient of an expectation whose distribution depends on the parameters: with . 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:
Now the derivative moves inside the expectation (it is an integral over with a fixed density), and ordinary backpropagation handles . The older alternative, the score-function (REINFORCE) estimator , is also unbiased but much noisier. Test both on , where and the exact gradient is :
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 , 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 , 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.randomturns uniform bits into exponential and Gaussian samples this way.
Exercises
Exercise 1: Normalise a ramp
Find such that on (zero elsewhere) is a density, and compute .
Answer
, .
Solution
Exercise 2: Mean of the exponential distribution
Show that on is a density and that its mean is .
Answer
and .
Solution
Exercise 3: KL between exponentials (code)
Derive and check it for , with scipy.integrate.quad.
Answer
.
Solution
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
is uniform on and . Use the change-of-variables formula to find the density of .
Answer
for : is exponential with rate .
Solution
Test yourself
What does tell you?
- and are equal (almost everywhere)
- and have the same mean
- is uniform
- is Gaussian
Why does the reparameterisation make the gradient computable by backpropagation?
- It removes all randomness
- The randomness no longer depends on the parameters, so the derivative can move inside the expectation over
- It makes the KL divergence zero
- It normalises the density
has density and . What is ?