Course contents 03 / 15

03 / 15 · Bayesian Modelling

Bayesian model selection

Comparing models by the probability they gave the data before seeing it: the evidence as an automatic Occam's razor, Bayes factors, choosing a polynomial degree, empirical Bayes, the BIC, and the evidence's dependence on the prior.

On this page 9

Take twenty points xix_i equally spaced on [−1,1][-1, 1], with targets yi=sin⁡(πxi)y_i = \sin(\pi x_i) plus Gaussian noise of standard deviation 0.20.2. Fit polynomials of degree M=0,1,…,9M = 0, 1, \dots, 9 by least squares. Which degree should you keep?

The training error cannot say. Its root mean square never rises with the degree, from 0.6180.618 for a constant to 0.1160.116 for degree 9, because the larger model contains the smaller one and its best fit can only be at least as good. The usual answer is a validation set or cross-validation. It works, but it spends data on the comparison, it is noisy with twenty points, and its cost grows with the number of hyperparameters: a grid over ten of them is out of reach.

The previous note met a quantity that avoids all three problems: the evidence, the probability of the data with the parameters integrated out. It is computed from the training data alone, and it does not prefer bigger models.

The evidence of a model#

A model M\mathcal M is a likelihood p(X∣θ,M)p(X \mid \theta, \mathcal M) together with a prior p(θ∣M)p(\theta \mid \mathcal M). Its evidence, or marginal likelihood, is

p(X∣M)=∫p(X∣θ,M) p(θ∣M) dθ.p(X \mid \mathcal M) = \int p(X \mid \theta, \mathcal M)\, p(\theta \mid \mathcal M)\, d\theta .

The integral is the sum rule over θ\theta followed by the product rule. It is the probability of generating the data from the model when its parameters are first drawn from the prior (Bishop, 2006, Section 3.4).

Apply Bayes’ formula one level up. Models are hypotheses like any other, with prior probabilities p(M)p(\mathcal M), and the data update them:

