2.6 Generalization

Imagine two college students, Ellie and Irene, preparing for a statistics final exam by practicing on past exams. Ellie memorizes every past question and its exact numerical answer word for word; scored on those practice exams, she gets 100%. Irene instead works to understand the underlying concepts and formulas; she gets 92% on the practice questions because of occasional arithmetic slips, yet when the real final exam arrives with brand-new problems, Irene scores 90% while Ellie flounders.

Machine learning models face the same divide. Our ultimate goal is never simply to score well on the finite training set we already have; it is to make accurate predictions on unseen examples drawn from the broader population, a property called generalization. In our synthetic linear regression earlier, we fitted 3 parameters to 1,000 examples, so memorization was impossible and training loss tracked validation loss closely. Once a model class becomes rich enough to bend around individual data points, however, driving training error to zero can make predictions on new data worse. In this section, we formalize the distinction between training error and generalization error, demonstrate underfitting and overfitting through polynomial curve fitting, unpack the bias--variance decomposition, and introduce validation sets and KK-fold cross-validation for principled model selection.

2.6.1 Training Error and Generalization Error#

In supervised learning, we assume that both our training examples and the future test examples we will encounter at deployment are drawn independently from the same underlying probability distribution P(x,y)P(\mathbf{x}, y)—the independent and identically distributed (i.i.d.) assumption.

Given a finite training dataset D={(x(1),y(1)),…,(x(n),y(n))}\mathcal{D} = \{(\mathbf{x}^{(1)}, y^{(1)}), \ldots, (\mathbf{x}^{(n)}, y^{(n)})\} of nn examples drawn i.i.d. from PP, the training error (or empirical risk) of a predictor ff under loss ll is the sample average over D\mathcal{D}:

Remp[f]=1n∑i=1nl(x(i),y(i),f(x(i))).(2.6.1)R_{\textrm{emp}}[f] = \frac{1}{n} \sum_{i=1}^n l\left(\mathbf{x}^{(i)}, y^{(i)}, f(\mathbf{x}^{(i)})\right). \tag{2.6.1}

By contrast, the generalization error (or true risk / population risk) is the expected loss on a fresh example (x,y)(\mathbf{x}, y) drawn from PP:

R[f]=E(x,y)∼P[l(x,y,f(x))]=∫l(x,y,f(x)) dP(x,y).(2.6.2)R[f] = \mathbb{E}_{(\mathbf{x}, y) \sim P}\Big[l\big(\mathbf{x}, y, f(\mathbf{x})\big)\Big] = \int l\big(\mathbf{x}, y, f(\mathbf{x})\big)\, dP(\mathbf{x}, y). \tag{2.6.2}

We want to find a function ff that minimizes the true risk R[f]R[f], yet we never have direct access to the distribution PP: we only observe the finite sample D\mathcal{D}, so our training algorithm minimizes Remp[f]R_{\textrm{emp}}[f] instead (empirical risk minimization).

Why can Remp[f^]R_{\textrm{emp}}[\hat{f}] underestimate R[f^]R[\hat{f}] so severely? If we picked a fixed function ff in advance, before looking at D\mathcal{D}, then by the law of large numbers Remp[f]R_{\textrm{emp}}[f] would be an unbiased estimate of R[f]R[f] with fluctuations of order 1/n1/\sqrt{n}. However, our trained model f^\hat{f} is not fixed independent of D\mathcal{D}: it was specifically selected from an entire model class F\mathcal{F} to minimize error on D\mathcal{D}. Whenever F\mathcal{F} is flexible enough to latch onto accidental noise quirks in D\mathcal{D}, the training error Remp[f^]R_{\textrm{emp}}[\hat{f}] becomes optimistically biased downward relative to the true risk R[f^]R[\hat{f}] (Exercise 4). To measure R[f^]R[\hat{f}] honestly, we must evaluate f^\hat{f} on an independent held-out test set (or validation set) D′\mathcal{D}' that played no role in fitting its parameters.

2.6.2 Underfitting and Overfitting#

