Skip to content
Mathematical foundations Core 25 min read

Estimation: MLE, MAP and Bayes

Learning from data is estimating the parameters of a probability model. There are three ways to do it: pick the parameters that make the data most probable (maximum likelihood), add a prior and pick the most probable parameters (MAP), or keep the whole distribution over parameters (Bayes). Training a neural network with cross-entropy is the first; weight decay turns it into the second; ensembles and Bayesian deep learning reach for the third.

10,000 ft

When you pre-train an LLM by minimising cross-entropy on next tokens, you are doing maximum likelihood estimation of billions of parameters. When you add weight decay, you are doing maximum a posteriori estimation with a Gaussian prior. When you smooth counts, use label smoothing, or ensemble five models to get calibrated uncertainty, you are approximating Bayesian inference. The same three ideas organise classical statistics, so this page is the bridge between "the model" of distributions and "the loss" of information theory, and the reason regularisation exists. It also tells you how good an estimate can possibly be (Fisher information and the Cramér–Rao bound), which is the theory behind every error bar in statistics for evals.

2,000 ft

Write down a model \(p(\text{data} \mid \theta)\). Viewed as a function of \(\theta\) with the data fixed, it is the likelihood. Then choose how much of the picture to keep:

Three ways to learn θ from data
Three ways to learn θ from data. Data D (i.i.d. examples), Model p(D given θ) = likelihood, Prior p(θ) = inductive bias, Posterior p(θ given D) ∝ likelihood × prior, MLE argmax likelihood = minimise cross-entropy, MAP argmax posterior = loss + regulariser, Bayes average predictions over the whole posteriorThree ways to learn θ from data. Data D (i.i.d. examples), Model p(D given θ) = likelihood, Prior p(θ) = inductive bias, Posterior p(θ given D) ∝ likelihood × prior, MLE argmax likelihood = minimise cross-entropy, MAP argmax posterior = loss + regulariser, Bayes average predictions over the whole posterior

  1. MLE picks \(\hat\theta = \arg\max_\theta p(D \mid \theta)\). With lots of data it is hard to beat; with little data it overfits.
  2. MAP picks \(\arg\max_\theta p(D \mid \theta)\,p(\theta)\). The log-prior is a regulariser: Gaussian prior gives L2, Laplace prior gives L1.
  3. Full Bayes keeps \(p(\theta \mid D)\) and predicts with \(p(y \mid x, D) = \int p(y \mid x, \theta)\,p(\theta \mid D)\,d\theta\), which carries uncertainty about \(\theta\) into the prediction. Exact for small conjugate models; approximated (Laplace, variational inference, ensembles) for neural networks.

Ground level

The likelihood is the data's verdict on the parameters

Flip a coin 10 times and see 7 heads. Under a Bernoulli model with unknown \(p\), the probability of this exact sequence is \(p^7 (1-p)^3\). Read as a function of \(p\) with the data fixed, that is the likelihood \(L(p)\). It is 0.0022 at \(p = 0.7\), 0.0017 at \(p = 0.8\) and 0.00098 at \(p = 0.5\): the data are about 2.3 times more probable if \(p = 0.7\) than if \(p = 0.5\). The likelihood ranks parameter values by how well they predicted what actually happened.

It is not a probability distribution over \(p\): it need not integrate to 1, and multiplying it by a constant changes nothing that matters. Only ratios of likelihoods carry meaning. To turn it into a distribution over \(p\) you need a prior, which is the step Bayes takes and maximum likelihood refuses to take.

For i.i.d. data \(x_1, \dots, x_n\) the likelihood is a product, so we work with its logarithm, the log-likelihood:

\[ \ell(\theta) = \log \prod_{i=1}^n p(x_i \mid \theta) = \sum_{i=1}^n \log p(x_i \mid \theta). \]

The log turns a product of tiny numbers (which underflows in floating point after a few hundred terms; see numerical computing) into a sum (which you can estimate on a minibatch), and it is monotonic, so it has the same maximiser.

Maximum likelihood, three times

