Generalization

Dive into Deep Learning · §2.6

Generalization, Bias–Variance & Model Selection
empirical vs. population risk · underfitting & overfitting · bias–variance decomposition · cross-validation

Memorizing Samples vs. Learning Population Patterns

The Central Problem of Supervised Learning

Fitting 20 polynomial weights to 20 noisy points from a cubic curve drives the training loss to zero while failing catastrophically on new inputs:

  • Degree 1 (left — underfitting): Too rigid to bend; misses both the points and the true curve.
  • Degree 3 (middle — balanced): Matches the cubic family and tracks the dashed true curve.
  • Degree 19 (right — overfitting): 20 parameters thread all 20 noisy points, oscillating wildly between them.

Empirical Risk (Training Error) vs. Population Risk

Statistical Foundations

R_{\textrm{emp}}[f] = \frac{1}{n} \sum_{i=1}^n l\bigl(f(\mathbf{x}^{(i)}), y^{(i)}\bigr), \quad R[f] = \mathbb{E}_{(\mathbf{x}, y) \sim P}\Bigl[l\bigl(f(\mathbf{x}), y\bigr)\Bigr]

  • Empirical risk (R_{\textrm{emp}}[f]): Average loss on the n training examples \mathcal{D}; minimized during training.
  • Population risk (R[f]): Expected loss on unseen examples drawn from P(\mathbf{x}, y); governs deployment accuracy.
  • Generalization gap (R[\hat{f}] - R_{\textrm{emp}}[\hat{f}]): Measures how much worse \hat{f} performs on new data than on \mathcal{D}.

Why Training Error Is Optimistically Biased Downward

The Optimism of Empirical Risk Minimization

\mathbb{E}\bigl[R_{\textrm{emp}}\bigr] = \sigma^2\Bigl(1 - \frac{p}{n}\Bigr), \qquad \mathbb{E}\bigl[R_{\textrm{in-sample}}\bigr] = \sigma^2\Bigl(1 + \frac{p}{n}\Bigr)

  • Selection bias of optimization: Because \hat{f} is chosen to minimize loss on \mathcal{D}, each fitted parameter absorbs \sigma^2/n of training noise.
  • Exact interpolation at p = n = 20: Expected training MSE vanishes (\sigma^2(1 - 20/20) = 0) even when fitting pure noise.

Polynomial Regression: Linear Fitting on Monomials

Controlled Capacity Benchmark

def features(x, d):
    """Design matrix whose columns are the powers x^0, x^1, ..., x^d."""
    return x.reshape(-1, 1) ** np.arange(d + 1)

def fit_degree(x, y, d):
    """Least-squares weights of the degree-d polynomial fitted to (x, y)."""
    return np.linalg.lstsq(features(x, d), y, rcond=None)[0]

def mse(w, x, y):
    """Mean squared error of the polynomial with weights w on (x, y)."""
    return ((features(x, len(w) - 1) @ w - y) ** 2).mean()
  • Linear in the weights \mathbf{w}: Mapping x \in [-1, 1] to [1, x, x^2, \ldots, x^d] turns degree-d polynomial fitting into linear least squares \hat{\mathbf{y}} = \mathbf{X}\mathbf{w} on n = 20 points from f^*(x) = 5 + 1.2x - 3.4x^2 + 5.6x^3 (\sigma = 0.1).

Degrees 1, 3, and 19: Errors and Weight Explosion

Quantitative Diagnosis

degree  1: train 0.83, test 2, largest |weight| 4.1
degree  3: train 0.011, test 0.011, largest |weight| 5.8
degree 19: train 2.4e-19, test 2.9e+06, largest |weight| 9.4e+06
  • Why weights explode at degree 19: High powers x^{17} and x^{19} are nearly collinear on [-1, 1], so least squares cancels huge alternating coefficients (|\hat{w}_j| > 10^6) to thread the 20 points.

The U-Shaped Test Error Curve Across Degrees 1 to 19

Training vs. Generalization Trajectory

