Bayesian Model Comparison: The Evidence Framework

How Bayesian model comparison uses the marginal likelihood to pick model complexity: Bayes factors, BIC, AIC, and a polynomial regression demo in Python.

Cover Image for Bayesian Model Comparison: The Evidence Framework

Several curves can fit a small noisy dataset, and the most flexible one may follow fluctuations that will not repeat. Choosing a model means deciding how much complexity the observations support. Bayesian model comparison extends inference about parameters to this choice between models, using their probabilities for the observed data to weigh the alternatives.

In David MacKay's 1992 thesis, integrating over parameters supplies a preference for simpler models. Our polynomial evidence peaks at degree four, while AIC and BIC break down at degree nine. We calculate the integral in closed form, building on posterior sampling and the meaning of likelihood.

Quick Win: Evidence as a Function of Model Complexity

Open In Colab

The setup is a standard one: ten noisy observations of sin⁡(2πx)\sin(2\pi x), fit with polynomials of order M=0,1,…,9M = 0, 1, \ldots, 9 using a Gaussian prior on the weights. For each MM we compute the log marginal likelihood ln⁡p(D∣M)\ln p(\mathcal{D} \mid M) in closed form.

Polynomial fits growing from a flat line at M=0 to a perfect interpolator at M=9, with the log evidence updating on the right

import numpy as np

def phi_poly(x, M):
    return np.stack([x**k for k in range(M + 1)], axis=1)

def log_evidence(Phi, t, alpha, beta):
    N, M_plus = len(t), Phi.shape[1]
    A = alpha * np.eye(M_plus) + beta * Phi.T @ Phi
    m_N = beta * np.linalg.solve(A, Phi.T @ t)
    residual = t - Phi @ m_N
    E_mN = 0.5 * beta * residual @ residual + 0.5 * alpha * m_N @ m_N
    _, logdet_A = np.linalg.slogdet(A)
    return (
        0.5 * M_plus * np.log(alpha)
        + 0.5 * N * np.log(beta)
        - E_mN
        - 0.5 * logdet_A
        - 0.5 * N * np.log(2 * np.pi)
    )

# Ten sin(2pi x) points, Gaussian prior with alpha=5e-3, noise precision beta=1/0.3^2
log_evs = [log_evidence(phi_poly(x, M), t, 5e-3, 1 / 0.3**2) for M in range(10)]

Here is the resulting curve.

Log model evidence plotted against polynomial order M, peaking near M=4 and then slowly declining

A constant (M=0M = 0) gets ln⁡p(D)=−38.9\ln p(\mathcal{D}) = -38.9. A straight line rockets up to −18.7-18.7. The cubic M=3M = 3 is at −14.8-14.8. The evidence then peaks at M=4M = 4 and declines slowly as we pile on more parameters. No validation set, no cross-validation loop, no held-out data. The entire answer fell out of a single closed-form integral over the weights.

For comparison, the held-out test MSE (on 100 new observations) also reaches its minimum at M=4M = 4, and then degrades as the model overfits. The evidence, computed purely from the training data, tracks out-of-sample generalisation. That is the promise of the framework.

What Just Happened?

1. From parameters to models

You already know how to infer parameters from data inside a chosen model: Bayes' rule gives you p(w∣D)∝p(D∣w)p(w)p(\mathbf{w} \mid \mathcal{D}) \propto p(\mathcal{D} \mid \mathbf{w}) p(\mathbf{w}). The only thing new in model comparison is that we now apply Bayes' rule one level up. Given a set of candidate models {M1,…,ML}\{M_1, \ldots, M_L\} and a prior over models p(Mi)p(M_i), the posterior is

p(Mi∣D)∝p(D∣Mi) p(Mi).p(M_i \mid \mathcal{D}) \propto p(\mathcal{D} \mid M_i) \, p(M_i).

If we assume all models are equally likely a priori, everything hinges on the term p(D∣Mi)p(\mathcal{D} \mid M_i). This is the model evidence, also called the marginal likelihood, and it is obtained by integrating out the parameters:

p(D∣Mi)=∫p(D∣w,Mi) p(w∣Mi) dw.p(\mathcal{D} \mid M_i) = \int p(\mathcal{D} \mid \mathbf{w}, M_i) \, p(\mathbf{w} \mid M_i) \, d\mathbf{w}.

