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.
Conjugate priors and the exponential family · Least squares · Regularization · The multivariate Gaussian
On this page 9
Take twenty points equally spaced on , with targets plus Gaussian noise of standard deviation . Fit polynomials of degree by least squares. Which degree should you keep?
The training error cannot say. Its root mean square never rises with the degree, from for a constant to 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 is a likelihood together with a prior . Its evidence, or marginal likelihood, is
The integral is the sum rule over 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 , and the data update them:
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 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 : 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 as has evidence . Only evidences of the same data in the same units are compared. Measuring in units times smaller multiplies every model’s evidence by , by the change-of-variables formula applied to each of the 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:
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:
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 :
because the likelihood sums to 1 over datasets for every ; 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 and the first only . With equal prior probabilities, Bayes’ formula makes the posterior proportional to these likelihoods: for the second die and for the first. It can produce fewer outcomes, and it predicted this one better.
Take ten flips of a coin. Model says the coin is fair. Model says its probability of heads is unknown, with a uniform prior. The probabilities the two models give to the number of heads are
The integral is the beta function of the conjugate priors note, so
under the uniform prior every count is equally likely.
The evidence as Occam's razor: a fair coin against any coin
| Heads | Ratio | ||
|---|---|---|---|
| for the fair coin | |||
| for the biased coin |
Five heads favour the fair coin, although contains 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 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 , so that , and a posterior of standard deviation . Approximate the peak by a Gaussian bump of height and standard deviation ; a bump of height 1 integrates to . This is the Laplace approximation in one dimension:
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 , with and a prior range of 1, the width comes from the curvature of the log-likelihood . Its second derivative at is , and the variance is minus its inverse:
| Quantity | Value |
|---|---|
| best-fit likelihood | |
| the fair coin’s likelihood | |
| posterior width | |
| Occam factor | |
| approximate evidence | |
| exact evidence |
fits forty times better than the fair coin (), which has no parameter and pays no Occam factor. A factor of of that advantage is paid back for flexibility, leaving a ratio of about ; the exact evidences give . 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:
Dividing Bayes’ formula for by the one for cancels the common denominator, so the posterior odds are the Bayes factor times the prior odds:
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:
| Evidence against | ||
|---|---|---|
| 1 to 3 | 0 to 2 | not worth more than a bare mention |
| 3 to 20 | 2 to 6 | positive |
| 20 to 150 | 6 to 10 | strong |
| above 150 | above 10 | very strong |
Nine heads in ten give , positive evidence for a biased coin. With equal prior odds, . Under the next flip is heads with probability , the rule of succession; under with . Model averaging predicts heads with probability
Five heads in ten give for the fair coin, barely worth a mention. Evidence for the simpler hypothesis accumulates slowly: 50 heads in 100 flips give , still only positive. The flexible model is never refuted by data it can also explain. It only loses its Occam factor, which shrinks like , because the posterior width does.
When one of the models generated the data, the comparison is right on average. Averaged over datasets from the true model , the log Bayes factor is, by the definition of the KL divergence,
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 be the design matrix of a polynomial of degree , with columns . Write the model as
with and independent, the prior precision of each weight and the noise precision. Then is an affine function of Gaussian vectors, hence Gaussian, with mean 0 and covariance :
No posterior was needed: the weights were integrated out by the rule for affine maps. Taking the logarithm of the Gaussian density,
The two terms are the razor in matrix form. Adding a column to adds the rank-one term to : the model can now produce data in one more direction. The fit term can only improve, because a larger in the positive semidefinite order has a smaller inverse, so cannot grow. And grows by the factor , 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 on the weights and the noise precision of the true standard deviation . 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 | Training RMSE | Log evidence | BIC | Error against the true curve |
|---|---|---|---|---|
| 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 |
| 4 | 0.131 | −5.04 | −6.48 | 0.146 |
| 5 | 0.121 | −5.19 | −6.85 | 0.123 |
| 6 | 0.120 | −5.74 | −4.20 | 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.130 |
The evidence of polynomial models
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 is odd and 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 , 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 times the evidence of degree 3, , 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 and were fixed above. A Bayesian could give them a prior too, a hyperprior, and integrate them out:
This is full Bayesian inference: every unknown, weights and hyperparameters alike, gets a posterior. The joint factorizes by the product rule, with depending on only through , and Bayes’ formula gives
A prediction at a new input sums over all three unknowns by the sum rule. The product rule splits the integrand, and the new target is independent of given and :
with the conditioning on 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 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,
then use the posterior . 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 and together? The joint density at grows without bound as , because the prior becomes an ever higher spike at zero: its log-density at the centre is for weights. For the cubic, , it rises by nats for every hundredfold increase of , and has no maximum. Integrating 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 | noise sd | log evidence, fixed → fitted | ||
|---|---|---|---|---|
| 3 | ||||
| 9 |
Here “fixed” means , . 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:
| Approach | Integrated out | Maximized | Example |
|---|---|---|---|
| Point estimate (MAP) | nothing | , with , fixed | ridge regression |
| Empirical Bayes | , | the table above; the RVM | |
| Full Bayes | , , | nothing | a 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 dimensions. The Laplace approximation, later in the course, replaces the integrand by a Gaussian around its maximum and integrates that. With the Hessian of at , it gives
For i.i.d. points the Hessian is a sum of per-point terms plus the prior’s curvature, which does not grow. By the law of large numbers the sum is about times its expectation, , with the Fisher information of one point, so . Keeping only the terms that grow with ,
Multiplied by , this is the Bayesian information criterion, or Schwarz criterion, smaller being better (Bishop, 2006, Section 4.4.1):
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 .
For 9 heads in 10 under , the three values of the log evidence are:
| Log evidence | |
|---|---|
| exact, | |
| Laplace | |
| BIC, |
For the polynomials, with (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 is large compared with 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 | ||||
|---|---|---|---|---|
| −34.5 | −4.2 | −5.2 | −6.8 | |
| −38.8 | −8.8 | −13.6 | −18.3 | |
| −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 nats per weight. From to the cubic loses nats and degree 9 loses . The gap between degrees 3 and 9 widens from 2.6 nats at to 20.6.
In the limit of a flat prior, , 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 on the whole real line, leaves the evidence undefined: the constant 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 and outputs of order 1 make 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 , so averaging 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 is the likelihood of a model, and .
- 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: ; on twenty noisy points of a sine the evidence peaks at degree 3. Empirical Bayes maximizes it over , .
- BIC 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).