3.5 Generalization in Classification
Our Fashion-MNIST classifier achieved roughly accuracy on validation images. How far can we trust that number as a guarantee of performance on future garments? Two fundamental obstacles stand in the way:
- Finite-sample uncertainty and test-set reuse: Even a fresh test set of 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.
- Memorization vs. learning: In high dimensions where every training image is distinct, a lookup-table memorizer achieves 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 , 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 before drawing an independent test set i.i.d. from the population distribution . Its empirical error on and its true population error are
Because was fixed in advance, each error indicator is an independent coin flip with mean and variance . Therefore, the test error is an unbiased estimator () with standard error
For our Fashion-MNIST classifier () on test images, the standard error is ( percentage points). Notice the 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 confidence interval , we have two tools:
- Asymptotic normal interval (Central Limit Theorem): For large , is approximately normal, falling within standard errors of with probability :
At and , the normal radius is ( percentage points); in the worst case (), guaranteeing a radius takes examples. This is a useful way to read the -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 is very close to (where a small test set may observe zero mistakes and collapse the plug-in normal radius to ), Hoeffding's inequality (Hoeffding, 1963) uses only the fact that each error lies in to give an exact bound valid for every and every distribution (Section 24.9):
Setting the right-hand side to yields the Hoeffding radius (requiring examples for , roughly twice the normal prescription: both assume the worst-case variance , but Hoeffding's exponential tail bound holds for every and is looser than the exact normal quantile).
Let us simulate independent test sets across sizes for two classifiers (one with and one with ) and plot the empirical coverage of both 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 , the plug-in normal interval stays close to coverage at every ; at and small , the normal interval drops to coverage whenever zero-error test sets occur, whereas Hoeffding's conservative interval exceeds coverage everywhere.
3.5.2 Test Set Reuse#
3.5.2.1 Selection Among Many Classifiers#
What happens when we evaluate fixed candidate classifiers on the same test set and report the winner? Even if all candidates were fixed before was drawn, picking the best score cherry-picks whichever candidate got luckiest on . Applying the union bound (the probability that at least one of bad events occurs is at most the sum of their individual probabilities) to (3.5.4) gives
Setting the right-hand side to shows that simultaneous accuracy across all models widens the confidence radius to . Notice the benign growth: comparing fixed models increases the radius by only a logarithmic factor, yet on coin-flip test labels scored by purely random coin-flipping guessers (every single one having true accuracy ), the luckiest guesser's test accuracy climbs steadily along to :
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 and the union bound (3.5.5) breaks down completely. Following Blum and Hardt (2015), watch what happens if we take just the first random coin-flipping guessers above, select only those that happened to score above 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 scalar accuracy queries, the majority vote of pure coin flippers jumps to test accuracy while still having population accuracy on any new data. (In fact, 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 to 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 selected from a hypothesis class by minimizing training error on a training set of size will generalize to the population? Since the learner picks after inspecting , we need the training error to stay close to the population error simultaneously for every (uniform convergence). If is finite (), applying the union bound (3.5.5) across all hypotheses on yields, with probability at least ,
3.5.3.2 The VC Dimension and the VC Bound#
For continuous parameter families like linear halfspaces on , , making (3.5.6) vacuous. Yet Vapnik and Chervonenkis (1971) observed that on any finite set of points, two classifiers that produce the exact same binary labeling are indistinguishable on . We say that shatters a set of points if functions in can realize all possible binary labelings of those points. The Vapnik--Chervonenkis (VC) dimension is the size of the largest set of points that can shatter:
- Lines in the plane () have VC dimension (Figure 3.5.1): Any three non-collinear points can be shattered in all ways by a straight line, whereas no four points in 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 have VC dimension (Exercise 5): They shatter the origin and the standard basis vectors, and by Radon's theorem no points in can be shattered.
- Unconstrained lookup-table memorizers have : They shatter every finite set of distinct points.
Lines in shatter three non-collinear points (left, all labelings) but cannot shatter any four points (middle and right).
By Sauer's lemma, once , the number of distinct labelings that a class of VC dimension can induce on points grows only polynomially—at most rather than . Running a symmetrized union bound over those labelings (Section 24.10) yields the VC bound: for an absolute constant , with probability at least over the training draw ,
This theorem answers our conceptual puzzle: because linear classifiers in have finite VC dimension , driving training error low when guarantees low population error for any distribution , 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 before the constant , and the capacity of all ten classes together is larger still, versus our empirical train--test gap on Fashion-MNIST) and becomes vacuous () 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 examples, a fixed classifier's empirical error has standard error , so pinning accuracy to within one percentage point at confidence requires roughly test examples under the normal approximation or under Hoeffding's finite-sample bound. Reusing the same test set to select among fixed models widens that uncertainty slowly as , 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 —the largest set of points the class can shatter ( for linear halfspaces in )—yielding a uniform bound that explains why linear models cannot memorize large datasets while remaining vacuous for overparameterized deep networks.
3.5.5 Exercises#
-
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.
- 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?
- 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.
- How large a test set would make a 0.4-point difference between two independently evaluated models lie outside the radius?
-
No errors on the test set. A classifier makes no error on a test set of examples.
- State the interval that the normal approximation, with in place of , reports, and the Hoeffding interval.
- Show that a classifier with population error makes no error on independent test examples with probability . Conclude that if , a test set without errors occurs with probability below 0.05 (the "rule of three").
- Compare with the Hoeffding radius for and , and explain the difference.
-
Leaking a test set. Somebody else holds a test set of examples with binary labels and releases only the inputs. You may submit any model , with no restriction on the model class, and you receive only its test error .
- Give a strategy that recovers every test label, and hence a model with test error whatever its population error, and count the submissions it uses.
- Each answer takes one of values. Use this to lower-bound the number of submissions that any strategy needs to distinguish all labelings.
-
[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.
- Choose the learning rate from by its accuracy on the validation split.
- 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?
- 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.
-
VC dimension of linear classifiers. ● Consider the linear classifiers on .
- Show that they shatter the points . Given arbitrary labels , construct and that produce them. Hint: depends on alone, so choose first.
- Let . Show that the vectors , each with a 1 appended, are linearly dependent, so that for some that are not all zero. Let be the indices with and those with . Show that neither is empty and that no linear classifier labels the points in with and those in with . Hint: evaluate in two ways.
- Conclude that the VC dimension is , and show that the convex hulls of and intersect.
-
VC dimension of polynomials. What is the VC dimension of the class of classifiers with a polynomial of degree at most five in ? What is it for ? Hint: such a classifier is a linear classifier on the monomials of . 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.