The distributions that run AI¶
About a dozen probability distributions do nearly all the work in machine learning. Learn each one as a shape, a story for where it comes from, and the loss function it turns into, and most of the equations in AI papers stop being notation and start being choices.
10,000 ft
Every model makes a distributional assumption, whether or not its authors say so. An LLM's output layer is a categorical distribution over tokens. A binary classifier is a Bernoulli. Mean-squared-error regression is a Gaussian in disguise; L1 regression is a Laplace. Diffusion models add and remove Gaussian noise; VAEs push data through a Gaussian latent; Thompson sampling keeps a Beta per arm; topic models use Dirichlet priors; request arrivals at an inference server are close to Poisson. Real data is often heavy-tailed, which breaks the Gaussian intuitions. This page gives you the catalogue, the family resemblances between its members (most are one exponential family), and the two sampling tricks (Gumbel-max and reparameterisation) that let gradient descent work through randomness. It builds on probability foundations and feeds estimation and information theory.
2,000 ft
Four questions place any distribution: what values it ranges over (binary, one of \(K\), a real number, a positive number, a probability, a vector), what story generates it (a coin flip, a sum of many small effects, waiting for a rare event, a vote of priors), what loss its negative log-likelihood becomes, and how you sample it. The family tree below shows how the main ones are built from each other.
Ground level¶
Bernoulli and binomial: one bit, and counting bits¶
A Bernoulli variable takes the value 1 with probability \(p\) and 0 otherwise: \(p(x) = p^x (1-p)^{1-x}\), mean \(p\), variance \(p(1-p)\). It is the output of every binary classifier (spam or not, toxic or not, the reward model's "is A preferred to B"), and of every eval question scored right or wrong. The variance \(p(1-p)\) is largest at \(p = 0.5\): a model that is right half the time is the hardest to measure precisely.
Add up \(n\) independent Bernoullis with the same \(p\) and you get a binomial, \(P(K = k) = \binom{n}{k} p^k (1-p)^{n-k}\), mean \(np\), variance \(np(1-p)\). If a model with true accuracy 70% answers 200 questions, the number it gets right is binomial with mean 140 and standard deviation \(\sqrt{200 \times 0.7 \times 0.3} = 6.5\); scores between 127 and 153 (63.5% to 76.5%) are all unremarkable. Seeing this spread before reading a leaderboard is a habit worth building; statistics for evals turns it into error bars.
Categorical and the softmax: the shape of every LLM output¶
A categorical distribution picks one of \(K\) outcomes with probabilities \(p_1, \dots, p_K\) that are non-negative and sum to 1. With a one-hot vector \(\mathbf{y}\) for the outcome, \(p(\mathbf{y}) = \prod_k p_k^{y_k}\). An LLM's output at each position is exactly this, with \(K\) the vocabulary size (tens of thousands to a few hundred thousand tokens in current models).
Networks produce unconstrained real numbers (logits \(z_k\)), so the last layer maps them to a valid categorical with the softmax:
For logits \((2.0, 1.0, 0.1)\) the probabilities are \((0.659, 0.242, 0.099)\). Adding the same constant to every logit changes nothing (it cancels top and bottom), and dividing the logits by a temperature \(T\) before the softmax sharpens (\(T < 1\)) or flattens (\(T > 1\)) the distribution. Softmax is not an arbitrary squashing function: it is the inverse of the categorical's natural parameterisation, as the exponential family section shows, which is why its gradient under cross-entropy is so clean.
Counting the outcomes of \(n\) categorical draws gives the multinomial, the categorical's version of the binomial; a bag-of-words document is one multinomial sample.
The Gaussian: the shape of sums and of noise¶
The Gaussian (normal) density with mean \(\mu\) and variance \(\sigma^2\) is
About 68.3% of the mass lies within one standard deviation of the mean, 95.4% within two and 99.7% within three. It deserves its central place for four separate reasons:
- Sums. By the central limit theorem, a sum of many small independent effects is approximately Gaussian whatever the effects look like. Measurement noise, the pre-activation of a wide layer at initialisation, and the noise in a large-batch gradient are all such sums.
- Maximum entropy. Among all distributions with a given mean and variance, the Gaussian assumes the least (it has the highest entropy; derived in First principles). Choosing it says "I know the scale and nothing else".
- Closure. Linear maps of Gaussians are Gaussian; marginals and conditionals of a multivariate Gaussian are Gaussian; the product of two Gaussian densities is a scaled Gaussian. Whole fields (Kalman filters, Gaussian processes, linear-Gaussian diffusion) run on these closed forms.
- Its log is a quadratic. \(-\log \mathcal{N}(y; \mu, \sigma^2) = \frac{(y - \mu)^2}{2\sigma^2} + \frac12 \log(2\pi\sigma^2)\). With \(\sigma\) fixed, maximising Gaussian likelihood is minimising squared error. MSE is a Gaussian assumption.
The multivariate Gaussian over \(\mathbf{x} \in \mathbb{R}^d\) has a mean vector \(\boldsymbol{\mu}\) and a \(d \times d\) covariance matrix \(\Sigma\):
Its contours are ellipses whose axes are the eigenvectors of \(\Sigma\), with half-lengths proportional to the square roots of the eigenvalues; that is exactly the picture PCA draws (see eigenvectors, SVD and PCA). The quadratic form in the exponent is the squared Mahalanobis distance, distance measured in units of the data's own spread.
Where you will meet it in AI:
- Initialisation. Weights are drawn from a zero-mean Gaussian (or uniform) whose variance keeps activations from exploding or vanishing: \(2/(n_\text{in} + n_\text{out})\) for Glorot and Bengio (2010), \(2/n_\text{in}\) for ReLU networks in He et al. (2015). Both come from the rule \(\operatorname{Var}(\sum_i w_i x_i) = n\,\operatorname{Var}(w)\operatorname{Var}(x)\) for independent zero-mean terms (see initialisation).
- Diffusion. The forward process of DDPM (Ho et al., 2020) blends data with Gaussian noise, and by the closure property the noisy sample at any step is one Gaussian away from the clean data: \(q(\mathbf{x}_t \mid \mathbf{x}_0) = \mathcal{N}(\sqrt{\bar\alpha_t}\,\mathbf{x}_0, (1 - \bar\alpha_t) I)\). See diffusion models.
- Latent variables. A VAE encodes each input as a diagonal Gaussian and regularises it towards \(\mathcal{N}(\mathbf{0}, I)\).
- Infinitely wide networks. A randomly initialised network with infinitely wide layers computes a Gaussian process (Lee et al., 2017, extending Radford Neal's 1990s single-hidden-layer result), one of the starting points of the infinite-width theory of deep learning.
Uniform, exponential and Poisson: time and counts¶
The uniform distribution on \([a, b]\) is the raw material of all sampling (every pseudo-random generator produces it) and one of the two standard initialisation choices.
The Poisson distribution counts rare independent events in a fixed window: \(P(K = k) = \lambda^k e^{-\lambda} / k!\), mean and variance both \(\lambda\). It is the limit of a binomial with many trials and a tiny success probability. The waiting time between Poisson events is exponential, density \(\lambda e^{-\lambda t}\) with mean \(1/\lambda\), and it is memoryless: having waited 3 seconds tells you nothing about the remaining wait.
These two appear in AI systems more than in AI models. Requests arriving at an inference server are often modelled as Poisson: at an average of 5 requests per second, a one-second window is empty with probability \(e^{-5} = 0.0067\) and contains 10 or more requests with probability 0.032, about twice a minute. Capacity planning, batching windows and queueing delays in LLM serving start from this model, and the variance equal to the mean is a quick check of whether real traffic is burstier than Poisson (it usually is).
Beta and Dirichlet: distributions over probabilities¶
Sometimes the unknown is a probability: a model's true accuracy, an arm's click-through rate, a topic's word frequencies. The Beta distribution lives on \([0, 1]\),
and its parameters read as pseudo-counts: \(\operatorname{Beta}(8, 4)\) is roughly "8 successes and 4 failures' worth of belief", mean 0.667 and standard deviation 0.131. Its key property is conjugacy with the Bernoulli: start with \(\operatorname{Beta}(\alpha, \beta)\), observe \(s\) successes and \(f\) failures, and the posterior is \(\operatorname{Beta}(\alpha + s, \beta + f)\). Learning is addition. Thompson sampling for bandits keeps one Beta per arm, samples a \(p\) from each and plays the largest (see bandits); estimation uses the same update to explain smoothing.
The Dirichlet is the Beta for \(K\) outcomes, a distribution over probability vectors, and conjugate to the categorical. Its concentration parameters control sparsity: all \(\alpha_k = 1\) is uniform over the simplex; all \(\alpha_k \ll 1\) puts mass near the corners, favouring vectors where a few components dominate. That is why latent Dirichlet allocation uses small \(\alpha\): each document should be about a few topics, not all of them.
Heavy tails and power laws¶
The Gaussian's tails fall off like \(e^{-x^2/2}\), absurdly fast: a six-standard-deviation event is about 65 million times less dense than the centre. Many quantities in AI do not behave like that.
- Word and token frequencies follow Zipf's law approximately: the \(r\)-th most common word has frequency roughly proportional to \(1/r\) (see Piantadosi's review, 2014). A few tokens are everywhere; a long tail is seen a handful of times, which is why rare tokens get poor embeddings and why vocabulary design matters (see tokenisation).
- Gradient noise in deep networks has been measured to be heavy-tailed rather than Gaussian (Simsekli et al., 2019), one argument for gradient clipping.
- Activations in large transformers contain rare outlier features many times larger than the rest, which break naive 8-bit quantisation (Dettmers et al., 2022; see quantisation).
- Losses across examples: a few mislabelled or hard examples can dominate a mean.
Two families model heavy tails. The Laplace distribution, density \(\frac{1}{2b} e^{-|x - \mu|/b}\), has exponential tails; its negative log-likelihood is \(|x - \mu|/b\), so L1 loss and the lasso are Laplace assumptions. The Student-t with \(\nu\) degrees of freedom has polynomial tails: its variance is infinite for \(\nu \le 2\) and its mean does not exist for \(\nu \le 1\) (the Cauchy case). When the variance is infinite the \(1/\sqrt{n}\) law of the previous page fails, averages wander, and robust statistics (medians, trimmed means, clipping) are no longer optional; the code below shows it. For checking whether data really follow a power law, use the methods of Clauset, Shalizi and Newman (2009), not a straight line on a log–log plot.
Mixtures: when the answer has more than one mode¶
A mixture draws a component \(k\) with probability \(\pi_k\) and then a value from that component: \(p(x) = \sum_k \pi_k\, p_k(x)\). A Gaussian mixture can approximate any smooth density given enough components. Mixtures matter because real targets are often multimodal. If half the plausible futures go left and half go right, a model trained with MSE predicts straight ahead, the mean, which is the one thing that never happens; blurry image predictions are the same failure. Fixes either model the mixture explicitly (mixture density networks, Gaussian mixture models fitted with EM; see clustering and mixtures) or sample from a richer model (autoregressive categorical outputs, diffusion). Mixture of experts began, in Jacobs, Jordan, Nowlan and Hinton (1991), as a literal mixture model with a gating network choosing the component; today's sparse MoE layers keep the gate (see mixture of experts).
The Gumbel-max trick: sampling as an argmax¶
The Gumbel distribution describes the maximum of many independent draws; a standard Gumbel sample is \(g = -\log(-\log U)\) with \(U\) uniform. Its remarkable property: if you add independent standard Gumbel noise to each logit and take the argmax, the winner is an exact sample from the softmax,
The code below checks it: over a million draws the argmax frequencies are \((0.659, 0.242, 0.099)\), matching the softmax to three decimals. This turns sampling into a perturb-then-argmax operation that parallelises well, and replacing the hard argmax with a temperature-controlled softmax gives the Gumbel-softmax (or Concrete) relaxation, a differentiable approximation to a discrete sample, introduced simultaneously by Jang, Gu and Poole and Maddison, Mnih and Teh in 2016.
Reparameterisation: gradients through a sample¶
You often need the gradient of an expectation with respect to the parameters of the distribution you are sampling from, e.g. \(\nabla_{\mu, \sigma} \mathbb{E}_{z \sim \mathcal{N}(\mu, \sigma^2)}[f(z)]\). Sampling \(z\) directly blocks the gradient: a random number has no derivative. The reparameterisation trick writes the sample as a deterministic function of parameter-free noise, \(z = \mu + \sigma \varepsilon\) with \(\varepsilon \sim \mathcal{N}(0, 1)\), so
and an average over a few samples of \(\varepsilon\) is a low-variance, unbiased gradient estimate. For \(f(z) = z^2\) with \(\mu = 1.5\), \(\sigma = 0.5\), the code recovers \(\partial/\partial\mu = 3.000\) and \(\partial/\partial\sigma = 0.998\) against exact values 3 and 1. This trick is what made VAEs trainable with backpropagation. When no such reparameterisation exists (discrete actions, a sampled token), you fall back on the higher-variance score-function (REINFORCE) estimator of policy gradients.
Choosing a distribution is choosing a loss¶
Because training maximises likelihood (see estimation), the distribution you assume for the target fixes the loss you minimise:
| Target | Assumed distribution | Negative log-likelihood (per example) | Name in code |
|---|---|---|---|
| real number | Gaussian, fixed \(\sigma\) | \(\frac{(y - \mu)^2}{2\sigma^2}\) + const | MSE |
| real number with outliers | Laplace, fixed \(b\) | \(\frac{\lvert y - \mu \rvert}{b}\) + const | L1 / MAE |
| real number, uncertain | Gaussian, predicted \(\sigma\) | \(\frac{(y - \mu)^2}{2\sigma^2} + \log \sigma\) | Gaussian NLL |
| yes / no | Bernoulli, \(p = \sigma(z)\) | \(-y \log p - (1 - y)\log(1 - p)\) | binary cross-entropy |
| one of \(K\) | Categorical, \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) | \(-\log p_y\) | cross-entropy |
| count | Poisson, \(\lambda = e^{z}\) | \(\lambda - y \log \lambda\) + const | Poisson NLL |
The assumption decides what the model predicts. Minimising squared error makes the prediction the conditional mean; absolute error makes it the conditional median. On the targets \((1, 2, 3, 50)\) the MSE-optimal constant is 14 and the MAE-optimal constant is 2.5. One outlier moves the mean prediction from 2 to 14 and leaves the median almost untouched. Predicting \(\sigma\) as well (the third row) lets a model say "I don't know" on hard inputs, the basis of heteroscedastic regression and of aleatoric uncertainty estimates.
The exponential family: one template for almost all of them¶
Bernoulli, categorical, Gaussian, Poisson, exponential, Beta, Dirichlet and gamma all share one form:
with natural parameters \(\boldsymbol{\eta}\), sufficient statistics \(T(x)\), base measure \(h(x)\) and log-partition function \(A(\boldsymbol{\eta})\), which normalises the density. Rewrite the Bernoulli: \(p^x (1-p)^{1-x} = \exp\big(x \log\tfrac{p}{1-p} + \log(1-p)\big)\). So its natural parameter is the logit \(\eta = \log\frac{p}{1-p}\), and inverting gives \(p = 1/(1 + e^{-\eta})\), the sigmoid. Do the same for the categorical and the inverse map is the softmax; for the Poisson it is \(\lambda = e^\eta\). The output nonlinearities of neural networks are not design whims: they are the canonical inverse links of the distribution being predicted (generalised linear models, with a network computing \(\eta\)).
Two identities make the family powerful. First, \(\nabla_{\boldsymbol\eta} A = \mathbb{E}[T(x)]\) and \(\nabla^2_{\boldsymbol\eta} A = \operatorname{Cov}[T(x)]\), so \(A\) is convex and the negative log-likelihood is convex in \(\boldsymbol\eta\). Second, the gradient of the negative log-likelihood with respect to the natural parameters is
predicted minus observed. For softmax with cross-entropy that is the famous \(\mathbf{p} - \mathbf{y}\) gradient with respect to the logits; for logistic regression it is \(p - y\); for linear regression it is \(\mu - y\). One formula, every output layer.
First principles¶
Why these shapes, and not others? Most of the catalogue can be derived from one principle: choose the distribution with the greatest entropy consistent with what you know. Entropy (see information theory) measures how much a distribution leaves unsaid; maximising it means assuming nothing you weren't told.
- Know only the range \([a, b]\): the answer is uniform.
- Know the value is positive and its mean: exponential.
- Know the mean and variance of a real number: Gaussian.
- Know the expected values of any set of features \(T(x)\): the exponential family with those sufficient statistics. This is why "log-linear models" and softmax classifiers over features are the natural default.
The derivation is a short Lagrange-multiplier calculation, shown in The maths.
Why the Gaussian is also forced by geometry. Suppose a 2-D error distribution is rotationally symmetric (no preferred direction) and its \(x\) and \(y\) coordinates are independent. The only density with both properties is a Gaussian: independence makes \(p(x, y) = f(x) f(y)\), symmetry makes it a function of \(x^2 + y^2\), and the only functions with \(f(x) f(y) = g(x^2 + y^2)\) are \(f(x) \propto e^{-c x^2}\). This Herschel–Maxwell argument is also where the \(\pi\) in the normalising constant comes from (3Blue1Brown's video in Go deeper tells this story).
Why sums go Gaussian. In the space of distributions, adding independent variables is convolution, and the Gaussian is the fixed point that repeated convolution (with rescaling) flows to, as long as variances are finite. If variances are infinite, the flow goes elsewhere: to the stable distributions, of which Cauchy is one. So "heavy tails" are not exotic noise; they are a different basin of attraction.
Why conjugacy exists. A prior is conjugate when it has the same functional form as the likelihood viewed as a function of the parameter. The Bernoulli likelihood of \(s\) successes and \(f\) failures is \(p^s(1-p)^f\); the Beta density is \(p^{\alpha-1}(1-p)^{\beta-1}\); multiplying them just adds exponents. Every exponential-family likelihood has such a conjugate prior. It is a convenience, not a law of nature, and modern Bayesian deep learning mostly gives it up (see estimation).
The maths¶
The catalogue
| Distribution | Support | PMF / PDF | Mean | Variance |
|---|---|---|---|---|
| Bernoulli\((p)\) | \(\{0,1\}\) | \(p^x(1-p)^{1-x}\) | \(p\) | \(p(1-p)\) |
| Binomial\((n,p)\) | \(\{0..n\}\) | \(\binom{n}{k}p^k(1-p)^{n-k}\) | \(np\) | \(np(1-p)\) |
| Categorical\((\mathbf{p})\) | one of \(K\) | \(\prod_k p_k^{y_k}\) | \(\mathbf{p}\) | \(\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\) |
| Poisson\((\lambda)\) | \(\{0,1,\dots\}\) | \(\lambda^k e^{-\lambda}/k!\) | \(\lambda\) | \(\lambda\) |
| Uniform\((a,b)\) | \([a,b]\) | \(1/(b-a)\) | \((a+b)/2\) | \((b-a)^2/12\) |
| Exponential\((\lambda)\) | \([0,\infty)\) | \(\lambda e^{-\lambda x}\) | \(1/\lambda\) | \(1/\lambda^2\) |
| Gaussian\((\mu,\sigma^2)\) | \(\mathbb{R}\) | \(\frac{1}{\sqrt{2\pi\sigma^2}}e^{-(x-\mu)^2/2\sigma^2}\) | \(\mu\) | \(\sigma^2\) |
| Laplace\((\mu,b)\) | \(\mathbb{R}\) | \(\frac{1}{2b}e^{-\lvert x-\mu\rvert/b}\) | \(\mu\) | \(2b^2\) |
| Beta\((\alpha,\beta)\) | \([0,1]\) | \(\frac{p^{\alpha-1}(1-p)^{\beta-1}}{B(\alpha,\beta)}\) | \(\frac{\alpha}{\alpha+\beta}\) | \(\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\) |
| Dirichlet\((\boldsymbol\alpha)\) | simplex | \(\frac{\prod_k p_k^{\alpha_k-1}}{B(\boldsymbol\alpha)}\) | \(\alpha_k / \sum_j \alpha_j\) | see Bishop §2.2 |
| Gumbel\((0,1)\) | \(\mathbb{R}\) | \(e^{-(x + e^{-x})}\) | \(\gamma \approx 0.5772\) | \(\pi^2/6\) |
The Categorical variance is the covariance matrix of the one-hot vector; it is also the Hessian of the log-partition \(\log\sum_k e^{\eta_k}\), i.e. the Jacobian of softmax.
Multivariate Gaussian: affine maps, marginals, conditionals
If \(\mathbf{x} \sim \mathcal{N}(\boldsymbol\mu, \Sigma)\) then \(A\mathbf{x} + \mathbf{b} \sim \mathcal{N}(A\boldsymbol\mu + \mathbf{b}, A\Sigma A^\top)\). Sampling follows: with \(\Sigma = LL^\top\) (Cholesky) and \(\boldsymbol\varepsilon \sim \mathcal{N}(\mathbf{0}, I)\), \(\mathbf{x} = \boldsymbol\mu + L\boldsymbol\varepsilon\).
Partition \(\mathbf{x} = (\mathbf{x}_1, \mathbf{x}_2)\) with blocks \(\boldsymbol\mu_i\), \(\Sigma_{ij}\). The marginal is \(\mathbf{x}_1 \sim \mathcal{N}(\boldsymbol\mu_1, \Sigma_{11})\) and the conditional is
The conditional mean is a linear regression of \(\mathbf{x}_1\) on \(\mathbf{x}_2\); the conditional covariance shrinks by what \(\mathbf{x}_2\) explains and does not depend on the observed value. Gaussian-process regression is this formula applied to function values.
Derivation: maximum entropy gives the exponential family (and the Gaussian)
Maximise \(H[p] = -\int p(x)\log p(x)\,dx\) subject to \(\int p = 1\) and \(\int p(x)\,T_i(x)\,dx = c_i\). The Lagrangian is
Setting the functional derivative with respect to \(p(x)\) to zero: \(-\log p(x) - 1 + \lambda_0 + \sum_i \lambda_i T_i(x) = 0\), so
an exponential family with natural parameters \(\lambda_i\). With \(T(x) = (x, x^2)\) on \(\mathbb{R}\) the exponent is a quadratic, which must open downwards to be normalisable: a Gaussian. With \(T(x) = x\) on \([0, \infty)\): exponential. With no constraints on \([a,b]\): uniform. Entropy is concave and the constraints are linear in \(p\), so this stationary point is the maximum.
Derivation: the exponential-family gradient identities
Normalisation gives \(A(\boldsymbol\eta) = \log \int h(x)\exp(\boldsymbol\eta^\top T(x))\,dx\). Differentiate:
Differentiating again gives \(\nabla^2 A = \mathbb{E}[TT^\top] - \mathbb{E}[T]\mathbb{E}[T]^\top = \operatorname{Cov}[T]\), which is positive semi-definite, so \(A\) is convex. The negative log-likelihood of one observation is \(-\boldsymbol\eta^\top T(x) + A(\boldsymbol\eta) - \log h(x)\), whose gradient is \(\mathbb{E}[T] - T(x)\). For a categorical with \(\boldsymbol\eta\) = logits, \(T(x)\) = one-hot \(\mathbf{y}\) and \(\mathbb{E}[T] = \operatorname{softmax}(\boldsymbol\eta)\), this is \(\mathbf{p} - \mathbf{y}\).
Derivation: why the Gumbel-max trick is exact
Let \(G_j\) be i.i.d. standard Gumbel, with CDF \(F(g) = \exp(-e^{-g})\), and \(Z_j = z_j + G_j\). The probability that \(Z_k\) wins, conditioning on its value \(m\):
(The \(j = k\) factor \(\exp(-e^{-(m - z_k)})\) from the Gumbel density joins the product.) Substitute \(t = e^{-m}\), \(dt = -e^{-m}\,dm\), and write \(S = \sum_j e^{z_j}\):
Build it¶
Three sampling identities, checked numerically: Box–Muller (two uniforms make two Gaussians, Box and Muller, 1958), Gumbel-max, and the reparameterisation gradient.
import numpy as np
rng = np.random.default_rng(0)
n = 1_000_000
# Box-Muller: two uniforms -> two independent standard normals
u1, u2 = rng.random(n), rng.random(n)
r = np.sqrt(-2 * np.log(1 - u1))
z = r * np.cos(2 * np.pi * u2)
print(f"Box-Muller: mean {z.mean():+.4f} var {z.var():.4f} P(|z|<1) {np.mean(abs(z) < 1):.4f} P(|z|<2) {np.mean(abs(z) < 2):.4f}")
# Gumbel-max: argmax(logits + Gumbel noise) is an exact sample from softmax(logits)
logits = np.array([2.0, 1.0, 0.1])
soft = np.exp(logits) / np.exp(logits).sum()
g = -np.log(-np.log(rng.random((n, 3))))
picks = np.argmax(logits + g, axis=1)
print("softmax :", soft.round(4))
print("Gumbel-max :", np.bincount(picks, minlength=3) / n)
# Reparameterisation: z = mu + sigma * eps lets gradients flow through a sample
mu, sigma = 1.5, 0.5
eps = rng.standard_normal(n)
zs = mu + sigma * eps
f = zs**2 # E[z^2] = mu^2 + sigma^2
print(f"E[z^2] MC {f.mean():.4f} exact {mu**2 + sigma**2:.4f}")
print(f"d/dmu MC {np.mean(2 * zs):.4f} exact {2 * mu:.4f}") # pathwise gradient
print(f"d/dsigma MC {np.mean(2 * zs * eps):.4f} exact {2 * sigma:.4f}")
Box-Muller: mean -0.0005 var 1.0019 P(|z|<1) 0.6826 P(|z|<2) 0.9542
softmax : [0.659 0.2424 0.0986]
Gumbel-max : [0.658978 0.242497 0.098525]
E[z^2] MC 2.4993 exact 2.5000
d/dmu MC 2.9997 exact 3.0000
d/dsigma MC 0.9980 exact 1.0000
And the two consequences of the loss-as-distribution view: mean versus median under an outlier, and what heavy tails do to averages.
import numpy as np
rng = np.random.default_rng(1)
# Choosing a distribution is choosing a loss: Gaussian NLL vs MSE, Laplace NLL vs MAE
y = np.array([1.0, 2.0, 3.0, 50.0]) # one outlier
for c in [2.5, 14.0]:
mse = np.mean((y - c)**2); mae = np.mean(abs(y - c))
print(f"prediction {c:>5}: MSE {mse:8.2f} MAE {mae:6.2f}")
print("argmin MSE = mean =", y.mean(), "| argmin MAE = median =", np.median(y))
# Heavy tails: running means of Gaussian vs Student-t (nu = 1.5, infinite variance) vs Cauchy
for name, draw in [("gaussian", lambda k: rng.standard_normal(k)),
("student-t 1.5", lambda k: rng.standard_t(1.5, k)),
("cauchy", lambda k: rng.standard_cauchy(k))]:
x = draw(1_000_000)
print(f"{name:>13}: mean of first 1e3 {x[:1000].mean():+8.3f} 1e5 {x[:100_000].mean():+8.3f} 1e6 {x.mean():+8.3f} max |x| {abs(x).max():.3g}")
prediction 2.5: MSE 564.75 MAE 12.50
prediction 14.0: MSE 432.50 MAE 18.00
argmin MSE = mean = 14.0 | argmin MAE = median = 2.5
gaussian: mean of first 1e3 -0.054 1e5 -0.005 1e6 -0.000 max |x| 5.04
student-t 1.5: mean of first 1e3 +0.374 1e5 -0.048 1e6 -0.030 max |x| 7.63e+03
cauchy: mean of first 1e3 +2.036 1e5 -0.778 1e6 -0.314 max |x| 3.21e+05
The Gaussian's mean settles at the \(1/\sqrt{n}\) rate and its largest value in a million draws is about 5. The Student-t (\(\nu = 1.5\)) has a mean (zero) but no variance: its average still drifts at a million samples and one draw reached 7,630. The Cauchy has no mean at all and its running average never converges.
Things to try
- Sample from a 2-D Gaussian with covariance \(\begin{pmatrix} 2 & 1.2 \\ 1.2 & 1 \end{pmatrix}\) using a Cholesky factor, and check the sample covariance. Then compute the conditional mean of \(x_1\) given \(x_2 = 1\) from the formula and from samples near \(x_2 = 1\).
- Replace the hard argmax in the Gumbel cell with \(\operatorname{softmax}((\mathbf{z} + \mathbf{g})/\tau)\) for \(\tau = 0.1, 1, 10\) and look at the average output vector. What happens to the discreteness as \(\tau\) grows?
- Fit a Poisson to the per-second request counts of any log you have. Is the variance equal to the mean? If it is much larger, the traffic is bursty and a Poisson capacity plan will under-provision.
- Draw Dirichlet samples (
rng.dirichlet) with \(\alpha = (0.1, 0.1, 0.1)\) and \(\alpha = (10, 10, 10)\) and look at how many components exceed 0.5.
Check yourself¶
Why does a model trained with MSE on a bimodal target predict something that never occurs?
MSE is the negative log-likelihood of a unimodal Gaussian, and its minimiser is the conditional mean. The mean of two well-separated modes lies between them, in a region of low probability. Use a mixture output, a categorical over bins, or a generative model.
Logistic regression and a softmax classifier both have gradient 'prediction minus label' with respect to their logits. Why is that not a coincidence?
Both are exponential families in natural parameterisation (Bernoulli with \(\eta\) = logit; categorical with \(\boldsymbol\eta\) = logits). For any exponential family the gradient of the negative log-likelihood with respect to \(\boldsymbol\eta\) is \(\mathbb{E}[T(x)] - T(x)\), and for these two \(T(x)\) is the label and \(\mathbb{E}[T(x)]\) is the predicted probability.
You start with a Beta(1, 1) prior on a model's accuracy and observe 18 correct answers out of 20. What is the posterior, its mean, and how does it differ from 18/20?
\(\operatorname{Beta}(19, 3)\), mean \(19/22 = 0.864\), a little below the raw 0.90. The prior acts like one extra success and one extra failure, pulling the estimate towards 0.5; with 2,000 answers the pull would be negligible.
Why can't you backpropagate through torch.multinomial, and what are two ways around it?
Sampling a discrete index is a piecewise-constant function of the probabilities, so its derivative is zero almost everywhere. Either use the score-function (REINFORCE) estimator, \(\nabla \mathbb{E}[f] = \mathbb{E}[f \nabla \log p]\), which is unbiased but noisy, or relax the sample with Gumbel-softmax, which is differentiable but biased (it is not exactly discrete).
Show that under softmax, adding a constant c to every logit leaves the output unchanged. Why does this matter numerically?
\(e^{z_k + c} / \sum_j e^{z_j + c} = e^c e^{z_k} / (e^c \sum_j e^{z_j})\). It matters because you can subtract \(\max_j z_j\) before exponentiating, so the largest exponent is \(e^0 = 1\) and nothing overflows: the stable softmax of numerical computing.
Hard: a sum of n i.i.d. Cauchy variables, divided by n, has what distribution? What does this say about averaging?
The same standard Cauchy. Its characteristic function is \(e^{-|t|}\), so the mean of \(n\) copies has characteristic function \((e^{-|t|/n})^n = e^{-|t|}\). Averaging buys nothing at all: the central limit theorem's finite-variance assumption fails and Cauchy is its own stable limit. Robust estimators (the median) do concentrate.
Go deeper¶
Papers
- Auto-Encoding Variational Bayes — Kingma and Welling, 2013. Section 2.4 is the reparameterisation trick.
- Categorical Reparameterization with Gumbel-Softmax — Jang, Gu and Poole, 2016. Gumbel-max relaxed for gradients; short and clear.
- The Concrete Distribution — Maddison, Mnih and Teh, 2016. The same relaxation, with more on its properties.
- Power-law distributions in empirical data — Clauset, Shalizi and Newman, 2009. How to test a power-law claim properly.
- Zipf's word frequency law in natural language — Piantadosi, 2014. What Zipf's law is, how well it holds, and why it is not explained.
- A Tail-Index Analysis of Stochastic Gradient Noise — Simsekli, Sagun and Gürbüzbalaban, 2019. Evidence that gradient noise is heavy-tailed.
- Denoising Diffusion Probabilistic Models — Ho, Jain and Abbeel, 2020. The Gaussian closure property, turned into a generative model.
Videos and lectures
- Why π is in the normal distribution — 3Blue1Brown. The Herschel–Maxwell argument, visually.
- Convolutions: why X+Y in probability is a beautiful mess — 3Blue1Brown. What adding random variables does to their distributions.
- Binomial distributions: probabilities of probabilities — 3Blue1Brown. From binomial to Beta, motivated by product reviews.
Articles and interactive
- Probability Distribution Explorer — Justin Bois. Every distribution with its story, parameters and interactive plots.
- Tutorial: Categorical VAEs with Gumbel-Softmax — Eric Jang, 2016. The Gumbel-softmax paper explained by its first author, with code.
Books
- Pattern Recognition and Machine Learning — Bishop, 2006 (free PDF). Chapter 2 is the definitive treatment of these distributions, conjugacy and the exponential family.
- Probabilistic Machine Learning: An Introduction — Murphy, 2022 (free PDF). Chapters 2–3 cover the same ground with modern notation.
Where this leads¶
- Estimation: MLE, MAP and Bayes — fit these distributions to data, and see why the loss table above is just maximum likelihood.
- Entropy, cross-entropy and KL divergence — measure the distance between two of these distributions; the maximum-entropy argument made precise.
- Floating point, stability and log-sum-exp — compute softmax and Gaussian log-densities without overflowing.
- Diffusion models — the Gaussian's closure properties, used as a generative model.
- Decoding: greedy, beam, temperature, top-k, top-p — what to do with the categorical once the model has produced it.