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 .
- Validation set: chooses hyperparameters (degree, , architecture).
- Test set: touched once at the end, to report an unbiased estimate of performance.
-fold cross-validation
When data is scarce, a single validation split wastes data and gives a noisy estimate. -fold cross-validation splits the data into folds, trains times, each time validating on a different fold, and averages:
where is trained on everything except fold . Typical is 5 or 10; is leave-one-out.
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:
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.
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 . 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, , and the AIC; both penalize the number of parameters .
In software
cross_val_score,GridSearchCVandKFoldin 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 , how many models are trained, and on how many examples each?
Answer
60 models, each on 900 examples.
Solution
fits; each training set leaves out one fold of 100. (Then one final fit on all 1,000 with the chosen .)
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 with 3 parameters; model B has with 10 parameters; . Which has the higher BIC score ?
Answer
Model A.
Solution
The 7 extra parameters cost , more than the 8 nats of likelihood they gain.
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…
- the training error
- a validation set or cross-validation
- the test set, repeatedly
- the number of parameters only
In the bias-variance decomposition, a very flexible model typically has…
- high bias, low variance
- low bias, high variance
- zero noise
- low bias and low variance
Why does the Bayesian evidence penalize overly complex models?
- It adds an explicit penalty term
- A complex model spreads its probability over many possible datasets, so it gives less to the observed one
- It ignores the likelihood
- It always prefers linear models