Comparing training error against validation error diagnoses two opposite failure modes:

  • Underfitting (high bias): The model is too rigid to capture the true underlying trend in the data, so both training error and validation error remain high and close together.
  • Overfitting (high variance): The model is so flexible relative to the dataset size that it fits the random noise in the training examples in addition to the signal; training error becomes tiny while validation error climbs much higher, opening a large generalization gap R[f^]−Remp[f^]R[\hat{f}] - R_{\textrm{emp}}[\hat{f}].

2.6.2.1 Polynomial Curve Fitting#

We can watch underfitting, balanced fitting, and catastrophic overfitting unfold without leaving linear regression. Suppose a scalar input xx is drawn uniformly from [−1,1][-1, 1] and the true label is generated by a smooth curve plus Gaussian noise,

y=f∗(x)+ϵ,f∗(x)=5+1.2x−3.4x2+5.6x3,ϵ∼N(0,σ2),(2.6.3)y = f^*(x) + \epsilon, \qquad f^*(x) = 5 + 1.2x - 3.4x^2 + 5.6x^3, \qquad \epsilon \sim \mathcal{N}(0, \sigma^2), \tag{2.6.3}

with σ=0.1\sigma = 0.1. Note that the irreducible population noise floor for the squared error (y^−y)2(\hat{y} - y)^2 is σ2=0.01\sigma^2 = 0.01: even the true function f∗(x)f^*(x) incurs an expected squared error of 0.010.01 because of the unpredictable noise ϵ\epsilon.

To fit a curved function using linear regression, we map the scalar input xx to a vector of monomial polynomial features (1,x,x2,…,xk)⊤∈Rk+1(1, x, x^2, \ldots, x^k)^\top \in \mathbb{R}^{k+1}. A degree-kk polynomial

y^=∑j=0kwjxj(2.6.4)\hat{y} = \sum_{j=0}^k w_j x^j \tag{2.6.4}

is nonlinear in xx, yet linear in the weights w=(w0,…,wk)⊤\mathbf{w} = (w_0, \ldots, w_k)^\top. Thus we can fit any degree-kk polynomial on nn training points by constructing the Vandermonde design matrix X∈Rn×(k+1)\mathbf{X} \in \mathbb{R}^{n \times (k+1)} with entries Xij=(x(i))jX_{ij} = (x^{(i)})^j and calling lstsq (just as we did in Section 2.1.2.1). Let us generate n=20n = 20 training points and 1,0001{,}000 test points (enough to estimate test error accurately), and then compare three degrees: k=1k = 1 (a straight line), k=3k = 3 (a cubic), and k=19k = 19 (a degree-19 polynomial with 2020 parameters for 2020 points):

def target(x):
    """The cubic f* that generates the labels."""
    return 5 + 1.2 * x - 3.4 * x**2 + 5.6 * x**3

def make_data(rng, n, sigma):
    """Draw n inputs uniformly from [-1, 1] and label them by the noisy cubic."""
    x = rng.uniform(-1, 1, n)
    return x, target(x) + rng.normal(0, sigma, n)

sigma = 0.1                               # standard deviation of the noise
rng = np.random.default_rng()             # a new random draw on every run
x_train, y_train = make_data(rng, 20, sigma)  # few, so high degrees overfit
x_test, y_test = make_data(rng, 1000, sigma)

Below, features(x, d) builds the design matrix [1,x,…,xd][1, x, \ldots, x^d], fit_degree finds the exact least-squares weights, and mse computes the plain mean squared error (omitting the factor of 12\frac{1}{2} so the noise floor sits neatly at σ2=0.01\sigma^2 = 0.01):

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()

Let us plot the fits of degree 11, 33, and 1919 against the 2020 noisy training points and the true cubic:

xs = np.linspace(-1, 1, 200)
_, axes = d2l.plt.subplots(1, 3, figsize=(10, 3.4), sharey=True)
for ax, d in zip(axes, (1, 3, 19)):
    w = fit_degree(x_train, y_train, d)
    d2l.plot([xs, xs, x_train], [target(xs), features(xs, d) @ w, y_train],
             xlabel='x', ylim=(-7, 11), fmts=('--', '-', 'o'),
             legend=['cubic', 'fit', 'training data'] if d == 1 else None,
             axes=ax)
    ax.set_title(f'degree {d}')

