3.5 Generalization in Classification

Our Fashion-MNIST classifier achieved roughly 83%83\% accuracy on 10,00010{,}000 validation images. How far can we trust that number as a guarantee of performance on future garments? Two fundamental obstacles stand in the way:

  1. Finite-sample uncertainty and test-set reuse: Even a fresh test set of n=10,000n = 10{,}000 images is only a finite random sample, and worse still, in real development we consult the same evaluation split repeatedly as we compare models and tune hyperparameters.
  2. Memorization vs. learning: In high dimensions where every training image is distinct, a lookup-table memorizer achieves 100%100\% training accuracy while guessing randomly on every new image. Why does a low training error for a linear classifier certify low population error when a memorizer's zero training error certifies nothing?

Where Section 2.6 introduced overfitting and validation splits qualitatively for regression, this section makes generalization quantitative for classification: we derive exact and asymptotic confidence intervals for a test set of size nn, quantify how selection bias and adaptive overfitting inflate scores under test-set reuse, and introduce the Vapnik--Chervonenkis (VC) dimension and uniform convergence from statistical learning theory.

3.5.1 The Test Set#

3.5.1.1 Empirical and Population Error#

Fix a single classifier ff before drawing an independent test set D={(x(i),y(i))}i=1n\mathcal{D} = \{(\mathbf{x}^{(i)}, y^{(i)})\}_{i=1}^n i.i.d. from the population distribution P(X,Y)P(X, Y). Its empirical error on D\mathcal{D} and its true population error are

ϵD(f)=1n∑i=1n1(f(x(i))≠y(i)),ϵ(f)=P(f(X)≠Y).(3.5.1)\epsilon_\mathcal{D}(f) = \frac{1}{n}\sum_{i=1}^n \mathbf{1}\left(f(\mathbf{x}^{(i)}) \neq y^{(i)}\right), \qquad \epsilon(f) = P\left(f(X) \neq Y\right). \tag{3.5.1}

Because ff was fixed in advance, each error indicator 1(f(x(i))≠y(i))\mathbf{1}(f(\mathbf{x}^{(i)}) \neq y^{(i)}) is an independent Bernoulli(ϵ(f))\mathrm{Bernoulli}(\epsilon(f)) coin flip with mean ϵ(f)\epsilon(f) and variance ϵ(f)(1−ϵ(f))≤1/4\epsilon(f)(1 - \epsilon(f)) \leq 1/4. Therefore, the test error ϵD(f)\epsilon_{\mathcal{D}}(f) is an unbiased estimator (E[ϵD(f)]=ϵ(f)\mathbb{E}[\epsilon_{\mathcal{D}}(f)] = \epsilon(f)) with standard error

SE(ϵD(f))=ϵ(f)(1−ϵ(f))n≤0.5n.(3.5.2)\mathrm{SE}\big(\epsilon_{\mathcal{D}}(f)\big) = \sqrt{\frac{\epsilon(f)(1 - \epsilon(f))}{n}} \leq \frac{0.5}{\sqrt{n}}. \tag{3.5.2}

For our Fashion-MNIST classifier (ϵ(f)≈0.17\epsilon(f) \approx 0.17) on n=10,000n = 10{,}000 test images, the standard error is 0.17×0.83/10,000≈0.0038\sqrt{0.17 \times 0.83 / 10{,}000} \approx 0.0038 (0.380.38 percentage points). Notice the 1/n1/\sqrt{n} scaling law: halving our measurement uncertainty requires four times as many test examples.

3.5.1.2 Confidence Intervals and Hoeffding's Inequality#

To convert the standard error into a 95%95\% confidence interval ϵD(f)±r\epsilon_{\mathcal{D}}(f) \pm r, we have two tools:

  1. Asymptotic normal interval (Central Limit Theorem): For large nn, ϵD(f)\epsilon_{\mathcal{D}}(f) is approximately normal, falling within 1.961.96 standard errors of ϵ(f)\epsilon(f) with probability ≈0.95\approx 0.95:
P(∣ϵD(f)−ϵ(f)∣≤1.96ϵ(f)(1−ϵ(f))n)≈0.95.(3.5.3)P\left(|\epsilon_\mathcal{D}(f) - \epsilon(f)| \leq 1.96\sqrt{\frac{\epsilon(f)(1 - \epsilon(f))}{n}}\right) \approx 0.95. \tag{3.5.3}