Coin. Maximise \(\ell(p) = s \log p + f \log(1-p)\) for \(s\) heads and \(f\) tails: \(\ell'(p) = s/p - f/(1-p) = 0\) gives \(\hat p = s/(s+f)\), the observed frequency. Seven heads in ten gives 0.7. The MLE is the answer you would have guessed, which is reassuring.

Gaussian. For \(x_i \sim \mathcal{N}(\mu, \sigma^2)\) the MLE is the sample mean \(\hat\mu = \bar x\) and the sample variance with divisor \(n\), \(\hat\sigma^2 = \frac1n \sum_i (x_i - \bar x)^2\). The second one is biased: on average it is \(\frac{n-1}{n}\sigma^2\), because \(\bar x\) was fitted to the same data and sits closer to the points than the true \(\mu\) does. With \(n = 5\) and \(\sigma^2 = 4\), the code below measures \(\mathbb{E}[\hat\sigma^2] = 3.21\) against the theoretical 3.20. Dividing by \(n - 1\) removes the bias, yet the biased MLE has the smaller mean squared error (5.80 against 8.08). Unbiased is not the same as better; hold that thought for MAP.

A classifier or language model. A network outputs a categorical distribution \(p_\theta(y \mid \mathbf{x})\). The log-likelihood of a labelled dataset is \(\sum_i \log p_\theta(y_i \mid \mathbf{x}_i)\), and its negative, averaged, is exactly the cross-entropy loss. For a language model, each token is a "label" given the tokens before it, so next-token pre-training is maximum likelihood on the chain-rule factorisation of text. A reported loss of 2.0 nats per token means the model assigns the true next token a geometric-mean probability of \(e^{-2} = 0.135\). Every pre-trained LLM is, statistically speaking, an MLE. Information theory shows the same objective is "minimise the KL divergence from the data distribution to the model".

Where maximum likelihood fails

MLE trusts the data completely, and data can be small, sparse or noisy.

  • Zero counts. Three heads in three flips gives \(\hat p = 1\): the model declares tails impossible. The bigram model of probability foundations gave "the dog ran ." probability exactly 0 because one pair was unseen. In log space that is a loss of \(+\infty\).
  • Overfitting. A flexible model can make the training data arbitrarily likely. A degree-7 polynomial fitted by least squares to 20 noisy points (the figure below) passes close to every point and swings to +39.8 at \(x = 4\), where the truth is \(-0.76\).
  • Overconfidence. A point estimate carries no information about how sure you should be. The same MLE comes from 3/3 and from 3,000/3,000 heads.

MAP: the prior as a regulariser

Bayes' rule over parameters says \(p(\theta \mid D) \propto p(D \mid \theta)\,p(\theta)\). Maximum a posteriori estimation takes the peak:

\[ \hat\theta_\text{MAP} = \arg\max_\theta \Big[\underbrace{\log p(D \mid \theta)}_{\text{fit the data}} + \underbrace{\log p(\theta)}_{\text{stay plausible}}\Big]. \]

The prior adds a term to the objective, and the common priors give the common regularisers:

  • Beta prior on a probability → pseudo-counts. With prior \(\operatorname{Beta}(\alpha, \beta)\), the MAP estimate is \(\frac{s + \alpha - 1}{n + \alpha + \beta - 2}\). A \(\operatorname{Beta}(2, 2)\) prior ("as if I had already seen one head and one tail") turns 3/3 into \(4/5 = 0.8\). This is add-one (Laplace) smoothing, and the Dirichlet version is how \(n\)-gram models stopped assigning zero probability to unseen text.
  • Gaussian prior on weights → L2 regularisation. With \(\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \sigma_p^2 I)\), \(-\log p(\mathbf{w}) = \frac{1}{2\sigma_p^2}\lVert\mathbf{w}\rVert^2\) + const. MAP is least squares plus \(\lambda \lVert \mathbf{w} \rVert^2\) (ridge regression), with \(\lambda = \sigma_\text{noise}^2 / \sigma_p^2\): the less you trust the data relative to the prior, the stronger the penalty. In networks it is weight decay.
  • Laplace prior on weights → L1 regularisation. \(-\log p(\mathbf{w}) \propto \lVert\mathbf{w}\rVert_1\): the lasso (Tibshirani, 1996), which sets many weights to exactly zero because the Laplace density has a sharp peak at 0.
  • Other regularisers read as priors too. Label smoothing behaves like a prior that every class has some probability; early stopping behaves like a Gaussian prior centred on the initialisation; fine-tuning with a KL penalty to a reference model (as in RLHF, see post-training) is a prior centred on the reference policy.

