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
The setup is a standard one: ten noisy observations of , fit with polynomials of order using a Gaussian prior on the weights. For each we compute the log marginal likelihood in closed form.

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.

A constant () gets . A straight line rockets up to . The cubic is at . The evidence then peaks at 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 , 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 . The only thing new in model comparison is that we now apply Bayes' rule one level up. Given a set of candidate models and a prior over models , the posterior is
If we assume all models are equally likely a priori, everything hinges on the term . This is the model evidence, also called the marginal likelihood, and it is obtained by integrating out the parameters:
Read that integral carefully. The likelihood measures how well a specific choice of explains the data. Multiplying by the prior 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:
A Bayes factor of 100 in favour of 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 is sharply peaked around its mode , with width in each direction. If the prior is roughly flat over a region of width , the integral reduces to
where is the number of parameters. Taking logs:
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.

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 grows. The amber bars are the Occam penalty, which worsens (becomes more negative) as grows. Their sum, the black line, rises steeply until 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.

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 and Gaussian noise with precision , the posterior over weights is also Gaussian with covariance and mean . The predictive mean and variance at a new input are straightforward linear algebra.

Notice that the 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):
where is the number of parameters and 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 under mild regularity conditions (Schwarz 1978; the derivation is an exercise in Laplace approximation). In the limit, BIC differs from by , and the gap does not grow with , 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 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.

Our polynomial experiment exposes what happens when the asymptotic assumptions break down. In the middle range ( to ) all three criteria agree roughly, with scores clustered within a few nats. But at , BIC and AIC collapse to absurdly negative values (off the scale, near ) because the MLE interpolates the ten data points exactly: the residuals are zero, , and the log-likelihood at the MLE shoots to positive infinity. The evidence, by contrast, remains at , 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 , which corresponds to a prior standard deviation of about on each weight. Making the prior dramatically wider or dramatically tighter changes where the evidence peaks:
- Tighter prior ( large, small): the Occam penalty shrinks. The evidence favours larger models because the penalty per parameter is smaller.
- Wider prior (, ): 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 and 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: is decisive, 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 and themselves. Rather than cross-validating over a grid, you optimise the log evidence with respect to directly. This gives the elegant fixed-point iteration
where are the eigenvalues of and is the effective number of parameters, a number between 0 and that measures how many of your weights are constrained by the data versus being tied down by the prior. Directions where contribute roughly 1 to ; directions where 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 parameter in the evidence calculation.
Related Posts
- From Thermodynamics to ML: Entropy, KL and Mutual Info: the KL divergence that appears in Bayes factor expectations comes from here.
- AIC and BIC for Model Selection: Standalone walkthrough of the two criteria we compared against the full evidence.
- MCMC Metropolis-Hastings: An Intuitive Guide: When the evidence integral is intractable, sampling methods let you estimate it numerically.
- From MLE to Bayesian Inference: The prerequisite: inferring parameters with priors before we infer models.
- The EM Algorithm: A Coin Toss Guide: the EM algorithm and the evidence procedure converge to the same solution for hyperparameter estimation.
- Hierarchical Bayesian Regression with PyMC: Real-world Bayesian model comparison in PyMC, where evidence is approximated via sampling-based estimators.