Those three panels tell the whole story of the two classic failure modes of supervised learning:

  • Degree k=1k = 1 (underfitting): A straight line cannot bend to follow the S-shaped cubic; it misses training and test points alike.
  • Degree k=3k = 3 (well matched): A cubic has exactly the flexibility of f∗f^*; its fit is nearly indistinguishable from the true curve.
  • Degree k=19k = 19 (overfitting): With k+1=20k + 1 = 20 parameters and n=20n = 20 distinct training points, the polynomial has enough degrees of freedom to interpolate every single training point (Exercise 2). Between the data points, however, the curve oscillates wildly, sending the test error soaring by orders of magnitude.

What happens to the learned weights wjw_j themselves when the polynomial overfits? Let us print the training error, the test error, and the largest weight magnitude max⁡j∣w^j∣\max_j |\hat{w}_j| for each of the three degrees:

for d in (1, 3, 19):
    w = fit_degree(x_train, y_train, d)
    print(f'degree {d:2d}: train {mse(w, x_train, y_train):.2g}, '
          f'test {mse(w, x_test, y_test):.2g}, '
          f'largest |weight| {np.abs(w).max():.2g}')
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

Although exact numbers vary slightly with each random draw, the contrast is dramatic. Degree 11 suffers large errors on both splits (a test MSE around 22, roughly 200×200\times the σ2=0.01\sigma^2 = 0.01 noise floor). Degree 33 pushes both training and test errors right down to the σ2=0.01\sigma^2 = 0.01 floor, with its largest weight sitting near the true leading coefficient 5.65.6. Degree 1919 drives training error far below the noise floor—essentially to zero—while its test error explodes by many orders of magnitude. Look at its weights to see the mechanism: degree 1919 relies on huge positive and negative coefficients that delicately cancel at the 2020 training inputs and blow up everywhere else.

Sweeping across every degree from 11 to 1919 maps out the full transition on a logarithmic scale:

degrees = list(range(1, 20))
weights = [fit_degree(x_train, y_train, d) for d in degrees]
train_err = [mse(w, x_train, y_train) for w in weights]
test_err = [mse(w, x_test, y_test) for w in weights]
d2l.plot(degrees, [train_err, test_err], xlabel='polynomial degree',
         ylabel='mean squared error', legend=['train', 'test'],
         yscale='log', ylim=(1e-4, 1e3))

As kk increases, the training error decreases monotonically (since adding xk+1x^{k+1} only enlarges the subspace of functions available to least squares), plunging far below σ2\sigma^2 by k=19k = 19. The test error, by contrast, traces a classic U-shaped curve: it drops steeply to its minimum at k=3k = 3 (or a nearby degree) as underfitting disappears, and then climbs by orders of magnitude as extra powers of xx fit the random noise in our 20 training points. Because x17x^{17} and x19x^{19} look almost identical on [−1,1][-1, 1], the high-degree fit cancels giant positive multiples of one against giant negative multiples of the other to thread the 20 noisy points, an instability that we cure directly with weight decay in Section 2.7.

2.6.2.2 Bias and Variance#

Why does model complexity produce a U-shaped generalization curve? Let us decompose the expected squared error of a model f^D\hat{f}_{\mathcal{D}} trained on a random dataset D\mathcal{D} at a test point xx where y=f∗(x)+ϵy = f^*(x) + \epsilon (with E[ϵ]=0\mathbb{E}[\epsilon] = 0, Var(ϵ)=σ2\mathrm{Var}(\epsilon) = \sigma^2, and ϵ\epsilon independent of D\mathcal{D}). Write fˉ(x)=ED[f^D(x)]\bar{f}(x) = \mathbb{E}_{\mathcal{D}}[\hat{f}_{\mathcal{D}}(x)] for the average predictor across all possible training sets of size nn. Adding and subtracting f∗(x)f^*(x) and fˉ(x)\bar{f}(x) inside ED,ϵ[(f^D(x)−y)2]\mathbb{E}_{\mathcal{D}, \epsilon}[(\hat{f}_{\mathcal{D}}(x) - y)^2] and noting that the cross terms vanish yields the famous bias--variance decomposition:

