---
title: Model selection and cross-validation
heading: Choosing a model's complexity without fooling yourself, by k-fold and leave-one-out cross-validation with the leverage shortcut, by AIC and BIC, and by the Bayesian evidence with its Occam factor and re-estimated hyperparameters
eyebrow: S14 · Lesson 12 · Model selection
xp: 50
---

::: hook
Lesson 1 showed that training error keeps falling as a model grows, so it can't tell you when to stop. Three tools can: cross-validation, which measures error on data each fit didn't see; information criteria like AIC and BIC, which charge for parameters; and the Bayesian evidence, which charges automatically, through how thinly a flexible model has to spread its predictions. Each also tunes hyperparameters such as a ridge penalty or a prior's width.
:::

::: play
- The curve is the log evidence of a one-weight model $t = wx + \epsilon$ against its prior precision α, for 10 points with Σx² = 10, noise precision 4, and Σxt on the slider.
- A tiny α (a very broad prior) is penalized: the model spreads its predictions over slopes the data rule out. A huge α (a prior pinned at zero) can't fit the data.
- The peak sits near $\alpha = 1/w^2$, where the prior's width matches the slope the data support. With Σxt = 0 there's no slope to support, and the evidence prefers switching the weight off.
:::

```sim plot
view: graph
x: a = 0.001..1000 log
y: lnp = -20..-5
slider: T = 0..20 = 10
plot: 0.5*ln(a) + 5*ln(4) - (2*((T^2/10 + 2.5) - 2*(4*T/(a + 40))*T + (4*T/(a + 40))^2*10) + a/2*(4*T/(a + 40))^2) - 0.5*ln(a + 40) - 5*ln(2*pi) | label: log evidence
```

::: predict
## A least-squares fit leaves a residual of 0.3 at a point whose leverage (its own weight in its own fitted value) is 0.6. If that point were left out of the fit, what would its residual be?

- [ ] 0.3, since one point barely changes the fit
- [ ] 0.12
- [x] 0.75
- [ ] 0.48

::: reveal
For least squares and ridge regression the leave-one-out residual is exactly $e_i/(1 - h_{ii})$: 0.3/0.4 = 0.75. A high-leverage point pulls the fit toward itself, so its training residual understates how badly the model predicts it. The shortcut gives leave-one-out cross-validation from a single fit.
:::
:::

::: nameit
## Cross-validation

Hold out part of the data, fit on the rest, and measure error on what was held out. **k-fold cross-validation** splits the data into k parts and fits k times, each time holding out one part; every example is tested once, by a model that didn't see it. **Leave-one-out** is the case k = N.

## The leverage shortcut

Least squares and ridge regression predict $\hat{\mathbf t} = H\mathbf t$ with the hat matrix $H = \Phi(\Phi^T\Phi + \lambda I)^{-1}\Phi^T$. The leave-one-out residual of example i is
$$\frac{e_i}{1 - h_{ii}}$$
The average leverage is $\text{tr}(H)/N = p_\text{eff}/N$, with $p_\text{eff}$ the effective number of parameters of lesson 9. **Generalized cross-validation** replaces each $h_{ii}$ by the average: $\text{GCV} = \overline{e^2}/(1 - p_\text{eff}/N)^2$.

## Information criteria

With $\ln L$ the maximized log-likelihood and M parameters, choose the model with the largest
$$\text{AIC: } \ln L - M, \qquad \text{BIC: } \ln L - \tfrac M2\ln N$$
(often written as $2M - 2\ln L$ and $M\ln N - 2\ln L$, to be minimized). BIC's penalty grows with N, so with much data it prefers smaller models than AIC.

## The evidence

A model's **evidence** is the probability it gave the data, averaged over its prior: $p(D) = \int p(D|\mathbf w)p(\mathbf w)\,d\mathbf w$. When the posterior is much narrower than the prior,
$$\ln p(D) \approx \ln p(D|\mathbf w_\text{MAP}) + M\ln\frac{\Delta w_\text{posterior}}{\Delta w_\text{prior}}$$
The second term, the **Occam factor**, is negative and grows with the number of parameters and the breadth of their priors: complexity is charged without a separate rule.

## Re-estimating hyperparameters