In the polynomial example, the Gaussian prior shrinks the largest weight from 1.67 to 0.72 and the extrapolation at \(x = 4\) from +39.8 to +25.0. Better, but still wrong, and MAP has no way to say so. That is what the next step adds.

Weight decay is not always L2 regularisation

For plain SGD, adding \(\lambda\lVert\mathbf{w}\rVert^2\) to the loss and decaying the weights by a constant factor each step are the same thing. For adaptive optimisers like Adam they are not, because the L2 gradient gets divided by the per-parameter scale. Decoupling the decay from the gradient, as AdamW does (Loshchilov and Hutter), restores the intended prior-like shrinkage and generalises better. See optimisers.

Full Bayes: keep the uncertainty

The Bayesian answer to "what is \(\theta\)?" is not a number but the whole posterior \(p(\theta \mid D)\). To predict, average every plausible model's prediction, weighted by how plausible it is:

\[ p(y \mid \mathbf{x}, D) = \int p(y \mid \mathbf{x}, \theta)\, p(\theta \mid D)\, d\theta . \]

For the coin this is exact and simple. A \(\operatorname{Beta}(\alpha, \beta)\) prior and \(s\) heads in \(n\) flips give the posterior \(\operatorname{Beta}(\alpha + s, \beta + n - s)\), and the predictive probability of heads on the next flip is the posterior mean, \(\frac{\alpha + s}{\alpha + \beta + n}\). With a uniform \(\operatorname{Beta}(1,1)\) prior this is Laplace's rule of succession, \(\frac{s + 1}{n + 2}\). After 3 heads in 3 flips with the \(\operatorname{Beta}(2,2)\) prior: MLE 1.000, MAP 0.800, Bayesian predictive 0.714. The three answers differ most when data are scarce and converge as data grow.

The payoff is calibrated uncertainty. For Bayesian linear regression with a Gaussian prior and Gaussian noise, the posterior over weights is Gaussian in closed form, and the predictive distribution at a new input has variance

\[ \sigma^2_\text{pred}(\mathbf{x}) = \underbrace{\sigma^2_\text{noise}}_{\text{aleatoric}} + \underbrace{\boldsymbol\phi(\mathbf{x})^\top S\, \boldsymbol\phi(\mathbf{x})}_{\text{epistemic}}, \]

where \(S\) is the posterior covariance of the weights. The first term is noise in the data itself, which no amount of data removes (aleatoric uncertainty). The second is uncertainty about the parameters, which shrinks with more data and grows away from it (epistemic uncertainty). In the polynomial example the predictive standard deviation is 0.22 inside the data, 0.66 in the gap at \(x = 0\) and 17.8 at \(x = 4\). The model still extrapolates badly, but it now says so:

-440MLE (least squares)MAP mean ± 2 predictive sdtrue function sin(x)
A degree-7 polynomial fitted to 20 noisy points of sin(x) seen only on [−3, −1] and [1, 3]. The MLE (coral) chases the noise and swings wildly in the gap and beyond the data. The MAP fit (cyan line) is tamer, and the Bayesian predictive band widens exactly where there is no data: the model knows what it does not know.

Approximating the posterior for neural networks

For a network with millions of weights, the posterior has no closed form and its normaliser \(p(D) = \int p(D \mid \theta)\,p(\theta)\,d\theta\) is an integral over millions of dimensions. Every practical method approximates:

Method Idea Cost Reference
Laplace approximation Fit a Gaussian at the MAP, with covariance from the inverse Hessian One trained model + curvature MacKay, 1992; Daxberger et al., 2021
Variational inference Choose \(q(\theta)\) from a simple family; maximise the ELBO About 2× parameters Blundell et al., 2015
MC dropout Keep dropout on at test time; average several passes Several forward passes Gal and Ghahramani, 2016
Deep ensembles Train \(M\) models from different seeds; average \(M\)× training Lakshminarayanan et al., 2017
SWAG Fit a Gaussian to the SGD trajectory's iterates Small overhead Maddox et al., 2019
SG-MCMC Add calibrated noise to SGD so iterates sample the posterior Long runs Mandt et al., 2017 (analysis)