ED,ϵ ⁣[(f^D(x)−y)2]=(fˉ(x)−f∗(x))2⏟bias2(x)+ED ⁣[(f^D(x)−fˉ(x))2]⏟variance(x)+σ2⏟noise.(2.6.5)\begin{aligned} \mathbb{E}_{\mathcal{D}, \epsilon}\!\left[\big(\hat{f}_{\mathcal{D}}(x) - y\big)^2\right] &= \underbrace{\big(\bar{f}(x) - f^*(x)\big)^2}_{\textrm{bias}^2(x)} \\ &\quad + \underbrace{\mathbb{E}_{\mathcal{D}}\!\left[\big(\hat{f}_{\mathcal{D}}(x) - \bar{f}(x)\big)^2\right]}_{\textrm{variance}(x)} + \underbrace{\sigma^2}_{\textrm{noise}}. \end{aligned} \tag{2.6.5}

Every model's expected test error is the sum of three nonnegative pieces:

  1. Squared bias (fˉ(x)−f∗(x))2(\bar{f}(x) - f^*(x))^2: How far the average fitted model (even averaged over infinitely many training datasets) sits from the true function f∗(x)f^*(x). Rigid models (like a straight line k=1k = 1 on a cubic) have high bias.
  2. Variance ED[(f^D(x)−fˉ(x))2]\mathbb{E}_{\mathcal{D}}[(\hat{f}_{\mathcal{D}}(x) - \bar{f}(x))^2]: How sensitively the fitted model fluctuates from one random training sample D\mathcal{D} to the next. Overly flexible models (k=12k = 12) swing wildly with every new draw of 20 points, suffering huge variance.
  3. Irreducible noise σ2\sigma^2: The variance of the label yy around f∗(x)f^*(x) itself, which no predictor can ever beat.

In our polynomial experiment we can measure all three terms directly. Let us keep the 2020 training inputs fixed and redraw only their label noise. Because the least-squares weights depend linearly on y\mathbf{y} and the noise has mean zero, the average fit fˉ\bar{f} is simply the fit to the noiseless labels f∗(x(i))f^*(x^{(i)}), which gives the squared bias exactly; refitting across 200200 independent draws of the training noise estimates the variance at every test point:

noise = rng.normal(0, sigma, (len(x_train), 200))   # 200 draws of the noise
bias2, var = [], []
for d in degrees:
    w_avg = fit_degree(x_train, target(x_train), d)               # average fit
    W = fit_degree(x_train, target(x_train)[:, None] + noise, d)  # fit per draw
    bias2.append(mse(w_avg, x_test, target(x_test)))
    var.append((features(x_test, d) @ W).var(axis=1).mean())
d2l.plot(degrees, [bias2, var, [sigma**2] * len(degrees),
                   np.add(bias2, var) + sigma**2],
         xlabel='polynomial degree', ylabel='mean squared error',
         fmts=('-', 'C1-.', 'g:', 'm--'), yscale='log', ylim=(1e-4, 1e3))
d2l.plt.legend(['bias$^2$', 'variance', r'noise $\sigma^2$',
                'expected test error'], ncol=2, frameon=False,
               loc='lower center', bbox_to_anchor=(0.5, 1));  # above the plot

Look how cleanly the curves explain the U-shape of test error: squared bias is large at degrees 11 and 22, then collapses to zero at degree 33 (the first family rich enough to contain the cubic). Variance, meanwhile, climbs with every added degree, starting around σ2(k+1)/n\sigma^2(k+1)/n (the noise variance scaled by parameters per example; see exercise 4) and eventually rising orders of magnitude past the noise floor. Underfitting is error dominated by bias; overfitting is error dominated by variance. The idealized trade-off shown in Figure 2.6.1 recurs across classical statistics and machine learning: training error drops steadily with complexity, while test error reaches its minimum at an intermediate sweet spot (never dropping below σ2\sigma^2).

Figure 2.6.1:

Training and test error against model complexity. To the left of the best complexity the model underfits and both errors are high; to the right it overfits, its training error falls below the noise level, and the generalization gap widens.

2.6.2.3 Model Complexity#