Sweeping polynomial degree d from 1 to 19 contrasts the monotonic decline of training error with the U-shaped trajectory of test error:

  • Monotonic training error: Because degree d+1 strictly contains degree d (by setting w_{d+1} = 0), adding monomials can never increase least-squares training error.
  • Test error sweet spot (d = 3): Test MSE drops by two orders of magnitude from d = 1 to d = 3, then climbs relentlessly as extra parameters fit noise.
  • Diagnostic rule: High training error signals underfitting; low training error paired with a large generalization gap signals overfitting.

The Bias–Variance Decomposition of Expected Test Error

Theoretical Decomposition

\mathbb{E}_{\mathcal{D}, \epsilon}\Bigl[\bigl(y - \hat{f}_{\mathcal{D}}(x)\bigr)^2\Bigr] = \bigl(f^*(x) - \bar{f}(x)\bigr)^2 + \operatorname{Var}_{\mathcal{D}}\bigl(\hat{f}_{\mathcal{D}}(x)\bigr) + \sigma^2

  • Squared bias: Systematic approximation error of the model family even with infinite data (dominates in rigid models d = 1, 2).
  • Variance & noise \sigma^2: Sensitivity of \hat{f}_{\mathcal{D}} to random training sample noise (dominates in flexible models d \gg 3), above the irreducible floor \sigma^2.

Empirical Bias² and Variance Across Polynomial Degrees

Measuring the Decomposition

By redrawing the 20-point training noise 200 times at fixed inputs, we compute \textrm{bias}^2 (from the noiseless average fit) and \textrm{variance} (from the spread across the 200 fits) at every degree:

  • Squared bias collapses at d = 3: Huge at d = 1, 2 (where lines and parabolas cannot match a cubic), then drops to zero for all d \geq 3 because every family d \geq 3 contains f^*(x).
  • Variance climbs monotonically: Scales as \approx \sigma^2 (d + 1) / n at low degrees before exploding as the Vandermonde matrix becomes nearly singular near d = 19.
  • Optimal trade-off: The sum \textrm{bias}^2 + \textrm{variance} + \sigma^2 achieves its minimum at d = 3.

Model Complexity and the Classical Capacity Curve

Bias–Variance Trade-Off

Across classical parametric model families, increasing capacity shifts error from bias to variance:

  • Left of optimum (Underfitting): Model capacity is too low; high bias keeps both training risk and population risk elevated.
  • Right of optimum (Overfitting): Capacity outstrips the information in n examples; training error drops below the noise floor \sigma^2 while variance drives test risk up.
  • Weight norm as continuous capacity: Even at degree 19, functions with small coefficients \|\mathbf{w}\|_2 cannot oscillate wildly—motivating weight decay in the next section.

Dataset Scale: More Data Cures Variance, Never Bias

Sample Complexity

n =   20: test error of degrees 1, 3, 19: 1.8, 0.013, 1.4e+04
n =   50: test error of degrees 1, 3, 19: 1.9, 0.011, 0.37
n =  100: test error of degrees 1, 3, 19: 1.9, 0.011, 0.014
n = 1000: test error of degrees 1, 3, 19: 1.9, 0.01, 0.011
  • Variance decays as O(p / n): Growing n from 20 to 1{,}000 brings degree-19 test MSE right down to the \sigma^2 = 0.01 floor, whereas the underfitted degree-1 line stays stuck near 2.

Principled Model Selection: The Three-Way Data Split

Preventing Test-Set Leakage

  • Never select on training error: Training error always favors the most complex, memorization-prone model (d = 19).
  • Never tune on the test set: Repeatedly querying the test set fits hyperparameters to test-set noise.
  • Three-way partition: Fit (\mathbf{w}, b) on the training split, select hyperparameters (d, \eta, \lambda) on the validation split, and evaluate the winner once on the test split.

K-Fold Cross-Validation When Data Are Scarce

Sample-Efficient Validation