In large comparisons under dataset shift, deep ensembles have been the most reliable practical choice (Ovadia et al., 2019), and Wilson and Izmailov (2020) argue they are best understood as approximate Bayesian model averaging over the posterior's separate modes. For frontier LLMs, full Bayesian treatment is not used in pre-training; uncertainty is instead read from sampling (do several samples agree?) or from the model's own calibrated probabilities, which pre-trained models are surprisingly good at on multiple choice (Kadavath et al., 2022).

How good can an estimate be?

An estimator \(\hat\theta\) is a random variable (it depends on the random data), so it has a bias \(\mathbb{E}[\hat\theta] - \theta\) and a variance, and its mean squared error splits exactly as

\[ \mathbb{E}\big[(\hat\theta - \theta)^2\big] = \operatorname{bias}^2 + \operatorname{Var}(\hat\theta). \]

This is the bias–variance trade-off in its original form. Regularisation and priors add bias and remove variance; the variance-MLE example above and James–Stein shrinkage (for three or more means, shrinking all sample means towards a common point lowers total squared error, whatever the true means are) show that the trade can be strictly worth it.

There is also a floor. The Fisher information \(I(\theta) = \mathbb{E}\big[(\partial_\theta \log p(x \mid \theta))^2\big]\) measures how sharply one observation pins down \(\theta\), and the Cramér–Rao bound says no unbiased estimator from \(n\) i.i.d. observations can have variance below \(1/(n\,I(\theta))\). For a Bernoulli, \(I(p) = 1/(p(1-p))\), so the bound is \(p(1-p)/n\): 0.00420 for \(p = 0.3\), \(n = 50\), and the code measures the MLE's variance at 0.00419. The MLE achieves the bound here exactly, and in general it does so asymptotically, which is the strongest single argument for using it. The Fisher information reappears as the metric behind natural-gradient methods and K-FAC, and as the "importance" weights of elastic weight consolidation in continual learning.

Frequentist and Bayesian: two readings, one maths

A frequentist treats \(\theta\) as fixed and the data as random: an estimator is judged by how it behaves across hypothetical repeated datasets (bias, variance, coverage of confidence intervals). A Bayesian treats the observed data as fixed and \(\theta\) as uncertain: the posterior is the answer. In practice the two agree when data are plentiful: the Bernstein–von Mises theorem says that for well-behaved models the posterior becomes approximately Gaussian, centred on the MLE, with covariance \((n I(\theta))^{-1}\). They differ when data are scarce, priors are strong, or the model is hierarchical. A working ML engineer uses both: Bayesian thinking to design models and priors, frequentist tools to report how much to trust an evaluation.

First principles

Why maximise likelihood? Four independent justifications.

  1. It minimises a divergence from the truth. As \(n \to \infty\), the average log-likelihood \(\frac1n\sum_i \log p_\theta(x_i)\) converges to \(\mathbb{E}_{p_\text{data}}[\log p_\theta(x)]\), and maximising that is the same as minimising \(\operatorname{KL}(p_\text{data} \,\|\, p_\theta)\) (see information theory). MLE finds the model in your family that is closest to reality in this specific sense, even when no member of the family is exactly right.
  2. Consistency and efficiency. Under regularity conditions the MLE converges to the true parameter and, asymptotically, attains the Cramér–Rao bound: no consistent estimator does better in large samples.
  3. Invariance. The MLE of \(g(\theta)\) is \(g(\hat\theta)\): estimate a standard deviation or a variance and you get consistent answers. MAP lacks this, because densities pick up a Jacobian under reparameterisation, so the mode moves (see The maths).
  4. Compression. \(-\log_2 p_\theta(D)\) is the length in bits of the data encoded with the model's code. Maximising likelihood is finding the model that compresses the data best, the view taken by minimum description length and by the claim that language modelling is compression.

Why do we need priors at all? Because data underdetermine every flexible model. Infinitely many functions pass through any finite set of points; something beyond the data must choose among them. That something (architecture, regulariser, initialisation, data augmentation, early stopping) is a prior whether or not you write it as one. Writing it as a probability distribution makes it explicit, tunable and combinable with evidence.