As Figure 2.6.1 summarizes schematically, increasing model complexity (capacity) reduces bias while increasing variance. The optimal generalization performance sits at the sweet spot where the sum of squared bias and variance reaches its minimum. In classical parametric models, complexity is governed by the number of parameters pp and the magnitude of the weights ∥w∥\|\mathbf{w}\|; in deep learning (Section 4.5), we will see how regularization, architecture design, and dataset scale reshape this curve.

2.6.2.4 Dataset Size#

Besides restricting model complexity, the most direct way to crush variance is to collect more training data. For a fixed polynomial degree kk, fitting to n=1,000n = 1{,}000 points instead of n=20n = 20 averages out the random noise and pins down even high-degree coefficients cleanly (with estimation variance decaying as (k+1)σ2/n(k + 1)\sigma^2 / n). Let us watch how degrees 11, 33, and 1919 respond as we grow a fresh training set from n=20n = 20 to n=1,000n = 1{,}000 examples:

for n in (20, 50, 100, 1000):
    x, y = make_data(rng, n, sigma)          # a fresh training set of size n
    errs = [mse(fit_degree(x, y, d), x_test, y_test) for d in (1, 3, 19)]
    print(f'n = {n:4d}: test error of degrees 1, 3, 19:',
          ', '.join(f'{e:.2g}' for e in errs))
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

Look at the contrast. Growing the dataset rescues the overfitting degree-19 polynomial dramatically: its test error plunges by orders of magnitude by n=100n = 100, and by n=1,000n = 1{,}000 it matches the true cubic. Meanwhile, the underfitting straight line barely budges (its test error remains stuck around 22): collecting more data shrinks variance, but it can never cure bias. A model is never "too complex" in isolation; it is only too complex relative to the signal and data available to constrain it. That scaling principle is one major reason deep learning surged once massive digital datasets became commonplace, though deep networks will add important twists to the classical curve in Section 4.5.

2.6.3 Model Selection#

2.6.3.1 Validation Sets#

In our synthetic experiment we knew f∗(x)f^*(x) and generated 1,000 test points at will. In a real problem, how should we choose hyperparameters, such as the polynomial degree kk, the learning rate η\eta, or the weight decay strength λ\lambda?

We can never choose hyperparameters by minimizing training error, because training error always favors the most complex, memorization-prone model (k=19k = 19). Nor should we tune hyperparameters by repeatedly consulting the final test set, which would leak test-set noise into our design choices (Section 3.5). Instead, we partition our available data into three disjoint splits:

  1. Training set: Used to fit the model parameters (w,b)(\mathbf{w}, b) for each candidate hyperparameter setting.
  2. Validation set: Used to compare candidate hyperparameter settings and select the winner (model selection).
  3. Test set: Held in a vault and evaluated once at the very end to report an unbiased estimate of the selected model's generalization error.

2.6.3.2 Cross-Validation#

When a dataset is small (say, n=20n = 20 or n=100n = 100 clinical records), carving off a fixed 20% validation set leaves too few examples to train on and too few to validate reliably. KK-fold cross-validation (Figure 2.6.2) makes every example do double duty. We partition the dataset randomly into KK equal-sized disjoint subsets (folds) D1,…,DK\mathcal{D}_1, \ldots, \mathcal{D}_K (typically K=5K = 5 or K=10K = 10). In round i∈{1,…,K}i \in \{1, \ldots, K\}, we train the model from scratch on the K−1K - 1 folds D∖Di\mathcal{D} \setminus \mathcal{D}_i and evaluate its validation loss on the held-out fold Di\mathcal{D}_i. Averaging the KK held-out losses gives the KK-fold cross-validation score, and once the winning hyperparameter is chosen, we retrain the model on all nn examples. (In the extreme case K=nK = n, called leave-one-out cross-validation, each fold is a single data point; for linear least squares, a remarkable algebraic identity computes all nn leave-one-out residuals from a single fit without retraining nn times—see Exercise 6.)

Figure 2.6.2:

In KK-fold cross-validation (K=5K = 5 shown), the dataset is partitioned into KK folds; each round holds out one fold for validation (orange) and trains on the remaining K−1K - 1 folds.