p(M∣X)=p(X∣M) p(M)∑M′p(X∣M′) p(M′).p(\mathcal M \mid X) = \frac{p(X \mid \mathcal M)\, p(\mathcal M)}{\sum_{\mathcal M'} p(X \mid \mathcal M')\, p(\mathcal M')} .

The likelihood of a model is its evidence, the same integral that normalized the posterior over its parameters. Inference then has two levels (MacKay, 1992). The first is the posterior p(θ∣X,M)p(\theta \mid X, \mathcal M) within a model; the second is the posterior over models, through their evidences. With equal prior probabilities, models are ranked by evidence alone.

In regression a model describes the targets given the inputs, so its evidence is p(y∣X,M)p(y \mid X, \mathcal M): the inputs are conditioned on, not generated. For continuous data the evidence is a density value, not a probability, and it can exceed 1. A model that predicts a single target y=0y = 0 as N(0,0.12)\mathcal N(0, 0.1^2) has evidence 1/(0.12π)=3.991/(0.1\sqrt{2\pi}) = 3.99. Only evidences of the same data in the same units are compared. Measuring yy in units cc times smaller multiplies every model’s evidence by c−nc^{-n}, by the change-of-variables formula applied to each of the nn targets, and leaves their ratios unchanged.

A prediction need not choose. Bayesian model averaging weights every model’s predictive by its posterior probability, by the sum rule over models and the product rule:

p(x∗∣X)=∑Mp(x∗∣X,M) p(M∣X).p(x_* \mid X) = \sum_{\mathcal M} p(x_* \mid X, \mathcal M)\, p(\mathcal M \mid X) .

The evidence averages the likelihood over the prior instead of taking it at the best parameter. By the product rule, as the previous note found for the coin, it is a product of predictions:

p(X∣M)=∏i=1np(xi∣x1,…,xi−1,M).p(X \mid \mathcal M) = \prod_{i=1}^n p(x_i \mid x_1, \dots, x_{i-1}, \mathcal M) .

Each factor is the probability with which the model predicted a point from the ones before it, starting from the prior. A model earns evidence by predicting the data before seeing them; fitting them afterwards earns nothing. The log of a ratio of evidences is therefore a difference of predictive scores (Kass and Raftery, 1995, Section 3.2): a sequential form of validation in which every point is used first for testing and then for fitting.

Why the evidence prefers simple models#

The evidence is a probability distribution over datasets. Sum it over all datasets and exchange the sum with the integral over θ\theta:

∑Xp(X∣M)=∫(∑Xp(X∣θ,M)) p(θ∣M) dθ=∫p(θ∣M) dθ=1,\begin{aligned} \sum_X p(X \mid \mathcal M) &= \int \Big(\sum_X p(X \mid \theta, \mathcal M)\Big)\, p(\theta \mid \mathcal M)\, d\theta \\ &= \int p(\theta \mid \mathcal M)\, d\theta = 1 , \end{aligned}

because the likelihood sums to 1 over datasets for every θ\theta; for continuous data the sum is an integral. A model that can explain many different datasets must spread this unit of probability over all of them, and so gives each one less. A simple model concentrates its probability on the few datasets it can explain. When the data are among them, the simple model wins; when they are not, the flexible one does. This is the Bayesian Occam’s razor (MacKay, 2003, Section 28.1). No penalty is added; it follows from normalization.

Three dice show the effect without an integral. The first has the faces 1 to 6. The second has the faces 1, 2 and 3, each twice. The third has 1 and 2, each three times. One die is picked at random, rolled, and shows a 3. The third die cannot produce it and is ruled out. The other two can, but the second gives a 3 the probability 2/62/6 and the first only 1/61/6. With equal prior probabilities, Bayes’ formula makes the posterior proportional to these likelihoods: 2/32/3 for the second die and 1/31/3 for the first. It can produce fewer outcomes, and it predicted this one better.

Take ten flips of a coin. Model M0\mathcal M_0 says the coin is fair. Model M1\mathcal M_1 says its probability of heads ff is unknown, with a uniform prior. The probabilities the two models give to the number of heads kk are

P(k∣M0)=(10k)2−10,P(k∣M1)=∫01(10k)fk(1−f)10−k df=111.\begin{aligned} P(k \mid \mathcal M_0) &= \binom{10}{k} 2^{-10}, \\ P(k \mid \mathcal M_1) &= \int_0^1 \binom{10}{k} f^k (1 - f)^{10-k}\, df = \frac{1}{11} . \end{aligned}

The integral is the beta function B(k+1,n−k+1)=k! (n−k)!/(n+1)!B(k + 1, n - k + 1) = k!\,(n-k)!/(n+1)! of the conjugate priors note, so

(nk)B(k+1,n−k+1)=n!k! (n−k)!⋅k! (n−k)!(n+1)!=1n+1:\binom{n}{k} B(k + 1, n - k + 1) = \frac{n!}{k!\,(n-k)!} \cdot \frac{k!\,(n-k)!}{(n+1)!} = \frac{1}{n + 1} :

under the uniform prior every count is equally likely.

Figure

The evidence as Occam's razor: a fair coin against any coin

The evidence as Occam's razor: a fair coin against any coinBars for k = 0 to 10: the binomial probabilities of the fair coin, peaking at 0.246 at k = 5, and the flat bars of 0.091 of the flexible model. At k = 5 the fair coin is higher (ratio 2.71), at k = 9 the flexible model is (ratio 9.31).00.10.2M0: the coin is fairM1: uniform prior on its bias f012345678910number of heads k in 10 flips3435 headsM0: 0.246, M1: 0.091K01 = 2.71: the fair coin49 headsM0: 0.0098, M1: 0.091K10 = 9.31: a biased coinThe evidence as Occam's razor: a fair coin against any coinBars for k = 0 to 10: the binomial probabilities of the fair coin, peaking at 0.246 at k = 5, and the flat bars of 0.091 of the flexible model. At k = 5 the fair coin is higher (ratio 2.71), at k = 9 the flexible model is (ratio 9.31).00.10.2M0: the coin is fairM1: uniform prior on its bias f012345678910number of heads k in 10 flips3435 headsM0: 0.246, M1: 0.091K01 = 2.71: the fair coin49 headsM0: 0.0098, M1: 0.091K10 = 9.31: a biased coin
The probability each model gives to the number of heads in 10 flips; each set of bars sums to 1. M₀, a fair coin (amber), concentrates its mass near k = 5. M₁, a uniform prior on the bias (blue), gives every k 1/11. Compare the bars at k = 5 and k = 9.
HeadsP(k∣M0)P(k \mid \mathcal M_0)P(k∣M1)P(k \mid \mathcal M_1)Ratio
k=5k = 5252/1024=0.246252/1024 = 0.2461/11=0.0911/11 = 0.0912.712.71 for the fair coin
k=9k = 910/1024=0.009810/1024 = 0.00981/11=0.0911/11 = 0.0919.319.31 for the biased coin

Five heads favour the fair coin, although M1\mathcal M_1 contains f=0.5f = 0.5 and fits these data exactly as well. The fair coin predicted this outcome; the flexible model only allowed it.

What flexibility costs#

How much does M1\mathcal M_1 pay for its flexibility? When the posterior is a narrow peak, the evidence integral is about the height of the integrand at its peak times its width. In one dimension, take a uniform prior of width Δθ\Delta\theta, so that p(θ^)=1/Δθp(\hat\theta) = 1/\Delta\theta, and a posterior of standard deviation σθ∣X\sigma_{\theta \mid X}. Approximate the peak by a Gaussian bump of height p(X∣θ^) p(θ^)p(X \mid \hat\theta)\, p(\hat\theta) and standard deviation σθ∣X\sigma_{\theta \mid X}; a bump of height 1 integrates to 2π σθ∣X\sqrt{2\pi}\, \sigma_{\theta \mid X}. This is the Laplace approximation in one dimension:

p(X∣M)≈p(X∣θ^) p(θ^) 2π σθ∣X=p(X∣θ^)⋅2π σθ∣XΔθ.\begin{aligned} p(X \mid \mathcal M) &\approx p(X \mid \hat\theta)\, p(\hat\theta)\, \sqrt{2\pi}\, \sigma_{\theta \mid X} \\ &= p(X \mid \hat\theta) \cdot \frac{\sqrt{2\pi}\, \sigma_{\theta \mid X}}{\Delta\theta} . \end{aligned}

The first factor is the best-fit likelihood. The second is MacKay’s Occam factor: the fraction of the prior range that survives the data, at most about 1. A model with many parameters, or with broad priors, pays a factor for each of them.

For 9 heads in 10 under M1\mathcal M_1, with f^=0.9\hat f = 0.9 and a prior range of 1, the width comes from the curvature of the log-likelihood klog⁡f+(n−k)log⁡(1−f)k \log f + (n - k) \log(1 - f). Its second derivative at f^=k/n\hat f = k/n is −k/f^2−(n−k)/(1−f^)2=−n/(f^(1−f^))-k/\hat f^2 - (n-k)/(1 - \hat f)^2 = -n/\big(\hat f(1 - \hat f)\big), and the variance is minus its inverse:

QuantityValue
best-fit likelihood 0.99⋅0.10.9^9 \cdot 0.10.03870.0387
the fair coin’s likelihood 2−102^{-10}0.000980.00098
posterior width f^(1−f^)/n\sqrt{\hat f(1 - \hat f)/n}0.0950.095
Occam factor 2π⋅0.095\sqrt{2\pi} \cdot 0.0950.2380.238
approximate evidence 0.0387⋅0.2380.0387 \cdot 0.2380.00920.0092
exact evidence B(10,2)=1/110B(10, 2) = 1/1100.00910.0091

M1\mathcal M_1 fits forty times better than the fair coin (0.0387/0.00098=39.60.0387/0.00098 = 39.6), which has no parameter and pays no Occam factor. A factor of 1/0.238=4.21/0.238 = 4.2 of that advantage is paid back for flexibility, leaving a ratio of about 9.49.4; the exact evidences give 9.39.3. For linear-Gaussian models the decomposition into fit and Occam factor is exact; Bayesian linear regression derives it.

Bayes factors#

The ratio of the evidences of two models is their Bayes factor:

K10=p(X∣M1)p(X∣M0).K_{10} = \frac{p(X \mid \mathcal M_1)}{p(X \mid \mathcal M_0)} .

Dividing Bayes’ formula for M1\mathcal M_1 by the one for M0\mathcal M_0 cancels the common denominator, so the posterior odds are the Bayes factor times the prior odds:

p(M1∣X)p(M0∣X)=K10⋅p(M1)p(M0).\frac{p(\mathcal M_1 \mid X)}{p(\mathcal M_0 \mid X)} = K_{10} \cdot \frac{p(\mathcal M_1)}{p(\mathcal M_0)} .

Unlike a p-value, a Bayes factor can support the simpler model as well as reject it. Kass and Raftery (1995), adapting Jeffreys, read it on this scale:

K10K_{10}2log⁡K102 \log K_{10}Evidence against M0\mathcal M_0
1 to 30 to 2not worth more than a bare mention
3 to 202 to 6positive
20 to 1506 to 10strong
above 150above 10very strong

Nine heads in ten give K10=9.3K_{10} = 9.3, positive evidence for a biased coin. With equal prior odds, p(M1∣X)=9.3/10.3=0.903p(\mathcal M_1 \mid X) = 9.3/10.3 = 0.903. Under M1\mathcal M_1 the next flip is heads with probability (k+1)/(n+2)=10/12(k + 1)/(n + 2) = 10/12, the rule of succession; under M0\mathcal M_0 with 1/21/2. Model averaging predicts heads with probability

0.903⋅1012+0.097⋅12=0.801.0.903 \cdot \frac{10}{12} + 0.097 \cdot \frac12 = 0.801 .

Five heads in ten give K01=2.71K_{01} = 2.71 for the fair coin, barely worth a mention. Evidence for the simpler hypothesis accumulates slowly: 50 heads in 100 flips give K01=8.04K_{01} = 8.04, still only positive. The flexible model is never refuted by data it can also explain. It only loses its Occam factor, which shrinks like 1/n1/\sqrt n, because the posterior width f^(1−f^)/n\sqrt{\hat f(1 - \hat f)/n} does.

When one of the models generated the data, the comparison is right on average. Averaged over datasets from the true model M1\mathcal M_1, the log Bayes factor is, by the definition of the KL divergence,

EX∼p(X∣M1)log⁡p(X∣M1)p(X∣M0)=DKL(p(⋅∣M1) ∥ p(⋅∣M0)),\mathbb E_{X \sim p(X \mid \mathcal M_1)} \log \frac{p(X \mid \mathcal M_1)}{p(X \mid \mathcal M_0)} = D_{\mathrm{KL}}\big(p(\cdot \mid \mathcal M_1) \,\|\, p(\cdot \mid \mathcal M_0)\big) ,

which is never negative (Bishop, 2006, Section 3.4). On a single dataset the wrong model can still win.

The evidence of a linear-Gaussian model#

For regression the evidence has a closed form whenever the weights have a Gaussian prior and the noise is Gaussian. Let Φ\Phi be the N×(M+1)N \times (M+1) design matrix of a polynomial of degree MM, with columns 1,x,…,xM1, x, \dots, x^M. Write the model as

y=Φw+ε,w∼N(0,α−1I),ε∼N(0,β−1I),\begin{aligned} y &= \Phi w + \varepsilon, \\ w &\sim \mathcal N(0, \alpha^{-1} I), \\ \varepsilon &\sim \mathcal N(0, \beta^{-1} I), \end{aligned}

with ww and ε\varepsilon independent, α\alpha the prior precision of each weight and β\beta the noise precision. Then yy is an affine function of Gaussian vectors, hence Gaussian, with mean 0 and covariance ΦCov⁡(w)Φ⊤+Cov⁡(ε)\Phi \operatorname{Cov}(w) \Phi^\top + \operatorname{Cov}(\varepsilon):

p(y∣α,β)=N(y∣0, C),C=α−1ΦΦ⊤+β−1I.\begin{aligned} p(y \mid \alpha, \beta) &= \mathcal N\big(y \mid 0,\ C\big), \\ C &= \alpha^{-1} \Phi \Phi^\top + \beta^{-1} I . \end{aligned}

No posterior was needed: the weights were integrated out by the rule for affine maps. Taking the logarithm of the Gaussian density,

log⁡p(y∣α,β)=−12 y⊤C−1y⏟data fit−12log⁡det⁡C⏟complexity−N2log⁡2π.\begin{aligned} \log p(y \mid \alpha, \beta) ={}& \underbrace{-\tfrac12\, y^\top C^{-1} y}_{\text{data fit}} \\ &\underbrace{-\tfrac12 \log \det C}_{\text{complexity}} - \tfrac N2 \log 2\pi . \end{aligned}

The two terms are the razor in matrix form. Adding a column vv to Φ\Phi adds the rank-one term α−1vv⊤\alpha^{-1} v v^\top to CC: the model can now produce data in one more direction. The fit term can only improve, because a larger CC in the positive semidefinite order has a smaller inverse, so y⊤C−1yy^\top C^{-1} y cannot grow. And det⁡C\det C grows by the factor 1+α−1v⊤C−1v>11 + \alpha^{-1} v^\top C^{-1} v > 1, by the determinant lemma: the same unit of probability is spread over a larger volume of datasets. The next note derives the posterior of the weights and an equivalent form of this evidence in weight space.

Choosing the polynomial degree by the evidence#

Back to the twenty points of the opening, with the prior precision α=1\alpha = 1 on the weights and the noise precision β=25\beta = 25 of the true standard deviation 0.20.2. The table compares the training error, the log evidence, the BIC of a later section, and the error against the noise-free curve on a fine grid, which no method sees:

Degree MMTraining RMSELog evidenceBICError against the true curve
00.618−84.8443.510.708
10.411−34.4530.190.459
20.406−35.4132.670.463
30.132−4.18−9.380.147
40.131−5.04−6.480.146
50.121−5.19−6.850.123
60.120−5.74−4.200.123
70.119−6.17−1.420.123
80.116−6.580.420.129
90.116−6.773.380.130
Figure

The evidence of polynomial models

The evidence of polynomial modelsLeft, 20 points around a sine and three curves: a line (M = 1), a cubic (M = 3) that follows the data, and a degree-9 polynomial almost on top of the cubic. Right, the log evidence by degree M = 1 to 9 for α = 1 and α = 0.01: a sharp rise to M = 3 and a slow decline after it, steeper for the broader prior.data and posterior meansM = 1M = 3M = 9-101-101xlog evidenceα = 1α = 0.010−10−20−30−40peak at M = 3123456789degree MM = 0: −84.8, off the scaleThe evidence of polynomial modelsLeft, 20 points around a sine and three curves: a line (M = 1), a cubic (M = 3) that follows the data, and a degree-9 polynomial almost on top of the cubic. Right, the log evidence by degree M = 1 to 9 for α = 1 and α = 0.01: a sharp rise to M = 3 and a slow decline after it, steeper for the broader prior.data and posterior meansM = 1M = 3M = 9-101-101xlog evidenceα = 1α = 0.010−10−20−30−40peak at M = 3123456789degree MM = 0: −84.8, off the scale
Twenty points of sin(πx) plus noise of sd 0.2; prior N(0, α⁻¹I) on the weights, noise precision β = 25. Left: posterior means at α = 1 for degrees 1, 3 and 9. Right: log evidence by degree, peaking at M = 3 (−4.18 at α = 1, −8.84 at α = 0.01); the broader prior falls faster.

The evidence jumps by 31 nats between degrees 2 and 3, where the cubic first captures the shape of the sine. The even degree 2 adds almost nothing, because sin⁡(πx)\sin(\pi x) is odd and x2x^2 is even, so on the symmetric grid the new column is orthogonal to the signal, and it is penalized for it. After degree 3 every extra weight improves the fit a little and costs an Occam factor, and the evidence falls slowly. The peak is at M=3M = 3, as in similar experiments in Bishop (2006, Section 3.5.1) and in the 4F13 lectures: too simple models miss most of the data, too complex ones spread their probability too thin.

Two cautions on reading it. The differences beyond the peak are small: degree 5 has e−1.0e^{-1.0} times the evidence of degree 3, 2log⁡K=2.02 \log K = 2.0, not worth more than a bare mention. And the evidence ranks models by how probable they are, which is a different question from which one predicts best. The error against the true curve is slightly lower at degrees 5 to 7, because the sine is not a polynomial and more terms approximate it better. The evidence prefers the simplest model that explains the data to within the noise.

Empirical Bayes: fitting hyperparameters by the evidence#

The hyperparameters α\alpha and β\beta were fixed above. A Bayesian could give them a prior too, a hyperprior, and integrate them out:

p(y)=∬p(y∣α,β) p(α,β) dα dβ.p(y) = \iint p(y \mid \alpha, \beta)\, p(\alpha, \beta)\, d\alpha\, d\beta .

This is full Bayesian inference: every unknown, weights and hyperparameters alike, gets a posterior. The joint factorizes by the product rule, with yy depending on α\alpha only through ww, and Bayes’ formula gives

p(w,α,β∣y)∝p(y∣w,β) p(w∣α) p(α,β).p(w, \alpha, \beta \mid y) \propto p(y \mid w, \beta)\, p(w \mid \alpha)\, p(\alpha, \beta) .

A prediction at a new input x∗x_* sums over all three unknowns by the sum rule. The product rule splits the integrand, and the new target is independent of yy given ww and β\beta:

p(t∗∣y)=∭p(t∗∣w,β,y) p(w,α,β∣y) dw dα dβ=∭p(t∗∣w,β) p(w,α,β∣y) dw dα dβ,\begin{aligned} p(t_* \mid y) &= \iiint p(t_* \mid w, \beta, y)\, p(w, \alpha, \beta \mid y)\, dw\, d\alpha\, d\beta \\ &= \iiint p(t_* \mid w, \beta)\, p(w, \alpha, \beta \mid y)\, dw\, d\alpha\, d\beta , \end{aligned}

with the conditioning on x∗x_* left implicit. This hierarchical model is rarely tractable in closed form. The prediction is then averaged over draws from the joint posterior, made by Monte Carlo as the Gibbs sampler does for a mean and a precision, or over a variational approximation qq of it. Empirical Bayes, or type-II maximum likelihood, replaces the integral over the hyperparameters by its peak: choose the hyperparameters that maximize the evidence,

(α^,β^)=arg⁡max⁡α,β p(y∣α,β)=arg⁡max⁡α,β∫p(y∣w,β) p(w∣α) dw,\begin{aligned} (\hat\alpha, \hat\beta) &= \arg\max_{\alpha, \beta}\ p(y \mid \alpha, \beta) \\ &= \arg\max_{\alpha, \beta} \int p(y \mid w, \beta)\, p(w \mid \alpha)\, dw , \end{aligned}

then use the posterior p(w∣y,α^,β^)p(w \mid y, \hat\alpha, \hat\beta). This is maximum likelihood one level up, with the weights integrated out. It is justified when the evidence is sharply peaked in the hyperparameters, which is usual: there are few of them, and all the data inform them.

Why integrate the weights out instead of maximizing over ww and α\alpha together? The joint density p(y∣w,β) p(w∣α)p(y \mid w, \beta)\, p(w \mid \alpha) at w=0w = 0 grows without bound as α→∞\alpha \to \infty, because the prior N(0,α−1I)\mathcal N(0, \alpha^{-1} I) becomes an ever higher spike at zero: its log-density at the centre is d2log⁡(α/2π)\frac d2 \log(\alpha / 2\pi) for dd weights. For the cubic, d=4d = 4, it rises by 2log⁡100=9.22 \log 100 = 9.2 nats for every hundredfold increase of α\alpha, and has no maximum. Integrating ww out is what makes the problem well posed (Vetrov and Kropotov, 2015, lecture 3).

For the polynomial models the evidence is the Gaussian density of the previous section, a function of two numbers, and a general-purpose optimizer maximizes it:

Degreeα^\hat\alphaβ^\hat\betanoise sd 1/β^1/\sqrt{\hat\beta}log evidence, fixed → fitted
30.4180.41846.046.00.1470.147−4.18→−2.13-4.18 \to -2.13
90.6710.67144.444.40.1500.150−6.77→−5.86-6.77 \to -5.86

Here “fixed” means α=1\alpha = 1, β=25\beta = 25. Fitting the hyperparameters raises both evidences and leaves the cubic ahead. The next note derives a fixed-point iteration that finds the same maximum faster, and reads off from it how many parameters the data actually determine.

Empirical Bayes uses the data twice, to set the prior and then to update it, and so understates uncertainty about the hyperparameters. With many observations per hyperparameter the error is small. With a hyperparameter per weight, as in the relevance vector machine, it is not, and the evidence can then overfit.

The three ways to treat the two levels differ in what they integrate and what they maximize:

ApproachIntegrated outMaximizedExample
Point estimate (MAP)nothingww, with α\alpha, β\beta fixedridge regression
Empirical Bayeswwα\alpha, β\betathe table above; the RVM
Full Bayesww, α\alpha, β\betanothinga hyperprior, with sampling or VI

The BIC approximation#

When the evidence has no closed form, it can be approximated by the same peak-times-width argument in dd dimensions. The Laplace approximation, later in the course, replaces the integrand by a Gaussian around its maximum θ^\hat\theta and integrates that. With HH the Hessian of −log⁡(p(X∣θ) p(θ))-\log\big(p(X \mid \theta)\, p(\theta)\big) at θ^\hat\theta, it gives

log⁡p(X∣M)≈log⁡p(X∣θ^)+log⁡p(θ^)+d2log⁡2π−12log⁡det⁡H.\begin{aligned} \log p(X \mid \mathcal M) \approx{}& \log p(X \mid \hat\theta) + \log p(\hat\theta) \\ &+ \frac d2 \log 2\pi - \frac12 \log \det H . \end{aligned}

For nn i.i.d. points the Hessian is a sum of nn per-point terms plus the prior’s curvature, which does not grow. By the law of large numbers the sum is about nn times its expectation, H≈n I1(θ^)H \approx n\, I_1(\hat\theta), with I1I_1 the Fisher information of one point, so log⁡det⁡H=dlog⁡n+log⁡det⁡I1\log \det H = d \log n + \log \det I_1. Keeping only the terms that grow with nn,

log⁡p(X∣M)=log⁡p(X∣θ^)−d2log⁡n+O(1).\log p(X \mid \mathcal M) = \log p(X \mid \hat\theta) - \frac d2 \log n + O(1) .

Multiplied by −2-2, this is the Bayesian information criterion, or Schwarz criterion, smaller being better (Bishop, 2006, Section 4.4.1):

BIC=−2log⁡p(X∣θ^)+dlog⁡n.\mathrm{BIC} = -2 \log p(X \mid \hat\theta) + d \log n .

The Machine Learning course uses it to choose the number of mixture components. The derivation shows what it drops: the prior and the curvature, terms of order 1 that do not grow with nn.

For 9 heads in 10 under M1\mathcal M_1, the three values of the log evidence are:

Log evidence
exact, log⁡(1/110)\log(1/110)−4.700-4.700
Laplace−4.687-4.687
BIC, −3.251−12log⁡10-3.251 - \frac12 \log 10−4.402-4.402

For the polynomials, with d=M+2d = M + 2 (the weights and the noise variance), the BIC also picks degree 3. It needs only the maximum likelihood fit and can be used for any model. It is reliable when nn is large compared with dd and the model is regular, with a unique interior maximum and a full-rank Hessian; mixtures and neural networks break these conditions. It ignores the prior entirely, which is both its robustness and its limitation.

Where it breaks: the evidence depends on the prior width#

The posterior forgets the prior as data accumulate; the evidence does not. The Occam factor is the ratio of the posterior width to the prior width, so a prior twice as broad halves the evidence of every parameter it governs, however many data there are. The same twenty points, with broader priors on the weights:

Prior precision α\alphaM=1M = 1M=3M = 3M=5M = 5M=9M = 9
11−34.5−4.2−5.2−6.8
0.010.01−38.8−8.8−13.6−18.3
0.00010.0001−43.4−18.0−27.3−38.6

The cubic fit hardly changes between these priors, since the data determine its four weights. Once the prior is broad compared with the posterior, each tenfold broadening of its standard deviation costs log⁡10=2.3\log 10 = 2.3 nats per weight. From α=0.01\alpha = 0.01 to 0.00010.0001 the cubic loses 9.2=4⋅2.39.2 = 4 \cdot 2.3 nats and degree 9 loses 20.320.3. The gap between degrees 3 and 9 widens from 2.6 nats at α=1\alpha = 1 to 20.6.

In the limit of a flat prior, α→0\alpha \to 0, the evidence of every model with parameters goes to zero, and the model without parameters always wins. An improper prior, such as a uniform density cc on the whole real line, leaves the evidence undefined: the constant cc is arbitrary and multiplies the evidence, while it cancels from the posterior, which is often still fine (Bishop, 2006, Section 3.4).

Priors used for model comparison must therefore be proper and set on the scale of the problem. Here, inputs scaled to [−1,1][-1, 1] and outputs of order 1 make α=1\alpha = 1 reasonable, and hyperparameters that set the scale are better fitted by empirical Bayes than guessed. Conclusions should be reported with their sensitivity to the prior. When they change, held-out likelihood or cross-validation, which depend on the prior only through the posterior, are the safer criterion.

A related failure shows in the product of predictions. Its first factors are predictions made from the prior alone, so a model with a poor prior that adapts quickly to data can have a low evidence and still generalize well. Scoring only the later predictions, given the first part of the data, removes most of this dependence (Murphy, 2023, Section 3.8). Computing the evidence is also harder than computing the posterior. Outside conjugate and linear-Gaussian models it needs the Laplace approximation, a variational bound or careful sampling (Murphy, 2023, Section 3.8.3). One shortcut fails. Bayes’ formula gives Ep(θ∣X)[1/p(X∣θ)]=1/p(X)\mathbb E_{p(\theta \mid X)}\big[1/p(X \mid \theta)\big] = 1/p(X), so averaging 1/p(X∣θ)1/p(X \mid \theta) over posterior samples seems to estimate the evidence. The average is dominated by rare parameters with a tiny likelihood, which posterior samples almost never reach, and this harmonic-mean estimator can have infinite variance.

What you should remember#

  • The evidence p(X∣M)=∫p(X∣θ) p(θ) dθp(X \mid \mathcal M) = \int p(X \mid \theta)\, p(\theta)\, d\theta is the likelihood of a model, and p(M∣X)∝p(X∣M) p(M)p(\mathcal M \mid X) \propto p(X \mid \mathcal M)\, p(\mathcal M).
  • It is a distribution over datasets and a product of one-step predictions: flexible models spread their probability thin.
  • Evidence ≈ best fit × Occam factor, the posterior width over the prior width per parameter.
  • Bayes factors turn prior odds into posterior odds; they can support the simpler model, but slowly.
  • Linear-Gaussian: y∼N(0,α−1ΦΦ⊤+β−1I)y \sim \mathcal N(0, \alpha^{-1} \Phi\Phi^\top + \beta^{-1} I); on twenty noisy points of a sine the evidence peaks at degree 3. Empirical Bayes maximizes it over α\alpha, β\beta.
  • BIC =−2log⁡p(X∣θ^)+dlog⁡n= -2 \log p(X \mid \hat\theta) + d \log n drops the prior. The evidence itself falls with every broadening of the prior.

Code#

The coin’s Bayes factors and model average, the Occam factor with the Laplace and BIC approximations, the evidence as a product of predictions, the evidence of polynomial models with its peak, the effect of the prior width, empirical Bayes by a numerical optimizer, and the unbounded joint maximum. Seeds are fixed; the script runs in about a second, and exact numbers can differ in the last digit across platforms and library versions.

import numpy as np
from scipy import optimize, special, stats

# Occam's razor on a coin: M0 says the coin is fair, M1 gives its bias a uniform prior.
# The evidence of a sequence with k heads in n flips: 2^-n under M0, B(k + 1, n - k + 1) under M1.
def log_ev_fair(k, n): return -n * np.log(2)
def log_ev_uniform(k, n): return special.betaln(k + 1, n - k + 1)
for k, n in ((5, 10), (9, 10), (50, 100)):
    bf = np.exp(log_ev_uniform(k, n) - log_ev_fair(k, n))      # the Bayes factor of M1 against M0
    print(k, n, round(bf, 3), round(1 / bf, 2))
# 5 10 0.369 2.71 | 9 10 9.309 0.11 | 50 100 0.124 8.04

# model averaging after 9 heads in 10, equal prior odds
p1 = 9.309 / 10.309
print(round(p1, 3), round(p1 * 10 / 12 + (1 - p1) * 0.5, 3))   # 0.903 0.801

# best-fit likelihood x Occam factor, and the Laplace and BIC approximations, for M1 with 9 heads in 10
k, n = 9, 10
th = k / n
log_fit = k * np.log(th) + (n - k) * np.log(1 - th)            # log p(D | theta_hat)
sd = np.sqrt(th * (1 - th) / n)                                 # posterior width from the curvature
print(round(np.exp(log_fit), 4), round(np.sqrt(2 * np.pi) * sd, 3))           # 0.0387 0.238
print(round(log_ev_uniform(k, n), 3), round(log_fit + 0.5 * np.log(2 * np.pi) + np.log(sd), 3),
      round(log_fit - 0.5 * np.log(n), 3))                      # -4.7 -4.687 -4.402: exact, Laplace, BIC

# the evidence is the product of one-step-ahead predictions
seq = np.array([1] * 9 + [0])
a = b = 1.0
lp = 0.0
for x in seq:
    lp += np.log(a / (a + b) if x else b / (a + b))
    a, b = a + x, b + 1 - x
print(np.isclose(lp, log_ev_uniform(9, 10)))                    # True

# polynomial regression: y = Phi w + noise, w ~ N(0, I / alpha), noise ~ N(0, 1 / beta)
rng = np.random.default_rng(0)
N = 20
x = np.linspace(-1, 1, N)
y = np.round(np.sin(np.pi * x) + 0.2 * rng.normal(size=N), 3)
x_test = np.linspace(-1, 1, 1001)

def design(x, M): return np.vander(x, M + 1, increasing=True)  # columns 1, x, ..., x^M

def log_evidence(Phi, y, alpha, beta):
    """log N(y | 0, C) with C = Phi Phi^T / alpha + I / beta, by a Cholesky factor."""
    C = Phi @ Phi.T / alpha + np.eye(len(y)) / beta
    L = np.linalg.cholesky(C)
    z = np.linalg.solve(L, y)
    return -0.5 * z @ z - np.log(np.diag(L)).sum() - 0.5 * len(y) * np.log(2 * np.pi)

print('M  train-rms  log-ev  BIC  test-rms')
for M in range(10):
    Phi = design(x, M)
    w = np.linalg.lstsq(Phi, y, rcond=None)[0]                  # maximum likelihood fit
    rss = ((y - Phi @ w) ** 2).sum()
    log_lik = -N / 2 * np.log(2 * np.pi * rss / N) - N / 2       # at the ML noise variance rss / N
    bic = -2 * log_lik + (M + 2) * np.log(N)                     # M + 1 weights and the noise variance
    test = np.sqrt(((design(x_test, M) @ w - np.sin(np.pi * x_test)) ** 2).mean())
    print(M, round(np.sqrt(rss / N), 3), round(log_evidence(Phi, y, 1.0, 25.0), 2), round(bic, 2), round(test, 3))
# 0 0.618 -84.84 43.51 0.708
# 1 0.411 -34.45 30.19 0.459
# 2 0.406 -35.41 32.67 0.463
# 3 0.132 -4.18 -9.38 0.147     <- the evidence and BIC peak at degree 3
# 4 0.131 -5.04 -6.48 0.146
# 5 0.121 -5.19 -6.85 0.123
# 6 0.12 -5.74 -4.2 0.123
# 7 0.119 -6.17 -1.42 0.123
# 8 0.116 -6.58 0.42 0.129
# 9 0.116 -6.77 3.38 0.13

# the evidence depends on the prior width: the same models with broader priors on the weights
for alpha in (1.0, 0.01, 0.0001):
    print(alpha, [round(float(log_evidence(design(x, M), y, alpha, 25.0)), 1) for M in (1, 3, 5, 9)])
# 1.0 [-34.5, -4.2, -5.2, -6.8] | 0.01 [-38.8, -8.8, -13.6, -18.3] | 0.0001 [-43.4, -18.0, -27.3, -38.6]

# empirical Bayes: maximize the evidence over log alpha and log beta with a general-purpose optimizer
for M in (3, 9):
    Phi = design(x, M)
    res = optimize.minimize(lambda p: -log_evidence(Phi, y, *np.exp(p)), [0.0, 0.0], method='Nelder-Mead',
                            options=dict(xatol=1e-9, fatol=1e-12, maxiter=4000))
    al, be = np.exp(res.x)
    print(M, round(al, 3), round(be, 2), round(1 / np.sqrt(be), 3), round(-res.fun, 2))
# 3 0.418 46.03 0.147 -2.13
# 9 0.671 44.44 0.15 -5.86

# maximizing the joint p(y, w | alpha) over w and alpha instead has no maximum: at w = 0 it grows like 2 log alpha
Phi = design(x, 3)
for alpha in (1e2, 1e4, 1e6):
    w0 = np.zeros(4)
    print(alpha, round(stats.norm.logpdf(y, Phi @ w0, 0.2).sum() + stats.norm.logpdf(w0, 0, alpha ** -0.5).sum(), 1))
# 100.0 -76.5 | 10000.0 -67.3 | 1000000.0 -58.1

Next#

The evidence of a polynomial model was a Gaussian density of the targets, obtained without ever writing down the posterior of the weights. The next note derives that posterior: for a linear model with Gaussian prior and noise, the posterior over the weights is Gaussian, its mean is the ridge solution, and its covariance gives a predictive distribution whose width grows away from the data. It then writes the evidence in weight space, splits it exactly into fit and Occam factor, and turns its maximization into a fixed-point iteration.

References#

  • D. P. Vetrov, D. A. Kropotov. Bayesian Methods in Machine Learning (in Russian). Lecture course, Moscow State University, 2015. Lecture 3, slides (Bayesian model selection, the evidence, why the hyperparameters are fitted to the evidence and not to the joint density).
  • Bayesian Methods in Machine Learning (in Russian). Lecture course, HSE University, 2021. Lecture notes, lecture 3 (Occam’s razor and falsifiability, the evidence maximization principle).
  • Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 2.
  • D. J. C. MacKay. Bayesian Interpolation. Neural Computation, 4(3), 415–447, 1992. Section 2 (the two levels of inference, the evidence and the Occam factor).
  • D. J. C. MacKay. Information Theory, Inference, and Learning Algorithms. Cambridge University Press, 2003. Section 28.1 (Occam’s razor, the evidence and the Occam factor).
  • C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 3.4 (Bayesian model comparison), Section 3.5.1 (the evidence of polynomial models), Section 4.4.1 (model comparison and BIC).
  • K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 3.8 (model selection: Bayesian model selection and averaging, estimating the marginal likelihood, its connection with cross-validation, the conditional marginal likelihood).
  • Cambridge 4F13 Probabilistic Machine Learning, 2025/26. Lectures “Bayesian inference and prediction in finite regression models” and “Marginal likelihood”; “Discrete binary distributions” (a fair and a bent coin compared by their evidence).
  • R. E. Kass, A. E. Raftery. Bayes Factors. Journal of the American Statistical Association, 90(430), 773–795, 1995. Section 3.2 (interpretation, the scale of evidence, Bayes factors as predictive scores).