Why is full Bayes intractable, and why it still matters. The posterior needs the normaliser \(p(D)\), an integral over parameter space whose volume grows exponentially with the number of parameters. Methods that avoid it (MCMC samples without normalising; variational inference optimises a bound that doesn't need it; the Laplace approximation replaces the integral with a Gaussian one) are the whole field of approximate inference. And \(p(D)\) itself, the marginal likelihood or evidence, is the principled score for comparing models: it automatically penalises models that could have explained many datasets (Bayesian Occam's razor; MacKay's book in Go deeper has the best account).

History

Least squares to likelihood to Bayesian deep learning

Legendre published least squares in 1805 and Gauss justified it in 1809 by assuming Gaussian errors, which makes least squares the maximum-likelihood fit (the "Gaussian" name comes from this). Laplace's 1774 memoir gave the rule of succession, a Bayesian predictive. R. A. Fisher proposed the method of maximum likelihood in 1912 and named and developed it in On the mathematical foundations of theoretical statistics (1922), which also introduced consistency, efficiency and sufficiency. Cramér and Rao proved the variance bound independently in the 1940s. Tikhonov regularisation (1943, 1963) and ridge regression (Hoerl and Kennard, 1970) added the L2 penalty; the lasso (Tibshirani, 1996) the L1. David MacKay (1992) and Radford Neal (1996) brought Bayesian inference to neural networks, and the deep-learning era revived it with Bayes by Backprop (2015), MC dropout (2016) and deep ensembles (2017).

The maths

Definitions

Data \(D = \{x_1, \dots, x_n\}\) i.i.d. from \(p(x \mid \theta)\), \(\theta \in \mathbb{R}^k\).

  • Likelihood \(L(\theta) = \prod_i p(x_i \mid \theta)\); log-likelihood \(\ell(\theta) = \sum_i \log p(x_i \mid \theta)\).
  • MLE \(\hat\theta_\text{ML} = \arg\max_\theta \ell(\theta)\).
  • Posterior \(p(\theta \mid D) = p(D \mid \theta)\,p(\theta) / p(D)\), with evidence \(p(D) = \int p(D \mid \theta)\,p(\theta)\,d\theta\).
  • MAP \(\hat\theta_\text{MAP} = \arg\max_\theta [\ell(\theta) + \log p(\theta)]\).
  • Posterior predictive \(p(x^* \mid D) = \int p(x^* \mid \theta)\,p(\theta \mid D)\,d\theta\).
  • Score \(s(\theta) = \nabla_\theta \log p(x \mid \theta)\), with \(\mathbb{E}[s] = 0\); Fisher information \(I(\theta) = \mathbb{E}[s s^\top] = -\mathbb{E}[\nabla^2_\theta \log p(x \mid \theta)]\).
Derivation: the Gaussian MLE and the bias of its variance

\(\ell(\mu, \sigma^2) = -\frac{n}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_i (x_i - \mu)^2\).

\(\partial_\mu \ell = \frac{1}{\sigma^2}\sum_i (x_i - \mu) = 0 \Rightarrow \hat\mu = \bar x\).

\(\partial_{\sigma^2} \ell = -\frac{n}{2\sigma^2} + \frac{1}{2\sigma^4}\sum_i (x_i - \hat\mu)^2 = 0 \Rightarrow \hat\sigma^2 = \frac1n \sum_i (x_i - \bar x)^2\).

For the bias, write \(\sum_i (x_i - \bar x)^2 = \sum_i (x_i - \mu)^2 - n(\bar x - \mu)^2\). Taking expectations, \(\mathbb{E}[\cdot] = n\sigma^2 - n \cdot \sigma^2/n = (n-1)\sigma^2\), so \(\mathbb{E}[\hat\sigma^2] = \frac{n-1}{n}\sigma^2\).

Derivation: MAP with a Gaussian prior is ridge regression

Model \(y_i = \boldsymbol\phi_i^\top \mathbf{w} + \varepsilon_i\), \(\varepsilon_i \sim \mathcal{N}(0, \beta^{-1})\), prior \(\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \alpha^{-1} I)\). With design matrix \(\Phi\) (\(n \times k\)):