Maximizing the evidence of Bayesian linear regression (lesson 10) over α gives
$$\alpha = \frac{\gamma}{\mathbf m_N^T\mathbf m_N}, \qquad \gamma = \sum_i\frac{\beta\lambda_i}{\alpha + \beta\lambda_i}$$
with $\lambda_i$ the eigenvalues of $\Phi^T\Phi$ and γ the number of well-determined parameters; iterate with $\mathbf m_N$ recomputed. For one weight the fixed point is $\alpha = S^2/(T^2 - S/\beta)$, with S = Σx² and T = Σxt, and if $T^2 \le S/\beta$ the evidence switches the weight off.
:::

::: example
## A model with 3 parameters reaches $\ln L$ = −120.0 on 200 examples; one with 6 reaches −116.5. Which do AIC and BIC choose?

::: solution
1. **AIC.**
   $$\begin{aligned} \text{small} &= -120 - 3 \\ &= -123.0 \\ \text{large} &= -116.5 - 6 \\ &= -122.5 \end{aligned}$$
   so AIC takes the larger model.
2. **BIC.**
   $$\begin{aligned} \text{small} &= -120 - 1.5\ln 200 \\ &= -127.9 \\ \text{large} &= -116.5 - 3\ln 200 \\ &= -132.4 \end{aligned}$$
   so BIC takes the smaller.
3. **Why they differ.** Three extra parameters bought 3.5 nats; AIC charges 1 nat each, BIC 2.65 at N = 200.
4. **Settling it.** When they disagree, cross-validation on the actual task settles it.

**Answer:** AIC chooses the 6-parameter model, and BIC the 3-parameter one.
:::
:::

::: example
## Find the evidence-optimal prior precision for a one-weight model with Σx² = 10, Σxt = 10 and β = 4, by iterating from α = 1.

::: solution
1. **First pass, at α = 1.**
   $$\begin{aligned} A &= 1 + 40 \\ &= 41 \\ m &= 4 \times 10/41 \\ &= 0.976 \\ \gamma &= 40/41 \\ &= 0.976 \end{aligned}$$
2. **New α.**
   $$\begin{aligned} \alpha &= \gamma/m^2 \\ &= 1.025 \end{aligned}$$
3. **Converge.** Repeating changes it only in the fourth digit, converging to
   $$\begin{aligned} \alpha &= \frac{S^2}{T^2 - S/\beta} \\ &= 100/97.5 \\ &= 1.026 \end{aligned}$$
4. **Compare the slope.** That's close to $1/w_\text{ML}^2$ = 1: the evidence picks a prior about as wide as the slope it has to explain, slightly narrower because the measured slope includes some noise.

**Answer:** the evidence-optimal prior precision is α = 1.026.
:::
:::

::: example
## A model's single parameter has a prior 10 units wide; after the data its posterior is 0.1 wide. What's its Occam factor, and how does it change if the prior is 1 unit wide and the fit is equally good?

::: solution
1. **Prior 10 units wide.**
   $$\ln(0.1/10) = -4.6\ \text{nats}$$
2. **Prior 1 unit wide.**
   $$\ln(0.1/1) = -2.3\ \text{nats}$$
3. **What the evidence charges for.** A prior a hundred times wider than the posterior means the model assigned most of its prior probability to parameter values the data then ruled out, and the evidence charges for that.
4. **Compare.** The model with the more precise prior wins by 2.3 nats, a factor of 10 in evidence, if both fit the data equally well.

**Answer:** the Occam factor is −4.6 nats with the 10-unit prior and −2.3 nats with the 1-unit prior.
:::
:::

::: check
kind: parts
given: p = 3 | 10 | 30; N = 50 | 200; e = 0.2 | -0.5 | 1; h = 0.1 | 0.4 | 0.75

## A least-squares fit with {p} parameters uses {N} points. One point has residual {e} and leverage {h}.

::: part
answer: p/N
tolerance: 0.5%

### What is the average leverage?

::: misses
- [any] $\text{tr}(H)/N = p/N$.
:::
:::

::: part
answer: e/(1 - h)
tolerance: 0.5%

### What is that point's leave-one-out residual?

