TExcelTAD
Home › Math for Machine Learning › Model Selection and Cross-Validation

Model Selection and Cross-Validation

Which polynomial degree? How much regularization? How many mixture components? These hyperparameters cannot be chosen by training error, which always prefers the most complex model. They are chosen by estimating test error on data the model has not trained on, most often with cross-validation, or by a Bayesian criterion that penalizes complexity.

Three data splits

  • Training set: fits the parameters θ\boldsymbol{\theta}.
  • Validation set: chooses hyperparameters (degree, λ\lambda, architecture).
  • Test set: touched once at the end, to report an unbiased estimate of performance.

KK-fold cross-validation

When data is scarce, a single validation split wastes data and gives a noisy estimate. KK-fold cross-validation splits the data into KK folds, trains KK times, each time validating on a different fold, and averages:

CV(λ)=1K∑k=1KR(Vk; θλ(−k))\text{CV}(\lambda) = \frac{1}{K}\sum_{k=1}^{K}\mathbf{R}\big(\mathcal{V}_k;\ \boldsymbol{\theta}_\lambda^{(-k)}\big)

where θλ(−k)\boldsymbol{\theta}_\lambda^{(-k)} is trained on everything except fold Vk\mathcal{V}_k. Typical KK is 5 or 10; K=NK = N is leave-one-out.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
N = 60
x = rng.uniform(-2, 2, N); y = np.sin(2 * x) + 0.3 * rng.normal(size=N)
Phi = lambda x: np.vander(x / 2, 13, increasing=True)
def fit(xt, yt, lam):
    P = Phi(xt); return np.linalg.solve(P.T @ P + lam * np.eye(P.shape[1]), P.T @ yt)
folds = np.array_split(rng.permutation(N), 5)
results = {}
for lam in (1e-8, 1e-5, 1e-3, 1e-1, 1.0, 10.0):
    errs = []
    for k in range(5):
        val = folds[k]; tr = np.concatenate([folds[j] for j in range(5) if j != k])
        theta = fit(x[tr], y[tr], lam)
        errs.append(np.mean((Phi(x[val]) @ theta - y[val]) ** 2))
    results[lam] = np.mean(errs)
    print(f"lambda={lam:<6g} 5-fold CV MSE {results[lam]:.4f}")
print("chosen lambda:", min(results, key=results.get))
lambda=1e-08  5-fold CV MSE 0.2539
lambda=1e-05  5-fold CV MSE 0.1603
lambda=0.001  5-fold CV MSE 0.1125
lambda=0.1    5-fold CV MSE 0.1001
lambda=1      5-fold CV MSE 0.2260
lambda=10     5-fold CV MSE 0.4391
chosen lambda: 0.1

Bias and variance

The expected test error of a regression model decomposes into three parts:

E[(y−f^(x))2]=(f(x)−E[f^(x)])2⏟bias2+V[f^(x)]⏟variance+σ2⏟noise\mathbb{E}\big[(y - \hat{f}(\mathbf{x}))^2\big] = \underbrace{\big(f(\mathbf{x}) - \mathbb{E}[\hat{f}(\mathbf{x})]\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{V}[\hat{f}(\mathbf{x})]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}}

where the expectation is over training sets. Simple models have high bias; flexible models have high variance; regularization trades a little bias for a big reduction in variance.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
f = lambda x: np.sin(2 * x); x0 = 1.0
Phi = lambda x, d: np.vander(np.atleast_1d(x) / 2, d + 1, increasing=True)
for deg in (1, 3, 9):
    preds = []
    for _ in range(500):                                   # many training sets
        x = rng.uniform(-2, 2, 20); y = f(x) + 0.3 * rng.normal(size=20)
        theta = np.linalg.lstsq(Phi(x, deg), y, rcond=None)[0]
        preds.append((Phi(x0, deg) @ theta)[0])
    preds = np.array(preds)
    print(f"degree {deg}: bias^2 {(preds.mean() - f(x0))**2:.4f}  variance {preds.var():.4f}")
degree 1: bias^2 0.5215  variance 0.0535
degree 3: bias^2 0.0003  variance 0.0262
degree 9: bias^2 0.0141  variance 8.3576

Bayesian model selection

Bayesian methods compare models by their evidence p(D∣M)=∫p(D∣θ,M) p(θ∣M) dθp(\mathcal{D} \mid M) = \int p(\mathcal{D} \mid \boldsymbol{\theta}, M)\,p(\boldsymbol{\theta} \mid M)\,d\boldsymbol{\theta}. A complex model spreads its prior over many possible datasets, so it assigns less probability to any one of them: the evidence contains an automatic "Occam's razor". Cheap approximations are the BIC, log⁡p(D∣θML)−D2log⁡N\log p(\mathcal{D} \mid \boldsymbol{\theta}_{\text{ML}}) - \frac{D}{2}\log N, and the AIC; both penalize the number of parameters DD.

In software

  • cross_val_score, GridSearchCV and KFold in scikit-learn (Cross-Validation, Grid Search).
  • GaussianMixture.bic(X) helps choose the number of mixture components (Mixtures as Latent-Variable Models).
  • Deep learning usually uses one validation split (data is plentiful) and early stopping on the validation loss.

Go further: Holdout and K-Fold Cross-Validation turns this into a workflow: tune with cross-validation, then touch the test set once.

Exercises

Exercise 1: Folds and fits

With 1,000 examples, 10-fold CV and 6 candidate values of λ\lambda, how many models are trained, and on how many examples each?

Answer

60 models, each on 900 examples.

Solution

10⋅6=6010 \cdot 6 = 60 fits; each training set leaves out one fold of 100. (Then one final fit on all 1,000 with the chosen λ\lambda.)

Exercise 2: Diagnose

A model has training MSE 0.02 and validation MSE 0.95. Is the problem bias or variance, and what would you try?

Answer

High variance (overfitting): regularize more, simplify the model, or get more data.

Solution

A huge gap between training and validation error means the model fits the training noise. High bias would show as both errors being high.

Exercise 3: BIC by hand (code)

Model A has log-likelihood −520-520 with 3 parameters; model B has −512-512 with 10 parameters; N=400N = 400. Which has the higher BIC score log⁡L−D2log⁡N\log\mathcal{L} - \frac{D}{2}\log N?

Answer

Model A.

Solution

The 7 extra parameters cost 72log⁡400≈21\frac{7}{2}\log 400 \approx 21, more than the 8 nats of likelihood they gain.

python · try it yourself
import math
for name, ll, D in (("A", -520, 3), ("B", -512, 10)):
    print(name, round(ll - D / 2 * math.log(400), 2))
A -528.99
B -541.96

Test yourself

Hyperparameters should be chosen using…

  1. the training error
  2. a validation set or cross-validation
  3. the test set, repeatedly
  4. the number of parameters only

In the bias-variance decomposition, a very flexible model typically has…

  1. high bias, low variance
  2. low bias, high variance
  3. zero noise
  4. low bias and low variance

Why does the Bayesian evidence penalize overly complex models?

  1. It adds an explicit penalty term
  2. A complex model spreads its probability over many possible datasets, so it gives less to the observed one
  3. It ignores the likelihood
  4. It always prefers linear models