\[ -\log p(\mathbf{w} \mid D) = \frac{\beta}{2}\lVert \mathbf{y} - \Phi\mathbf{w} \rVert^2 + \frac{\alpha}{2}\lVert\mathbf{w}\rVert^2 + \text{const}. \]

This is a quadratic in \(\mathbf{w}\), so the posterior is Gaussian. Completing the square:

\[ p(\mathbf{w} \mid D) = \mathcal{N}(\mathbf{m}, S), \quad S = (\alpha I + \beta \Phi^\top\Phi)^{-1}, \quad \mathbf{m} = \beta S \Phi^\top \mathbf{y}. \]

The MAP (= posterior mean, for a Gaussian) solves \((\Phi^\top\Phi + \lambda I)\mathbf{w} = \Phi^\top\mathbf{y}\) with \(\lambda = \alpha/\beta\): ridge regression. The predictive at \(\boldsymbol\phi_*\) is \(\mathcal{N}(\boldsymbol\phi_*^\top\mathbf{m},\; \beta^{-1} + \boldsymbol\phi_*^\top S \boldsymbol\phi_*)\). Setting \(\alpha \to 0\) (a flat prior) recovers least squares, the MLE.

Derivation: the Cramér–Rao bound (scalar case)

Let \(\hat\theta\) be unbiased: \(\int \hat\theta(x)\,p(x \mid \theta)\,dx = \theta\). Differentiate in \(\theta\) and use \(\partial_\theta p = p\,\partial_\theta \log p\): \(\mathbb{E}[\hat\theta\, s] = 1\). Since \(\mathbb{E}[s] = 0\), this is \(\operatorname{Cov}(\hat\theta, s) = 1\). Cauchy–Schwarz gives \(1 = \operatorname{Cov}(\hat\theta, s)^2 \le \operatorname{Var}(\hat\theta)\operatorname{Var}(s)\), and for \(n\) i.i.d. observations \(\operatorname{Var}(s) = n I(\theta)\). Hence \(\operatorname{Var}(\hat\theta) \ge 1/(n I(\theta))\).

For the Bernoulli, \(\log p(x \mid p) = x\log p + (1-x)\log(1-p)\), \(s = x/p - (1-x)/(1-p)\), \(I(p) = \mathbb{E}[s^2] = 1/p + 1/(1-p) = 1/(p(1-p))\).

Derivation: the evidence lower bound (ELBO)

For any distribution \(q(\theta)\),

\[ \log p(D) = \underbrace{\mathbb{E}_q[\log p(D \mid \theta)] - \operatorname{KL}(q(\theta) \,\|\, p(\theta))}_{\text{ELBO}(q)} + \operatorname{KL}(q(\theta) \,\|\, p(\theta \mid D)). \]

Proof: expand \(\operatorname{KL}(q \,\|\, p(\theta \mid D)) = \mathbb{E}_q[\log q - \log p(D \mid \theta) - \log p(\theta) + \log p(D)]\) and rearrange. Since KL \(\ge 0\), the ELBO is a lower bound on \(\log p(D)\), and maximising it over \(q\) is the same as minimising the KL from \(q\) to the true posterior, without ever computing \(p(D)\). Variational inference for Bayesian networks and the VAE objective are both this identity. The first term is "fit the data", the second "stay close to the prior": MAP's two terms again, now for a distribution rather than a point.

Why MAP depends on the parameterisation

Let \(\phi = g(\theta)\) be a smooth one-to-one reparameterisation. Densities transform as \(p_\phi(\phi) = p_\theta(g^{-1}(\phi))\,\lvert dg^{-1}/d\phi\rvert\). The likelihood is a function, not a density, so it transforms without the Jacobian, and the MLE moves consistently (\(\hat\phi = g(\hat\theta)\)). The posterior is a density, so its mode moves by more than \(g\): the MAP of \(\phi\) is generally not \(g\) of the MAP of \(\theta\). Posterior means and predictive distributions do not have this problem.

Build it

The coin, the biased variance, and the Cramér–Rao bound:

import numpy as np
rng = np.random.default_rng(0)