At ϵ≈0.17\epsilon \approx 0.17 and n=10,000n = 10{,}000, the 95%95\% normal radius is 1.96×0.0038≈0.0071.96 \times 0.0038 \approx 0.007 (±0.7\pm 0.7 percentage points); in the worst case (ϵ=1/2\epsilon = 1/2), guaranteeing a 95%95\% radius ≤0.01\leq 0.01 takes n≥(1.96×0.5/0.01)2=9,604n \geq (1.96 \times 0.5 / 0.01)^2 = 9{,}604 examples. This is a useful way to read the 10,00010{,}000-example test sets of MNIST, Fashion-MNIST, and CIFAR-10: they pin accuracy to about one point. 2. Finite-sample Hoeffding interval: Because the normal approximation can undercover badly when ϵ(f)\epsilon(f) is very close to 00 (where a small test set may observe zero mistakes and collapse the plug-in normal radius to 00), Hoeffding's inequality (Hoeffding, 1963) uses only the fact that each error lies in [0,1][0, 1] to give an exact bound valid for every nn and every distribution (Section 24.9):

P(∣ϵD(f)−ϵ(f)∣≥t)≤2exp⁡(−2nt2).(3.5.4)P\left(|\epsilon_\mathcal{D}(f) - \epsilon(f)| \geq t\right) \leq 2\exp\left(-2nt^2\right). \tag{3.5.4}