Read that integral carefully. The likelihood p(D∣w,Mi)p(\mathcal{D} \mid \mathbf{w}, M_i) measures how well a specific choice of w\mathbf{w} explains the data. Multiplying by the prior p(w∣Mi)p(\mathbf{w} \mid M_i) and integrating asks a different question: averaged over every configuration of parameters this model allows, how likely is this data? A flexible model spreads its prior thinly across many configurations, so it must pay a complexity price for every parameter it does not use well.

The ratio of two model evidences has a name: the Bayes factor, introduced by Kass and Raftery (1995) as the Bayesian replacement for a p-value:

Bij=p(D∣Mi)p(D∣Mj).B_{ij} = \frac{p(\mathcal{D} \mid M_i)}{p(\mathcal{D} \mid M_j)}.

A Bayes factor of 100 in favour of MiM_i is decisive; 3 is suggestive; under 1 flips the conclusion. Because it is a ratio of evidences, the awkward normalisation constant cancels out.

2. Why the integral gives you Occam's razor

Here is the part that felt magical to me the first time I saw it. Suppose we approximate the integral by assuming the posterior p(w∣D,Mi)p(\mathbf{w} \mid \mathcal{D}, M_i) is sharply peaked around its mode wMAP\mathbf{w}_{\text{MAP}}, with width Δwposterior\Delta w_{\text{posterior}} in each direction. If the prior is roughly flat over a region of width Δwprior\Delta w_{\text{prior}}, the integral reduces to

p(D)≃p(D∣wMAP)⋅(ΔwposteriorΔwprior)M,p(\mathcal{D}) \simeq p(\mathcal{D} \mid \mathbf{w}_{\text{MAP}}) \cdot \left( \frac{\Delta w_{\text{posterior}}}{\Delta w_{\text{prior}}} \right)^M,

where MM is the number of parameters. Taking logs:

ln⁡p(D)≃ln⁡p(D∣wMAP)+Mln⁡(ΔwposteriorΔwprior).\ln p(\mathcal{D}) \simeq \ln p(\mathcal{D} \mid \mathbf{w}_{\text{MAP}}) + M \ln \left( \frac{\Delta w_{\text{posterior}}}{\Delta w_{\text{prior}}} \right).

The first term is the log-likelihood at the best-fit parameters. The second term is a penalty: since posterior widths are always smaller than prior widths, the ratio is less than one and its log is negative. Adding a parameter shrinks the posterior somewhere, which shrinks the ratio, which adds a negative constant per parameter.

Bar chart showing the data-fit term growing and the complexity penalty growing in the opposite direction, with the sum peaking at an intermediate M

The bar chart decomposes the log evidence for our polynomial example. The teal bars are the data-fit contribution, which improves (becomes less negative) as MM grows. The amber bars are the Occam penalty, which worsens (becomes more negative) as MM grows. Their sum, the black line, rises steeply until M=3M = 3 then plateaus and slowly turns over. Nowhere did we tell the model to prefer simpler explanations. The preference emerged from integrating over the prior.

3. Occam in a picture

There is a second, deeper reason evidence penalises complexity. Imagine sweeping every possible dataset the world could hand you onto a single horizontal axis, and asking each model to predict a probability for each dataset.

Three bell curves of different widths on the same axis: a narrow green one concentrated at the origin, an amber intermediate one, and a wide grey one; a dashed vertical line marks the observed data

A simple model concentrates its predictive probability on a narrow band of datasets. If the data falls in that band, the simple model has high evidence there. A very complex model spreads its predictive probability across a huge range of possible datasets, so any particular observation receives low probability density under the complex model, even if it could have been generated by one of many configurations of its parameters. A model of intermediate complexity puts moderate mass on a moderate range, and tends to win on most real datasets. This is Occam's razor as a consequence of normalisation: all these distributions are probability densities over dataset space, so they must integrate to one.

4. Posterior predictive fits

The closed-form Bayesian polynomial regression is worth staring at directly. With a Gaussian prior w∼N(0,α−1I)\mathbf{w} \sim \mathcal{N}(0, \alpha^{-1} \mathbf{I}) and Gaussian noise with precision β\beta, the posterior over weights is also Gaussian with covariance SN=(αI+βΦ⊤Φ)−1\mathbf{S}_N = (\alpha \mathbf{I} + \beta \mathbf{\Phi}^\top \mathbf{\Phi})^{-1} and mean mN=βSNΦ⊤t\mathbf{m}_N = \beta \mathbf{S}_N \mathbf{\Phi}^\top \mathbf{t}. The predictive mean and variance at a new input are straightforward linear algebra.