# 1) A coin: MLE, MAP and the Bayesian predictive after 3 heads in 3 flips
s, f = 3, 0
a, b = 2.0, 2.0                                   # Beta(2, 2) prior: "one head and one tail already seen"
mle = s / (s + f)
map_ = (s + a - 1) / (s + f + a + b - 2)
pred = (s + a) / (s + f + a + b)                  # posterior mean = P(next flip is heads)
print(f"MLE {mle:.3f}   MAP {map_:.3f}   Bayes predictive {pred:.3f}")

# 2) The MLE of a Gaussian variance is biased by (n-1)/n
sigma2, n = 4.0, 5
x = rng.normal(0, np.sqrt(sigma2), size=(200_000, n))
mle_var = x.var(axis=1)                            # divides by n
unb_var = x.var(axis=1, ddof=1)                    # divides by n-1
print(f"E[MLE var] {mle_var.mean():.3f} (theory {sigma2*(n-1)/n:.3f})   E[unbiased] {unb_var.mean():.3f}")
mse = lambda est: np.mean((est - sigma2)**2)
print(f"MSE of MLE var {mse(mle_var):.3f}   MSE of unbiased var {mse(unb_var):.3f}")

# 3) The Bernoulli MLE meets the Cramer-Rao bound p(1-p)/n
p, n = 0.3, 50
phat = rng.binomial(n, p, size=200_000) / n
print(f"Var(p_hat) {phat.var():.5f}   Cramer-Rao bound {p*(1-p)/n:.5f}")
MLE 1.000   MAP 0.800   Bayes predictive 0.714
E[MLE var] 3.207 (theory 3.200)   E[unbiased] 4.009
MSE of MLE var 5.802   MSE of unbiased var 8.083
Var(p_hat) 0.00419   Cramer-Rao bound 0.00420

MLE versus MAP versus the Bayesian predictive on the polynomial problem in the figure:

import numpy as np
rng = np.random.default_rng(3)

# Data: y = sin(x) + noise, observed only on x in [-3, -1] and [1, 3]
x = np.concatenate([rng.uniform(-3, -1, 10), rng.uniform(1, 3, 10)])
noise_sd = 0.2
y = np.sin(x) + rng.normal(0, noise_sd, x.size)
feats = lambda x: np.stack([x**k for k in range(8)], axis=1)   # degree-7 polynomial
Phi = feats(x)

# MLE (least squares) vs MAP (ridge: Gaussian prior on weights, sd 1)
w_mle = np.linalg.lstsq(Phi, y, rcond=None)[0]
alpha, beta = 1.0, 1 / noise_sd**2               # prior precision, noise precision
S = np.linalg.inv(alpha * np.eye(8) + beta * Phi.T @ Phi)   # posterior covariance
m = beta * S @ Phi.T @ y                                     # posterior mean = MAP
print("|w| MLE", np.abs(w_mle).max().round(2), "  |w| MAP", np.abs(m).max().round(2))

# Bayesian predictive: mean and sd at a point inside the data and one in the gap/outside
for x0 in [2.0, 0.0, 4.0]:
    phi = feats(np.array([x0]))[0]
    mean = phi @ m
    sd = np.sqrt(1 / beta + phi @ S @ phi)
    print(f"x={x0:>4}: true {np.sin(x0):+.3f}  MLE {phi @ w_mle:+9.3f}  MAP {mean:+.3f}  predictive sd {sd:.3f}")
|w| MLE 1.67   |w| MAP 0.72
x= 2.0: true +0.909  MLE    +0.988  MAP +0.918  predictive sd 0.221
x= 0.0: true +0.000  MLE    -1.671  MAP -0.717  predictive sd 0.663
x= 4.0: true -0.757  MLE   +39.829  MAP +25.007  predictive sd 17.812