::: misses
- [e*(1 - h)] Leaving the point out makes its residual larger, not smaller.
- [e/h] Divide by 1 − h.
- [any] $e_i/(1 - h_{ii})$.
:::
:::
:::

::: check
kind: parts
given: m = 0.5 | 2 | 10; q = 2 | 8 | 20; N = 40 | 100

## A ridge fit on {N} points has {q} effective parameters and a mean squared training residual of {m}.

::: part
answer: m/(1 - q/N)^2
tolerance: 0.5%

### What is its generalized cross-validation score?

::: misses
- [m/(1 - q/N)] GCV divides by the square.
- [any] $\overline{e^2}/(1 - p_\text{eff}/N)^2$.
:::
:::
:::

::: check
kind: parts
given: L = -500 | -120; M = 3 | 12; N = 100 | 10000

## A model with {M} parameters reaches a maximized log-likelihood of {L} on {N} examples.

::: part
answer: L - M
tolerance: 0.5%

### What is its AIC score (in the form ln L − M)?

::: misses
- [any] Subtract the number of parameters.
:::
:::

::: part
answer: L - M/2*ln(N)
tolerance: 0.5%

### Its BIC score (ln L − (M/2) ln N)?

::: misses
- [L - M*ln(N)] BIC charges half of ln N per parameter.
- [any] $\ln L - \frac M2\ln N$.
:::
:::
:::

::: check
kind: parts
given: a = 2 | 5 | 10; d = 3 | 8 | 15; N = 50 | 1000 | 100000

## A larger model has {a} more parameters than a smaller one and raises the maximized log-likelihood by {d} nats, on {N} examples.

::: part
answer: d - a/2*ln(N)
tolerance: 0.5%

### By how much does it change the BIC score (positive favors the larger model)?

::: misses
- [d - a] That's AIC's change.
- [any] $\Delta\ln L - \frac{\Delta M}2\ln N$.
:::
:::
:::

::: check
kind: parts
given: M = 2 | 4 | 20; w = 2 | 10 | 100; u = 0.05 | 0.5

## Each of a model's {M} parameters has a prior {w} units wide and a posterior {u} wide.

::: part
answer: M*ln(u/w)
unit: nats
tolerance: 0.5%

### What is the log of its Occam factor?

::: misses
- [ln(u/w)] Each parameter contributes a factor.
- [M*ln(w/u)] The factor is less than 1, so its log is negative.
- [any] $M\ln(\Delta w_\text{post}/\Delta w_\text{prior})$.
:::
:::
:::

::: check
kind: parts
given: S = 5 | 20; T = 8 | 12 | 20; b = 0.5 | 1

## A one-weight model has Σx² = {S} and Σxt = {T}, with noise precision {b}.

::: part
answer: S^2/(T^2 - S/b)
tolerance: 0.5%

### What prior precision maximizes its evidence?

::: misses
- [S^2/T^2] That's $1/w_\text{ML}^2$; the noise in the measured slope makes the evidence prefer a slightly narrower prior.
- [any] $\alpha = S^2/(T^2 - S/\beta)$.
:::
:::

::: part
answer: b*S/(S^2/(T^2 - S/b) + b*S)
tolerance: 0.5%

### How many well-determined parameters γ does it have there?

::: misses
- [any] $\gamma = \beta S/(\alpha + \beta S)$.
:::
:::
:::

::: check
kind: choice

## Two models fit the data equally well, but one gives its parameters a far broader prior. Why does the evidence prefer the other?

- [ ] Broad priors make the posterior broader
- [x] The broad-prior model spread its prior probability over many parameter values the data rule out, so it assigned less probability to the data actually seen
- [ ] The evidence ignores the fit and counts parameters
- [ ] Broad priors make the likelihood smaller

::: misses
- [1] The posterior is set mostly by the data, not the prior's width.
- [3] The fit enters through the likelihood term.
- [4] The best-fit likelihood is the same; the averaging over the prior differs.
:::
:::

::: check
kind: derivation
vars: S = 1..100, T = 10..100, b = 1..10

## A one-weight model has Σx² = S and Σxt = T, with noise precision β, and its prior precision is set by maximizing the evidence.

::: step
answer: T/S

### What is the maximum-likelihood weight?
:::