Four panels: M=0 is a flat line well below the data, M=1 is a linear fit cutting through the sinusoid, M=3 captures the shape cleanly, M=9 wiggles slightly around all ten points

Notice that the M=9M = 9 fit is not the wild oscillating mess you get from maximum likelihood with nine degrees of freedom on ten points. The Gaussian prior regularises the weights, so the fit remains well-behaved even at the interpolation limit. The evidence, however, still correctly tells us the cubic is the right complexity for this data.

Going Deeper

BIC and AIC as approximations of evidence

Maximum likelihood practitioners have been comparing models for decades without computing evidence integrals. They use the Bayesian Information Criterion (Schwarz 1978) and the Akaike Information Criterion (Akaike 1974):

BIC=−2ln⁡p(D∣w^ML)+kln⁡N\text{BIC} = -2 \ln p(\mathcal{D} \mid \hat{\mathbf{w}}_{\text{ML}}) + k \ln N
AIC=−2ln⁡p(D∣w^ML)+2k\text{AIC} = -2 \ln p(\mathcal{D} \mid \hat{\mathbf{w}}_{\text{ML}}) + 2k

where kk is the number of parameters and NN the number of data points. Lower is better. Both plug the MLE into the likelihood and add a complexity penalty.

BIC is a large-sample asymptotic approximation to −2ln⁡p(D)-2 \ln p(\mathcal{D}) under mild regularity conditions (Schwarz 1978; the derivation is an exercise in Laplace approximation). In the N→∞N \to \infty limit, BIC differs from −2ln⁡p(D)-2 \ln p(\mathcal{D}) by O(1)O(1), and the gap does not grow with NN, so they order models identically for large datasets.

AIC approximates a different target: it estimates the expected Kullback-Leibler divergence between the fitted model and the data-generating process. Akaike's derivation uses asymptotic bias correction arguments. AIC's penalty is smaller than BIC's for N>7N > 7 or so, which means AIC consistently selects richer models than BIC. The two criteria answer different questions: BIC asks "which model is most probable given the data?", AIC asks "which model will generalise best?". For finite samples the answers can differ substantially.

Two panels: left shows -2 ln evidence, BIC, AIC vs M with all three roughly flat between M=3 and M=8 then plummeting at M=9; right shows train and test MSE, with train falling monotonically and test U-shaped minimising around M=3-4

Our polynomial experiment exposes what happens when the asymptotic assumptions break down. In the middle range (M=3M = 3 to M=6M = 6) all three criteria agree roughly, with scores clustered within a few nats. But at M=9M = 9, BIC and AIC collapse to absurdly negative values (off the scale, near −295-295) because the MLE interpolates the ten data points exactly: the residuals are zero, σML2→0\sigma^2_{\text{ML}} \to 0, and the log-likelihood at the MLE shoots to positive infinity. The evidence, by contrast, remains at ln⁡p(D)=−15.2\ln p(\mathcal{D}) = -15.2, because the integral averages over the whole posterior rather than evaluating at one point.

This is not a quirk of this particular dataset. Any time you have as many parameters as data points, classical MLE-based criteria break down in exactly this way. The Bayesian evidence is robust because it never relies on a point estimate.

Hyperparameters: the prior width matters

The evidence is not defined if the prior is improper, and the framework is sensitive to the prior width. We used α=5×10−3\alpha = 5 \times 10^{-3}, which corresponds to a prior standard deviation of about 1414 on each weight. Making the prior dramatically wider or dramatically tighter changes where the evidence peaks:

  • Tighter prior (α\alpha large, Δwprior\Delta w_{\text{prior}} small): the Occam penalty ln⁡(Δwpost/Δwprior)\ln(\Delta w_{\text{post}}/\Delta w_{\text{prior}}) shrinks. The evidence favours larger models because the penalty per parameter is smaller.
  • Wider prior (α→0\alpha \to 0, Δwprior→∞\Delta w_{\text{prior}} \to \infty): the penalty per parameter becomes arbitrarily negative, so the evidence favours simpler models. In the improper-prior limit the evidence itself becomes undefined.

Ratios of evidences (Bayes factors) can still be meaningful in the improper-prior limit if the limiting behaviour is handled carefully, but absolute evidences need a well-defined prior. In practice this means thinking about the prior as seriously as you think about the likelihood, which is a healthy discipline in any case.