Things to try

  • Rerun the coin with 300 heads in 300 flips. How far apart are the three estimates now? How large must \(n\) be before the prior shifts the estimate by less than 0.01?
  • Sweep the prior precision alpha over \(10^{-4}, 10^{-2}, 1, 10^2\) in the polynomial problem. Plot training error and the error at \(x = 0\). Where is the bias–variance sweet spot? Then choose alpha by maximising the evidence \(p(D)\) (closed form for this model; Bishop §3.5) and compare.
  • Replace the Bayesian predictive with a "deep ensemble" of polynomial fits on bootstrap resamples of the data. Does the spread of the ensemble widen in the gap the way the predictive sd does?
  • Smooth the bigram model of probability foundations with add-\(k\) for \(k = 0.01, 0.1, 1\) and compute the log-likelihood of a held-out sentence. Which \(k\) wins, and why is \(k = 1\) usually too much for large vocabularies?

Common misconceptions

  • "The likelihood is the probability of the parameters." It is the probability of the data under each parameter value. Only with a prior does it become a distribution over parameters.
  • "Bayesian methods have no hyperparameters." The prior is one, and so are the approximating family and the number of samples. They are just more explicit.
  • "MAP is Bayesian." MAP uses a prior but throws away the posterior's width; it is regularised maximum likelihood. The predictive benefits of Bayes come from averaging.
  • "Unbiased estimators are best." The biased variance MLE above beats the unbiased one on squared error; shrinkage beats the sample mean in three or more dimensions.

Check yourself

Show that minimising mean squared error is maximum likelihood under a Gaussian noise model. What assumption about the noise does it hide?

\(-\log p(y \mid \mathbf{x}, \theta) = \frac{(y - f_\theta(\mathbf{x}))^2}{2\sigma^2} + \frac12\log(2\pi\sigma^2)\). With \(\sigma\) fixed, the second term is a constant and the first is proportional to squared error. Hidden assumption: the noise is Gaussian with the same variance everywhere (homoscedastic). Heavy-tailed or input-dependent noise calls for a different likelihood.

With a Beta(α, β) prior, after s successes in n trials, give the MLE, MAP and posterior mean. Which one is Laplace smoothing?

MLE \(s/n\); MAP \(\frac{s + \alpha - 1}{n + \alpha + \beta - 2}\); posterior mean \(\frac{s + \alpha}{n + \alpha + \beta}\). Add-one smoothing \(\frac{s+1}{n+2}\) is the posterior mean under \(\operatorname{Beta}(1,1)\) (Laplace's rule of succession), or equivalently the MAP under \(\operatorname{Beta}(2,2)\).

Weight decay λ = 0.1 in a regression with noise variance 0.25. What prior standard deviation on the weights does it correspond to?

\(\lambda = \sigma_\text{noise}^2 / \sigma_p^2\), so \(\sigma_p^2 = 0.25 / 0.1 = 2.5\) and \(\sigma_p \approx 1.58\) (for the objective \(\lVert\mathbf{y} - \Phi\mathbf{w}\rVert^2 + \lambda\lVert\mathbf{w}\rVert^2\)). Conventions with a factor \(\frac12\) or a \(1/n\) average change the constant; the scaling argument does not change.

Why does Bayesian predictive uncertainty grow away from the data, and why does a softmax classifier's confidence often not?

The epistemic term \(\boldsymbol\phi^\top S \boldsymbol\phi\) is large in directions of feature space the data did not constrain. A single trained network is a point estimate: nothing in its output measures parameter uncertainty, and ReLU networks in particular become more confident far from the data, as their logits grow linearly.

The Fisher information of a Gaussian mean with known σ is 1/σ². What is the smallest possible variance of an unbiased estimator of μ from n samples, and which estimator achieves it?

\(1/(n I) = \sigma^2 / n\), achieved by the sample mean, which is the MLE. This is the \(\sigma/\sqrt{n}\) standard error of the mean, derived from the information side.

Hard: an LLM is pre-trained by maximum likelihood. Name two ways the MLE objective explains known LLM behaviours.

(1) Mode covering: minimising \(\operatorname{KL}(p_\text{data} \| p_\theta)\) heavily penalises giving low probability to anything in the data, so the model spreads mass over every plausible continuation, including low-quality ones; that is why raw sampling produces degenerate text and decoding truncates the tail (top-\(p\)). (2) Imitation, not preference: MLE reproduces the data distribution, including its errors and its average quality; reaching better than the data needs a different objective (reward models, RL, preference optimisation; see post-training).

Go deeper

Papers

Videos and lectures

Articles and notes

Books

Where this leads