Setting the right-hand side to δ=0.05\delta = 0.05 yields the 95%95\% Hoeffding radius r=log⁡(2/δ)/(2n)r = \sqrt{\log(2/\delta)/(2n)} (requiring n≥log⁡(40)/(2×0.012)≈18,445n \geq \log(40)/(2 \times 0.01^2) \approx 18{,}445 examples for r≤0.01r \leq 0.01, roughly twice the normal prescription: both assume the worst-case variance 1/41/4, but Hoeffding's exponential tail bound holds for every nn and is looser than the exact normal quantile).

Let us simulate 10,00010{,}000 independent test sets across sizes n∈[100,10,000]n \in [100, 10{,}000] for two classifiers (one with ϵ=0.17\epsilon = 0.17 and one with ϵ=0.01\epsilon = 0.01) and plot the empirical coverage of both 95%95\% intervals:

rng = np.random.default_rng()
num_sets = 10000
ns = np.array([100, 200, 500, 1000, 2000, 5000, 10000])
curves, legend = [], []
for eps in [0.17, 0.01]:
    # The number of errors on a test set of size n is Binomial(n, eps)
    errs = [rng.binomial(n, eps, num_sets) / n for n in ns]
    normal = [1.96 * np.sqrt(e * (1 - e) / n) for e, n in zip(errs, ns)]
    hoeffding = [np.sqrt(np.log(2 / 0.05) / (2 * n)) for n in ns]
    for name, radii in [('normal', normal), ('Hoeffding', hoeffding)]:
        curves.append([np.mean(np.abs(e - eps) <= r)  # coverage
                       for e, r in zip(errs, radii)])
        legend.append(rf'{name}, $\epsilon = {eps}$')
d2l.plot(ns, curves + [[0.95] * len(ns)], 'test set size n', 'coverage',
         legend=legend + ['0.95'], xscale='log', ylim=(0.5, 1.02),
         fmts=('C0-', 'C0--', 'C1-', 'C1--', 'k:'), figsize=(4.5, 3))

At ϵ=0.17\epsilon = 0.17, the plug-in normal interval stays close to 95%95\% coverage at every nn; at ϵ=0.01\epsilon = 0.01 and small nn, the normal interval drops to ∼63%\sim 63\% coverage whenever zero-error test sets occur, whereas Hoeffding's conservative interval exceeds 95%95\% coverage everywhere.

3.5.2 Test Set Reuse#

3.5.2.1 Selection Among Many Classifiers#

What happens when we evaluate kk fixed candidate classifiers f1,…,fkf_1, \ldots, f_k on the same test set D\mathcal{D} and report the winner? Even if all kk candidates were fixed before D\mathcal{D} was drawn, picking the best score cherry-picks whichever candidate got luckiest on D\mathcal{D}. Applying the union bound (the probability that at least one of kk bad events occurs is at most the sum of their individual probabilities) to (3.5.4) gives

P(max⁡j=1,…,k∣ϵD(fj)−ϵ(fj)∣≥t)≤2kexp⁡(−2nt2).(3.5.5)P\left(\max_{j=1,\ldots,k} |\epsilon_\mathcal{D}(f_j) - \epsilon(f_j)| \geq t\right) \leq 2k\exp\left(-2nt^2\right). \tag{3.5.5}

Setting the right-hand side to δ\delta shows that simultaneous 1−δ1 - \delta accuracy across all kk models widens the confidence radius to log⁡(2k/δ)/(2n)\sqrt{\log(2k/\delta)/(2n)}. Notice the benign log⁡k\sqrt{\log k} growth: comparing k=1,000k = 1{,}000 fixed models increases the radius by only a logarithmic factor, yet on n=1,000n = 1{,}000 coin-flip test labels scored by k=10,000k = 10{,}000 purely random coin-flipping guessers (every single one having true accuracy 0.500.50), the luckiest guesser's test accuracy climbs steadily along 0.5+log⁡(k)/(2n)0.5 + \sqrt{\log(k)/(2n)} to ∼0.56\sim 0.56:

n, k = 1000, 10000
labels = rng.random(n) < 0.5            # one test set with coin-flip labels
guesses = rng.random((k, n)) < 0.5      # k classifiers that guess at random
accuracy = (guesses == labels).mean(axis=1)
ks = np.arange(1, k + 1)
d2l.plot(ks, [np.maximum.accumulate(accuracy),
              0.5 + np.sqrt(np.log(ks) / (2 * n))],
         'number of classifiers k', 'best test accuracy',
         legend=['best of k', r'$0.5 + \sqrt{\log(k) / (2n)}$'], xscale='log',
         ylim=(0.4, 0.6))

3.5.2.2 Adaptive Overfitting#

Selection bias grows far more dangerous when new candidates are chosen adaptively based on previous test scores (Dwork et al., 2015). Once test feedback guides model design, the classifiers are no longer independent of D\mathcal{D} and the union bound (3.5.5) breaks down completely. Following Blum and Hardt (2015), watch what happens if we take just the first 1,0001{,}000 random coin-flipping guessers above, select only those that happened to score above 0.500.50 on the test set, and take their majority vote on each test example:

kept = guesses[:1000][accuracy[:1000] > 0.5]  # guessers that scored above 0.5
vote = kept.mean(axis=0) > 0.5                # their majority vote
print(f'majority vote: {(vote == labels).mean():.3f}, '
      f'best single guesser: {accuracy[:1000].max():.3f}')
majority vote: 0.709, best single guesser: 0.564

Without ever seeing an individual test label, using only 1,0001{,}000 scalar accuracy queries, the majority vote of pure coin flippers jumps to ∼70%\sim 70\% test accuracy while still having 50%50\% population accuracy on any new data. (In fact, O(n)O(n) queries can reconstruct every test label; see Exercise 3.) This is why hyperparameter tuning and architecture exploration belong on a validation split (Exercise 4), leaving the test set for one-shot final evaluation.

How much damage has a decade of reuse done to the standard benchmarks? When Recht et al. (2019) collected fresh test sets for CIFAR-10 and ImageNet, accuracies fell by 33 to 1515 points, yet the ranking of the models barely changed. The worst case above is possible, but ordinary model development had overfit these test sets far less than the theory permits. The drop itself is better explained by a small change in the data distribution, which is the subject of Section 3.6.

3.5.3 Statistical Learning Theory#

3.5.3.1 Uniform Convergence#

How can we guarantee a priori that a classifier fSf_{\mathcal{S}} selected from a hypothesis class F\mathcal{F} by minimizing training error ϵS(f)\epsilon_{\mathcal{S}}(f) on a training set S\mathcal{S} of size nn will generalize to the population? Since the learner picks fS∈Ff_{\mathcal{S}} \in \mathcal{F} after inspecting S\mathcal{S}, we need the training error to stay close to the population error simultaneously for every f∈Ff \in \mathcal{F} (uniform convergence). If F\mathcal{F} is finite (∣F∣<∞|\mathcal{F}| \lt \infty), applying the union bound (3.5.5) across all k=∣F∣k = |\mathcal{F}| hypotheses on S\mathcal{S} yields, with probability at least 1−δ1 - \delta,

∣ϵS(f)−ϵ(f)∣≤log⁡(2∣F∣/δ)2nfor every f∈F.(3.5.6)|\epsilon_\mathcal{S}(f) - \epsilon(f)| \leq \sqrt{\frac{\log(2|\mathcal{F}|/\delta)}{2n}} \quad \textrm{for every } f \in \mathcal{F}. \tag{3.5.6}

3.5.3.2 The VC Dimension and the VC Bound#

For continuous parameter families like linear halfspaces f(x)=sign⁡(w⊤x+b)f(\mathbf{x}) = \operatorname{sign}(\mathbf{w}^\top\mathbf{x} + b) on Rd\mathbb{R}^d, ∣F∣=∞|\mathcal{F}| = \infty, making (3.5.6) vacuous. Yet Vapnik and Chervonenkis (1971) observed that on any finite set of nn points, two classifiers that produce the exact same binary ±1\pm 1 labeling are indistinguishable on S\mathcal{S}. We say that F\mathcal{F} shatters a set of mm points if functions in F\mathcal{F} can realize all 2m2^m possible binary labelings of those mm points. The Vapnik--Chervonenkis (VC) dimension v=VC(F)v = \mathrm{VC}(\mathcal{F}) is the size of the largest set of points that F\mathcal{F} can shatter:

  • Lines in the plane (R2\mathbb{R}^2) have VC dimension 33 (Figure 3.5.1): Any three non-collinear points can be shattered in all 23=82^3 = 8 ways by a straight line, whereas no four points in R2\mathbb{R}^2 can ever be shattered (splitting opposite corners of a convex quadrilateral requires crossing diagonals, and a halfplane containing the three vertices of a triangle automatically contains any point inside it).
  • Linear halfspaces in Rd\mathbb{R}^d have VC dimension d+1d + 1 (Exercise 5): They shatter the origin and the dd standard basis vectors, and by Radon's theorem no d+2d + 2 points in Rd\mathbb{R}^d can be shattered.
  • Unconstrained lookup-table memorizers have v=∞v = \infty: They shatter every finite set of distinct points.
Figure 3.5.1:

Lines in R2\mathbb{R}^2 shatter three non-collinear points (left, all 23=82^3 = 8 labelings) but cannot shatter any four points (middle and right).

By Sauer's lemma, once n≥vn \geq v, the number of distinct labelings that a class of VC dimension vv can induce on nn points grows only polynomially—at most (en/v)v(en/v)^v rather than 2n2^n. Running a symmetrized union bound over those labelings (Section 24.10) yields the VC bound: for an absolute constant cc, with probability at least 1−δ1 - \delta over the training draw S\mathcal{S},

ϵ(f)≤ϵS(f)+cv+log⁡(1/δ)nfor every f∈F.(3.5.7)\epsilon(f) \leq \epsilon_\mathcal{S}(f) + c\sqrt{\frac{v + \log(1/\delta)}{n}} \quad \textrm{for every } f \in \mathcal{F}. \tag{3.5.7}

This theorem answers our conceptual puzzle: because linear classifiers in Rd\mathbb{R}^d have finite VC dimension v=d+1v = d + 1, driving training error low when n≫dn \gg d guarantees low population error for any distribution PP, whereas an infinite-VC memorizer enjoys no bound at all. At the same time, because worst-case uniform convergence bounds must hold even for adversarial distributions, (3.5.7) is numerically loose on natural images (for a single one-vs-rest halfspace 785/60,000≈0.11\sqrt{785 / 60{,}000} \approx 0.11 before the constant cc, and the capacity of all ten classes together is larger still, versus our empirical 0.010.01 train--test gap on Fashion-MNIST) and becomes vacuous (v≥nv \geq n) for overparameterized deep neural networks capable of memorizing random labels (Zhang et al., 2021). We return to that puzzle in Section 4.5 while relying on held-out test sets for sharp empirical measurement.

3.5.4 Summary#

On an untouched test set of nn examples, a fixed classifier's empirical error ϵD(f)\epsilon_{\mathcal{D}}(f) has standard error ϵ(1−ϵ)/n≤0.5/n\sqrt{\epsilon(1-\epsilon)/n} \leq 0.5/\sqrt{n}, so pinning accuracy to within one percentage point at 95%95\% confidence requires roughly 10,00010{,}000 test examples under the normal approximation or 18,50018{,}500 under Hoeffding's finite-sample bound. Reusing the same test set to select among kk fixed models widens that uncertainty slowly as log⁡(2k/δ)/(2n)\sqrt{\log(2k/\delta)/(2n)}, whereas adaptive design guided by past test scores can overfit a test set in far fewer queries. To bound generalization from training error alone, statistical learning theory measures hypothesis-class capacity by the VC dimension vv—the largest set of points the class can shatter (v=d+1v = d + 1 for linear halfspaces in Rd\mathbb{R}^d)—yielding a uniform O(v/n)O(\sqrt{v/n}) bound that explains why linear models cannot memorize large datasets while remaining vacuous for overparameterized deep networks.

3.5.5 Exercises#

  1. Two models, one test set. A paper reports that model A reaches 91.2% and model B 91.6% on a test set of 10,000 images.

    1. Compute the standard error of each accuracy and the 95% radius of the normal approximation. Is the difference of 0.4 points meaningful if the two models were evaluated on two independent test sets of this size?
    2. Both models were in fact evaluated on the same 10,000 images. Explain why the question is now about the images on which the two models disagree, and describe how you would decide it if the paper reported, for every test image, which models got it right.
    3. How large a test set would make a 0.4-point difference between two independently evaluated models lie outside the radius?
  2. No errors on the test set. A classifier makes no error on a test set of nn examples.

    1. State the interval that the normal approximation, with ϵD(f)\epsilon_\mathcal{D}(f) in place of ϵ(f)\epsilon(f), reports, and the Hoeffding interval.
    2. Show that a classifier with population error ϵ\epsilon makes no error on nn independent test examples with probability (1−ϵ)n≤e−nϵ(1 - \epsilon)^n \leq e^{-n\epsilon}. Conclude that if ϵ≥3/n\epsilon \geq 3/n, a test set without errors occurs with probability below 0.05 (the "rule of three").
    3. Compare 3/n3/n with the Hoeffding radius for n=100n = 100 and n=10,000n = 10{,}000, and explain the difference.
  3. Leaking a test set. Somebody else holds a test set D\mathcal{D} of nn examples with binary labels and releases only the inputs. You may submit any model ff, with no restriction on the model class, and you receive only its test error ϵD(f)\epsilon_\mathcal{D}(f).

    1. Give a strategy that recovers every test label, and hence a model with test error 00 whatever its population error, and count the submissions it uses.
    2. Each answer ϵD(f)\epsilon_\mathcal{D}(f) takes one of n+1n+1 values. Use this to lower-bound the number of submissions that any strategy needs to distinguish all 2n2^n labelings.
  4. [code] A validation split for Fashion-MNIST. The chapter selected models on the 10,000 test images. Hold out 10,000 of the 60,000 training images as a validation split instead, and train softmax regression on the remaining 50,000.

    1. Choose the learning rate from {0.01,0.03,0.1,0.3,1}\{0.01, 0.03, 0.1, 0.3, 1\} by its accuracy on the validation split.
    2. Evaluate the selected model once on the test images, and compare its test accuracy with its validation accuracy. Is the difference within the radius of the 95% interval for 10,000 examples?
    3. Explain why the test accuracy, measured once after the choice, is an unbiased estimate for the selected model, while the best validation accuracy is not.
  5. VC dimension of linear classifiers. ● Consider the linear classifiers f(x)=sign⁡(w⊤x+b)f(\mathbf{x}) = \operatorname{sign}(\mathbf{w}^\top \mathbf{x} + b) on Rd\mathbb{R}^d.

    1. Show that they shatter the d+1d+1 points 0,e1,…,ed\mathbf{0}, \mathbf{e}_1, \ldots, \mathbf{e}_d. Given arbitrary labels y0,y1,…,yd∈{±1}y_0, y_1, \ldots, y_d \in \{\pm 1\}, construct bb and w\mathbf{w} that produce them. Hint: f(0)f(\mathbf{0}) depends on bb alone, so choose bb first.
    2. Let x1,…,xd+2∈Rd\mathbf{x}_1, \ldots, \mathbf{x}_{d+2} \in \mathbb{R}^d. Show that the d+2d + 2 vectors [xi,1]∈Rd+1[\mathbf{x}_i, 1] \in \mathbb{R}^{d+1}, each xi\mathbf{x}_i with a 1 appended, are linearly dependent, so that ∑iai[xi,1]=0\sum_i a_i [\mathbf{x}_i, 1] = \mathbf{0} for some aia_i that are not all zero. Let II be the indices with ai>0a_i > 0 and JJ those with ai<0a_i \lt 0. Show that neither is empty and that no linear classifier labels the points in II with +1+1 and those in JJ with −1-1. Hint: evaluate ∑iai(w⊤xi+b)\sum_i a_i (\mathbf{w}^\top \mathbf{x}_i + b) in two ways.
    3. Conclude that the VC dimension is d+1d + 1, and show that the convex hulls of {xi:i∈I}\{\mathbf{x}_i : i \in I\} and {xj:j∈J}\{\mathbf{x}_j : j \in J\} intersect.
  6. VC dimension of polynomials. What is the VC dimension of the class of classifiers f(x)=sign⁡(p(x))f(x) = \operatorname{sign}(p(x)) with pp a polynomial of degree at most five in x∈Rx \in \mathbb{R}? What is it for x∈Rd\mathbf{x} \in \mathbb{R}^d? Hint: such a classifier is a linear classifier on the monomials of x\mathbf{x}. Then say what the VC bound predicts for the training error of a degree-five polynomial classifier on Fashion-MNIST, and why nobody trains one.

Discussions