Folds must come from a random permutation, because real datasets often arrive sorted, and with folds of only four points a single split is noisy. So kfold_splits below draws ten independent random partitions into K=5K = 5 folds (repeated cross-validation), and cv_error averages the validation error of a polynomial fit over all of their folds:

def kfold_splits(rng, n, K=5, repeats=10):
    """Random partitions of the indices 0, ..., n-1 into K folds."""
    return [np.array_split(rng.permutation(n), K) for _ in range(repeats)]

def cv_error(x, y, d, splits):
    """Validation error of the degree-d fit, averaged over all folds."""
    return np.mean([mse(fit_degree(np.delete(x, f), np.delete(y, f), d),
                        x[f], y[f]) for folds in splits for f in folds])

Let us select the polynomial degree using strictly the 2020 training examples, evaluating every degree on the same folds for a fair comparison, and check how closely that choice matches the true test-set optimum (which cross-validation never sees):

splits = kfold_splits(rng, len(x_train))  # the same folds for every degree
cv_err = [cv_error(x_train, y_train, d, splits) for d in degrees]
print('cross-validation picks degree:', degrees[np.argmin(cv_err)])
print('lowest test error at degree:  ', degrees[np.argmin(test_err)])
cross-validation picks degree: 3
lowest test error at degree:   3

Let us plot the 5-fold cross-validation curve right alongside the test-error curve across all 19 degrees:

d2l.plot(degrees, [test_err, cv_err], xlabel='polynomial degree',
         ylabel='mean squared error', fmts=('m--', 'g-.'), yscale='log',
         ylim=(1e-4, 1e3))
d2l.plt.legend(['test', '5-fold cross-validation'], ncol=2, frameon=False,
               loc='lower center', bbox_to_anchor=(0.5, 1));  # above the plot

Without ever glancing at the test set, repeated 5-fold cross-validation reliably locates the bottom of the test-error bowl, usually selecting degree 33 or occasionally a nearby degree whose test error is nearly indistinguishable. Near the minimum, the two curves track within a small factor, with cross-validation naturally a bit noisier since it averages over 2020 points instead of 1,0001{,}000. At high degrees both curves shoot up by orders of magnitude. Cross-validation has a reason to rise even earlier than the test error: each fold trains on only 1616 points rather than 2020, so degree 1515 already interpolates all 1616 training points, and any validation point near the edges of [−1,1][-1, 1] falls outside the fitted range where high-degree polynomials explode. With a single draw of 2020 points, however, either curve may be the first to rise.

How should we pick KK? Because every fold trains on only a fraction (K−1)/K(K - 1) / K of the dataset, its fitted model is slightly worse than a model trained on all nn examples, giving KK-fold cross-validation a slight pessimistic bias (exercise 5 works it out exactly). Pushing K=nK = n (leave-one-out cross-validation) nearly eliminates that bias. For a general learner, however, it demands nn separate fits per candidate. And for an unstable learner such as a decision tree, where removing a single example can change the whole model, its nn nearly identical training sets can make the estimate noisier than that of a coarser split. This is why K=5K = 5 or K=10K = 10 is the usual default when each fit is expensive (Kohavi, 1995). Least squares is neither expensive nor unstable: a single fit yields all nn leave-one-out residuals, and the fit changes smoothly with the data.

Let us measure the bias and the noise for our cubic. On each of 500 fresh training sets of 20 points, we fit the cubic to all 20 points and record its test error, together with three estimates of that error that use the 20 points alone: leave-one-out (K=20K = 20, one point per fold), 5-fold on a single random split, and 5-fold repeated over ten splits:

loo = kfold_splits(rng, 20, K=20, repeats=1)  # K = n: one point per fold
est = {'test error': [], 'leave-one-out': [], '5-fold, 1 split': [],
       '5-fold, 10 splits': []}
for _ in range(500):                          # 500 fresh training sets
    x, y = make_data(rng, 20, sigma)
    est['test error'].append(mse(fit_degree(x, y, 3), x_test, y_test))
    est['leave-one-out'].append(cv_error(x, y, 3, loo))
    est['5-fold, 1 split'].append(
        cv_error(x, y, 3, kfold_splits(rng, 20, repeats=1)))
    est['5-fold, 10 splits'].append(cv_error(x, y, 3, kfold_splits(rng, 20)))