::: step
answer: S^2/(T^2 - S/b)

### What prior precision maximizes the evidence?
:::

::: step
answer: 1/(b*S)

### What is the variance of the maximum-likelihood weight?
:::

::: right
Right. The optimal α is $1/(w_\text{ML}^2 - \text{var}\,w_\text{ML})$: the prior matches the squared slope with the measurement noise taken out.
:::
:::

::: check
kind: python

## Write `ridge1(xs, ts, lam)` for one weight through the origin, `cv_error(xs, ts, lam, k)`: the mean squared error of k-fold cross-validation with contiguous folds, and `loo_shortcut(xs, ts, lam)`: the leave-one-out error from a single fit.

```python starter
def ridge1(xs, ts, lam):
    return sum(x * t for x, t in zip(xs, ts)) / (sum(x * x for x in xs) + lam)

def cv_error(xs, ts, lam, k):
    w = ridge1(xs, ts, lam)
    return sum((t - w * x) ** 2 for x, t in zip(xs, ts)) / len(xs)

def loo_shortcut(xs, ts, lam):
    return cv_error(xs, ts, lam, len(xs))
```

```python solution
def ridge1(xs, ts, lam):
    return sum(x * t for x, t in zip(xs, ts)) / (sum(x * x for x in xs) + lam)

def cv_error(xs, ts, lam, k):
    n = len(xs)
    err = 0.0
    for f in range(k):
        lo, hi = f * n // k, (f + 1) * n // k
        w = ridge1(xs[:lo] + xs[hi:], ts[:lo] + ts[hi:], lam)
        err += sum((t - w * x) ** 2 for x, t in zip(xs[lo:hi], ts[lo:hi]))
    return err / n

def loo_shortcut(xs, ts, lam):
    S = sum(x * x for x in xs) + lam
    w = ridge1(xs, ts, lam)
    return sum(((t - w * x) / (1 - x * x / S)) ** 2 for x, t in zip(xs, ts)) / len(xs)
```

```python tests
xs = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]
ts = [0.7, 1.1, 1.4, 2.3, 2.4, 3.2, 3.3, 4.1]
assert abs(cv_error(xs, ts, 0.5, 8) - loo_shortcut(xs, ts, 0.5)) < 1e-12, "With k = N, cross-validation equals the shortcut exactly."
assert abs(cv_error(xs, ts, 0.5, 4) - 0.035536) < 1e-6, "Four folds: 0.0355."
grid = [0, 0.1, 0.5, 1, 2, 5]
assert min(grid, key=lambda l: loo_shortcut(xs, ts, l)) == 0.1, "Leave-one-out picks λ = 0.1 from the grid."
```

::: right
Right. For a linear smoother, leave-one-out cross-validation costs no more than one fit.
:::
:::

::: explain
## Why can't training error choose a model's complexity, while cross-validation and the evidence can?

::: model
Training error is measured on the same data the model was fitted to, so a more flexible model always matches it at least as well, including its noise; it keeps falling as complexity grows. Cross-validation measures error only on examples each fit didn't see, so fitting noise is punished: the error falls while added flexibility captures real structure and rises once it starts memorizing. The evidence gets the same effect differently: a flexible model must spread its prior probability over many possible data sets, so it gives less probability to the one observed unless its flexibility was needed to explain it.
:::
:::

::: practice
::: check
given: e = 0.3 | -1; h = 0.2 | 0.6
answer: e/(1 - h)
tolerance: 0.5%

## Leave-one-out residual: residual {e}, leverage {h}?

::: misses
- [any] $e/(1 - h)$.
:::
:::

::: check
given: L = -80 | -300; M = 4 | 9; N = 60 | 5000
answer: L - M/2*ln(N)
tolerance: 0.5%

## BIC: ln L = {L}, M = {M}, N = {N}?

::: misses
- [any] $\ln L - \frac M2\ln N$.
:::
:::

::: check
given: S = 10 | 40; T = 12 | 30; b = 2 | 8
answer: S^2/(T^2 - S/b)
tolerance: 0.5%

## Evidence-optimal α: S = {S}, T = {T}, β = {b}?

::: misses
- [any] $S^2/(T^2 - S/\beta)$.
:::
:::
:::