When total data are scarce (n = 20), carving out a separate validation split wastes precious training examples. K-fold cross-validation partitions the n examples into K equal folds:

  • Rotate the held-out fold: In round k \in \{1, \ldots, K\}, train from scratch on K - 1 folds (\frac{K-1}{K}n examples) and validate on held-out fold k; average the K validation scores.
  • Refit the winner: Once the best hyperparameter d^* is selected, retrain the final model on all n examples.
  • Choosing K (5 or 10 vs. K = n): Smaller K trains on fewer examples per fold (slight pessimistic bias); leave-one-out (K = n) is nearly unbiased but costs n fits for a general learner (one for least squares).

Selecting Degree via 5-Fold Cross-Validation

Cross-Validation in Code

Using strictly the n = 20 training examples (K = 5, so each fold trains on 16 points and validates on 4), 5-fold cross-validation locates the bottom of the test-error curve without ever seeing the test set:

cross-validation picks degree: 3
lowest test error at degree:   3
  • Accurate model selection: Cross-validation consistently picks degree 3 (or a neighboring degree whose test MSE is within a tiny fraction of optimal).
  • Why CV can rise earlier at high degrees: Each fold trains on 16 points rather than 20, so degree 15 already interpolates the fold and explodes on held-out boundary points.

Concept Check: Risk Gaps, Sample Size & CV Cost

Check Your Understanding

Apply the principles of generalization and model selection to these three problems:

  1. Statistical significance of a gap: A model achieves training loss 0.020 and validation loss 0.030 on n' = 400 held-out examples, where per-example loss has standard deviation \sigma_l = 0.04. Could this 0.010 gap be a random fluctuation of the validation set?
  2. When to collect more data: Model A has training error 1.9 and validation error 2.0. Model B has training error 10^{-14} and validation error 10^4. For which model will collecting 10\times more training examples improve validation performance?
  3. Leave-one-out shortcut: Naive leave-one-out CV over 19 polynomial degrees on n = 20 points needs 19 \times 20 = 380 fits. With the identity y^{(i)} - \hat{y}^{(-i)} = (y^{(i)} - \hat{y}^{(i)}) / (1 - H_{ii}), \mathbf{H} = \mathbf{X}(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top, how many fits are needed?

Answers:

  1. The standard error is \sigma_l / \sqrt{n'} = 0.04 / 20 = 0.002, so the 0.010 gap is 5 standard errors: a genuine gap.
  2. Model B (overfitting, high variance; more data crushes variance). Model A underfits (high bias): more data leaves it near 2.0, so it needs a richer model class.
  3. Only 19 fits (one per degree): one fit’s residuals and the diagonal H_{ii} give the exact leave-one-out residuals in O(n) arithmetic.

Summary & Key Takeaways

Summary

Concept / Phenomenon Mathematical Expression Scaling / Behavior Practical Action / Remedy
Empirical vs. True Risk R_{\textrm{emp}}[f] = \frac{1}{n}\sum_i l_i vs. R[f] = \mathbb{E}[l] \mathbb{E}[R_{\textrm{emp}}] = \sigma^2(1 - p/n) < \mathbb{E}[R] Never evaluate or select models on training error
Underfitting (High Bias) \textrm{bias}^2(x) = (\bar{f}(x) - f^*(x))^2 \gg \sigma^2 Both train and val errors high (d=1) Increase model capacity / add features (more data won’t help)
Overfitting (High Variance) \operatorname{Var}(\hat{f}_{\mathcal{D}}(x)) \approx \sigma^2 p / n \gg \sigma^2 Train error \to 0, val error explodes (d=19) Add training data (n \uparrow), reduce p, or apply weight decay (§2.7)
Bias–Variance Identity \mathbb{E}[(y - \hat{f}(x))^2] = \textrm{bias}^2 + \operatorname{Var} + \sigma^2 U-shaped test risk minimized at intermediate d^* Balance approximation capacity against sample size n
Validation & K-Fold CV Average loss across K held-out folds \mathcal{D}_k Trains on \frac{K-1}{K}n points per fold (K=5 or 10) Tune all hyperparameters on val/CV; touch test set only once