When evidence is not enough

The Bayesian framework assumes one of your candidate models is close to the truth. If the data-generating process is nothing like any of your candidates, the evidence will still pick a winner, but that winner might be a poor approximation. Any approach needs to make assumptions about the form of the model, and if these are invalid then the results can be misleading.

Two practical implications. First, always keep an independent test set even when you have an evidence computation. The evidence tells you the best model among your candidates; it does not tell you whether any of them are good enough. Second, for high-dimensional problems the evidence integral becomes intractable, and you need approximations: Laplace's method (reasonable for near-Gaussian posteriors), variational bounds like the ELBO, bridge sampling, or nested sampling. Each has failure modes. Skilling's nested sampling (implemented in dynesty) is the current default in cosmology; Meng and Wong's bridge sampling is a favourite in PyMC (the arviz.bridgesampling module). None are free lunches.

For graphical models the computation is sometimes tractable through clever algorithmic tricks, which we touched on in the MCMC Metropolis-Hastings post, in our walkthrough of Bayesian network structure learning on the LUCADA lung-cancer database, and use extensively when comparing hierarchical regression models in PyMC.

Foundations: MacKay, Schwarz, Akaike, Kass

The modern evidence framework rests on four papers.

Akaike (1974), "A new look at the statistical model identification". The original derivation of AIC using asymptotic bias correction of the KL divergence between fitted and true model. Published in IEEE Transactions on Automatic Control. Akaike's insight was to see model selection as a problem in predictive accuracy, not in truth recovery.

Schwarz (1978), "Estimating the dimension of a model". Derives BIC as the asymptotic approximation to the log marginal likelihood under a Laplace approximation. Published in Annals of Statistics. Schwarz's penalty is harsher because he is asymptotically exact about model probability, whereas Akaike is asymptotically unbiased about predictive loss.

MacKay (1992a), "Bayesian interpolation". MacKay's Neural Computation paper and his PhD thesis, completed at Caltech in Hopfield's group, pulled the evidence framework into the machine learning community. He applied it to neural network regularisation (determining α\alpha and β\beta automatically via the evidence procedure, which we sketched above), model selection, and architecture comparison. The thesis (500+ pages, freely available) contains essentially every idea in modern Bayesian deep learning. MacKay's work strongly advocated Bayesian methods on neural networks, showing that they give rise to interesting algorithms and useful insights.

Kass and Raftery (1995), "Bayes factors". The standard reference for interpreting Bayes factors in applied work. Their Table 1 gives the rule of thumb most statisticians quote: log⁡10B>2\log_{10} B > 2 is decisive, log⁡10B\log_{10} B between 1 and 2 is strong, between 0.5 and 1 is substantial, below 0.5 is barely worth mentioning. Published in the Journal of the American Statistical Association.

The evidence approximation for hyperparameters

MacKay's other contribution is using the evidence to set hyperparameters like α\alpha and β\beta themselves. Rather than cross-validating over a grid, you optimise the log evidence with respect to α,β\alpha, \beta directly. This gives the elegant fixed-point iteration

α=γmN⊤mN,γ=∑iλiα+λi,\alpha = \frac{\gamma}{\mathbf{m}_N^\top \mathbf{m}_N}, \quad \gamma = \sum_i \frac{\lambda_i}{\alpha + \lambda_i},

where λi\lambda_i are the eigenvalues of βΦ⊤Φ\beta \mathbf{\Phi}^\top \mathbf{\Phi} and γ\gamma is the effective number of parameters, a number between 0 and MM that measures how many of your weights are constrained by the data versus being tied down by the prior. Directions where λi≫α\lambda_i \gg \alpha contribute roughly 1 to γ\gamma; directions where λi≪α\lambda_i \ll \alpha contribute roughly 0. This is the same framework that underlies empirical Bayes and the automatic relevance determination (ARD) priors used in Gaussian process regression.

Interactive Tools

  • Bayes' Theorem Calculator: Work through the single-parameter version of the framework before scaling up to model-level Bayes.
  • Overfitting Explorer: Polynomial overfitting exactly like the example in this post, with sliders for degree, regularisation, and sample size.
  • Normal Distribution Calculator: Play with Gaussian priors of varying widths to build intuition for the α\alpha parameter in the evidence calculation.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions