Fighting Overfitting: Validation and Regularization

We now understand the disease. The model's flexibility has to match the data, and test error is bias² + variance + noise. This section covers the two standard cures:

  1. Validation: measure generalization honestly, so you can choose the complexity knob scientifically.
  2. Regularization: keep a flexible model but discourage it from using its flexibility unless the data really demands it.

The three-way split

You can't tune the degree by looking at training error, which always prefers the most complex model. You also can't tune it on the test set, for a subtle but critical reason:

Any data you use to make a decision becomes, in effect, training data. If you choose the degree because it does best on the test set, the test error of the chosen model is optimistically biased, in exactly the way training error is. The test set must be touched once, at the very end.

So we split the labelled data three ways:

SetTypical shareUsed forAnalogy
Training60–80%Fitting parameters \(w\)Textbook exercises
Validation10–20%Choosing hyperparameters (degree, \(\lambda\), tree depth, GA settings), early stoppingMock exams
Test10–20%One final, honest estimate of future errorThe real exam, sat once
Data leakage: the silent killer

Leakage is any way information from validation or test data sneaks into training. Classic examples:

  • Normalizing features with the mean and std of the whole dataset before splitting. Compute them on the training set only.
  • Duplicate or near-duplicate examples landing in both train and test.
  • Tuning on the test set "just once more."
  • Time-series data split randomly, so the model is trained on the future to predict the past.

Leakage gives beautiful numbers that collapse in deployment.

k-fold cross-validation

With only 40 labelled deliveries, holding out 10 for validation wastes data and gives a noisy estimate. k-fold cross-validation fixes both problems:

  1. Split the (non-test) data into \(k\) equal folds.
  2. For each fold \(i\): train on the other \(k-1\) folds and measure error on fold \(i\).
  3. Average the \(k\) errors. That's the CV estimate for this hyperparameter setting.
  4. Repeat for each candidate setting, pick the best, then retrain on all the non-test data with that setting.
round 1round 2round 3round 4round 5
5-fold CV: every example is used for validation exactly once (orange) and for training four times (blue).

The extreme case \(k=n\) is leave-one-out CV: almost unbiased but expensive. \(k=5\) or \(10\) is the usual compromise.

import numpy as np

rng = np.random.default_rng(2)
def true_time(d):
    return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
    d = rng.uniform(0, 5, n)
    return d, true_time(d) + rng.normal(0, 2.0, n)
def poly_features(d, degree):
    return np.vander((d - 2.5) / 2.5, degree + 1, increasing=True)

d_all, t_all = make_deliveries(40)       # all the labelled data we have
d_test, t_test = make_deliveries(2000)   # locked away until the very end

def kfold_mse(d, t, degree, k=5):
    idx = np.arange(len(d))
    folds = np.array_split(idx, k)
    errs = []
    for f in folds:
        train = np.setdiff1d(idx, f)
        w, *_ = np.linalg.lstsq(poly_features(d[train], degree), t[train], rcond=None)
        errs.append(np.mean((poly_features(d[f], degree) @ w - t[f]) ** 2))
    return np.mean(errs)

cv = {deg: kfold_mse(d_all, t_all, deg) for deg in range(0, 11)}
for deg, e in cv.items():
    print(f"degree {deg:2d}: 5-fold CV MSE = {e:8.2f}")
best = min(cv, key=cv.get)
print("chosen degree:", best)

# retrain on ALL 40 points with the chosen degree, then touch the test set ONCE
w, *_ = np.linalg.lstsq(poly_features(d_all, best), t_all, rcond=None)
print("final test MSE: %.2f" % np.mean((poly_features(d_test, best) @ w - t_test) ** 2))
degree  0: 5-fold CV MSE =    23.33
degree  1: 5-fold CV MSE =     8.28
degree  2: 5-fold CV MSE =     7.34
degree  3: 5-fold CV MSE =     5.77
degree  4: 5-fold CV MSE =     6.55
degree  5: 5-fold CV MSE =     7.73
degree  6: 5-fold CV MSE =     7.08
degree  7: 5-fold CV MSE =    13.51
degree  8: 5-fold CV MSE =    44.50
degree  9: 5-fold CV MSE =    20.84
degree 10: 5-fold CV MSE =    68.31
chosen degree: 3
final test MSE: 4.54

CV found the U-shape and chose degree 3, and the untouched test set confirms it: 4.54, close to the noise floor of 4. Notice that the CV numbers are noisy (degree 6 beats degree 5, degree 9 beats degree 8). CV estimates are random variables too. When two settings are close, prefer the simpler one. Some people use the one-standard-error rule: pick the simplest model whose CV error is within one standard error of the best.

Regularization: penalize complexity directly

Choosing the degree is a coarse knob: 3 or 4, nothing in between. Regularization gives a smooth knob. Keep a flexible model, but add a penalty for large weights to the loss:

$$ J(w) = \underbrace{\sum_{i=1}^n \big(w^\top\phi(x_i) - y_i\big)^2}_{\text{fit the data}} \;+\; \underbrace{\lambda \sum_{j\ge1} w_j^2}_{\text{stay simple}} \qquad\text{(ridge / L2 regularization)} $$