for name, e in est.items():
    print(f'{name:18s} mean {np.mean(e):.4f}   std {np.std(e):.4f}')
test error         mean 0.0135   std 0.0045
leave-one-out      mean 0.0149   std 0.0252
5-fold, 1 split    mean 0.0200   std 0.0519
5-fold, 10 splits  mean 0.0175   std 0.0320

On average, leave-one-out lands close to the test error, within about a tenth of it. Both 5-fold estimates sit above the leave-one-out estimate, reflecting the pessimistic bias of training on 16 points instead of 19. Among the three cross-validation estimates, leave-one-out also has the smallest standard deviation across the 500 draws, so here the folklore that it is the noisier estimate does not hold. Repeating the 5-fold split ten times narrows its spread, but not down to that of leave-one-out: much of the spread comes from the luck of which 20 points were drawn, not from how they were split. For least squares, then, leave-one-out is both cheap and the most accurate of the three; for the networks of later chapters, where a single fit takes minutes or hours, a coarse split remains the practical choice.

Selecting a discrete polynomial degree worked here because our features came in a natural hierarchy 1,x,x2,…,xk1, x, x^2, \ldots, x^k. What should we do when a dataset arrives with hundreds of unordered features and no obvious way to drop columns one by one? In Section 2.7, we replace discrete feature selection with a continuous penalty on the weight norm.

2.6.4 Summary#

Supervised learning minimizes empirical risk Remp[f]R_{\textrm{emp}}[f] on a finite training sample while aiming for low population risk R[f]=E[l(f(x),y)]R[f] = \mathbb{E}[l(f(\mathbf{x}), y)] on unseen data. Because optimization chooses f^\hat{f} specifically to fit the training set, Remp[f^]R_{\textrm{emp}}[\hat{f}] is optimistically biased downward whenever the model class is flexible enough to absorb label noise. Expected squared test error decomposes into squared bias, estimation variance, and irreducible noise σ2\sigma^2: rigid models underfit with high bias, overly flexible models on small samples overfit with high variance, and collecting more training data shrinks variance as 1/n1/n without reducing bias. Because training error always favors memorization and repeated queries contaminate the final test set, hyperparameters must be chosen on a held-out validation split or via KK-fold cross-validation.