Why do large weights mean complexity? Look back at the overfit curves. To snake through every point, a degree-12 polynomial needs huge coefficients of alternating sign that nearly cancel each other. In the run below the unregularized weights have norm about 5 million. Smooth functions only need modest weights. Penalizing \(\lVert w\rVert^2\) therefore penalizes wiggliness.

Setting the gradient to zero gives a closed form, almost the same as the normal equations:

$$ (X^\top X + \lambda I')\,w = X^\top y \qquad (I' = \text{identity with a 0 for the intercept, which we don't penalize}) $$

A bonus: adding \(\lambda I'\) makes the matrix well-conditioned, so ridge also fixes the numerical problems of high-degree fits.

import numpy as np

rng = np.random.default_rng(42)
def true_time(d):
    return 6 + 4 * d + 3 * np.sin(1.4 * d)
def make_deliveries(n):
    d = rng.uniform(0, 5, n)
    return d, true_time(d) + rng.normal(0, 2.0, n)
def poly_features(d, degree):
    return np.vander((d - 2.5) / 2.5, degree + 1, increasing=True)

d_tr, t_tr = make_deliveries(15)
d_te, t_te = make_deliveries(2000)

def ridge_fit(X, y, lam):
    """Minimize ||Xw - y||^2 + lam * ||w[1:]||^2  (don't penalize the intercept)."""
    P = np.eye(X.shape[1]); P[0, 0] = 0
    return np.linalg.solve(X.T @ X + lam * P, X.T @ y)

X_tr, X_te = poly_features(d_tr, 12), poly_features(d_te, 12)
for lam in [0, 1e-4, 1e-2, 1, 100]:
    w = ridge_fit(X_tr, t_tr, lam)
    print(f"lambda={lam:<7g} train={np.mean((X_tr@w-t_tr)**2):6.2f}  "
          f"test={np.mean((X_te@w-t_te)**2):12.2f}  |w|={np.linalg.norm(w):10.1f}")
lambda=0       train=  0.27  test=11162182397.57  |w|= 5174896.9
lambda=0.0001  train=  1.27  test=        5.57  |w|=      40.7
lambda=0.01    train=  1.31  test=        4.31  |w|=      18.2
lambda=1       train=  1.81  test=        4.67  |w|=      16.9
lambda=100     train= 19.93  test=       27.22  |w|=      17.7

This is the same degree-12 model that was a disaster in §2.2. A tiny penalty, \(\lambda = 0.01\), takes test MSE from \(10^{10}\) to 4.31, which is as good as the hand-picked cubic. Too much penalty (\(\lambda=100\)) flattens the model into underfitting. \(\lambda\) is a bias–variance dial: small \(\lambda\) means low bias and high variance, large \(\lambda\) the reverse. And how do you choose \(\lambda\)? With cross-validation, of course.

L2 vs L1

Ridge (L2): \(\lambda\sum w_j^2\)Lasso (L1): \(\lambda\sum |w_j|\)
EffectShrinks all weights smoothly toward 0Drives many weights to exactly 0
ResultSmall, spread-out weightsSparse model, i.e. automatic feature selection
Closed form?YesNo (needs iterative optimization)
Bayesian viewGaussian prior on \(w\)Laplace prior on \(w\)
Connections: regularization is a prior belief

The "Bayesian view" row is not a footnote. Minimizing squared error + \(\lambda\lVert w\rVert^2\) is exactly finding the most probable weights (MAP estimate) when you believe beforehand that weights are probably small (a Gaussian prior) and the noise is Gaussian. Regularization = data + prior belief, combined with Bayes' rule (Ch 4). Overfitting is what happens when you trust the data completely and have no prior at all.

Other weapons against overfitting

  • Early stopping: when training iteratively (gradient descent, a GA over generations), monitor validation error and stop when it starts rising. You'll use this in the GA lab.
  • Pruning: grow a big decision tree, then cut branches that don't help on validation data (§6.4).
  • More data / data augmentation: the most reliable cure for variance.
  • Ensembles: average many models (bagging, random forests).
  • Simpler features: drop irrelevant inputs, since each one is a new way to fit noise.

Learning curves: is more data worth buying?

Plot training and validation error against training-set size for a fixed model:

  • High-bias model: both curves plateau quickly at a high level, close together. More data won't help. Use a richer model.
  • High-variance model: a large gap that slowly closes as data grows. More data will help.

This is the most practical diagnostic in the chapter: it tells you whether to spend next week collecting data or redesigning the model.

Chapter summary

  • Learning minimizes empirical risk, but we care about true risk on unseen data from the same distribution (i.i.d.).
  • Training error always falls with complexity. Test error is U-shaped.
  • Expected test error = bias² + variance + σ². Simple models have high bias, flexible models high variance, and noise is irreducible.
  • Choose complexity with a validation set or k-fold CV. Use the test set once.
  • Regularization (\(\lambda\lVert w\rVert^2\)) is a smooth bias–variance dial, and is equivalent to a prior belief.
Bolt's next problem

The engineers move Bolt's predictor onto a cheap microcontroller and lose access to the training data. All they can do is send a weight vector to a server and get back its training and validation error. There is no gradient and no formula, only "try a vector, get a score." How do you find good weights now? Welcome to Chapter 3: local search and genetic algorithms.