2.6.5 Exercises#

  1. When IID fails. Give three examples in which dependent observations make treating a dataset as IID inadvisable. For each, state whether a random train/validation split overestimates or underestimates the generalization error, and describe a split that avoids the problem.

  2. Exact polynomial regression. Show that when the nn training inputs x(1),…,x(n)x^{(1)}, \ldots, x^{(n)} are distinct, a polynomial of degree n−1n-1 fits the nn labels exactly, and explain where distinctness is used. What does least squares return when two inputs coincide but their labels differ?

  3. [code] A better basis for degree 19. The high powers x17x^{17} and x19x^{19} differ by less than 0.05 anywhere on [−1,1][-1, 1], so the columns of features(x, 19) are nearly parallel. The Chebyshev polynomials T0,…,T19T_0, \ldots, T_{19} span the same functions but stay between −1-1 and 11 on the interval.

    1. Predict first: if we fit degree 19 to the 20 training points in the Chebyshev basis, which of the training error, the test error, and the largest weight will change, and by how much?
    2. Check your prediction over several runs: replace features(x, 19) by np.polynomial.chebyshev.chebvander(x, 19) for both the training and the test inputs, and compare the two design matrices' condition numbers (np.linalg.cond), the training and test errors, and the largest weights.
    3. Explain why the two fits are the same polynomial in exact arithmetic, and which of your numbers differ in float64 and why. Does the better basis rescue degree 19 on 20 points? What does your answer say about the size of the weights as a measure of complexity?
  4. Optimism of the training error. ● Consider least squares with a fixed n×pn \times p design matrix X\mathbf{X} of full column rank and labels y=Xw∗+ϵ\mathbf{y} = \mathbf{X}\mathbf{w}^* + \boldsymbol{\epsilon}, whose noise terms are independent with mean zero and variance σ2\sigma^2. The fitted predictions are y^=Hy\hat{\mathbf{y}} = \mathbf{H}\mathbf{y} with H=X(X⊤X)−1X⊤\mathbf{H} = \mathbf{X}(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top.

    1. Show that the expected training error is E[∥y−y^∥2]/n=σ2(n−p)/n\mathbb{E}[\|\mathbf{y} - \hat{\mathbf{y}}\|^2]/n = \sigma^2 (n - p)/n. Hint: y−y^=(I−H)ϵ\mathbf{y} - \hat{\mathbf{y}} = (\mathbf{I} - \mathbf{H})\boldsymbol{\epsilon}, and the trace of I−H\mathbf{I} - \mathbf{H} is n−pn - p.
    2. Draw fresh labels y′=Xw∗+ϵ′\mathbf{y}' = \mathbf{X}\mathbf{w}^* + \boldsymbol{\epsilon}' at the same inputs. Show that the expected error of y^\hat{\mathbf{y}} on them is σ2(n+p)/n\sigma^2 (n + p)/n, so that the training error underestimates it by 2σ2p/n2\sigma^2 p/n. Show that σ2p/n\sigma^2 p/n is the variance of the predictions, averaged over the nn inputs.
    3. Evaluate both expressions for the cubic fit of Section 2.6.2.1 (n=20n = 20, p=4p = 4, σ=0.1\sigma = 0.1) and compare them with the training and test errors of degree 3 over several runs of the experiment. Explain the differences: how much does the training error of a single run spread around its expectation, and why does the formula of (b), which holds at the training inputs, not apply exactly to the test inputs?
  5. KK-fold cross-validation.

    1. Suppose that a model trained on mm examples has expected generalization error R(m)=R∞+c/mR(m) = R_\infty + c/m with c>0c > 0. Each fold's model trains on (K−1)n/K(K-1)n/K examples. Compute the bias of the KK-fold estimate relative to R(n)R(n), the error of the model trained on all nn examples. Express the bias as a fraction of R(n)−R∞R(n) - R_\infty and evaluate this fraction for K=2K = 2, 55, 1010, and nn.
    2. After selecting a hyperparameter by cross-validation, the final model is retrained on all nn examples. Explain why a hyperparameter whose best value depends on the training-set size complicates this step, and give an example.
  6. Leave-one-out shortcut. ● Leave-one-out cross-validation requires nn model fits for a general learner. Consider least squares with the design matrix X\mathbf{X}, whose rows are x(i)⊤\mathbf{x}^{(i)\top}. Let A=X⊤X\mathbf{A} = \mathbf{X}^\top\mathbf{X} and assume that it remains invertible when any one row of X\mathbf{X} is removed. Let y^(i)\hat{y}^{(i)} be the prediction at x(i)\mathbf{x}^{(i)} of the fit on all nn examples, let y^(−i)\hat{y}^{(-i)} be the prediction at x(i)\mathbf{x}^{(i)} of the fit that omits example ii, and let hi=x(i)⊤A−1x(i)h_i = \mathbf{x}^{(i)\top}\mathbf{A}^{-1}\mathbf{x}^{(i)}. Use the Sherman--Morrison identity (Section 21.2)

(A−uu⊤)−1=A−1+A−1uu⊤A−11−u⊤A−1u(\mathbf{A} - \mathbf{u}\mathbf{u}^\top)^{-1} = \mathbf{A}^{-1} + \frac{\mathbf{A}^{-1}\mathbf{u}\mathbf{u}^\top\mathbf{A}^{-1}}{1 - \mathbf{u}^\top\mathbf{A}^{-1}\mathbf{u}}

with u=x(i)\mathbf{u} = \mathbf{x}^{(i)} to show that

y(i)−y^(−i)=y(i)−y^(i)1−hi.(2.6.6)y^{(i)} - \hat{y}^{(-i)} = \frac{y^{(i)} - \hat{y}^{(i)}}{1 - h_i}. \tag{2.6.6}

State what leave-one-out cross-validation then costs for least squares compared with a single fit.

Discussions