4.5 Generalization in Deep Learning
In Section 2.6, a degree-19 polynomial with parameters interpolated noisy data points and blew up on test data. By that classical intuition, our Fashion-MNIST MLP in Section 4.2, with parameters for training images ( parameters per image), ought to overfit severely, especially if trained until it interpolates every single training image. Yet it reached accuracy on unseen images. And as we will see below, the same architecture given only training images and driven to training accuracy still classifies about of unseen images correctly.
Understanding why heavily overparameterized networks generalize is one of the central open problems of modern machine learning. In this section, we combine controlled experiments with exact results on tractable models to uncover four key pieces of the puzzle:
- Random-label memorization: Standard MLPs easily reach training accuracy on completely random labels (Zhang et al., 2021), proving that classical distribution-free capacity bounds (like VC dimension) cannot explain their generalization on real labels.
- Double descent: Sweeping model width past the interpolation threshold reveals a spike in test error at (where the feature matrix is nearly singular) followed by a second descent as extra parameters allow smaller-norm interpolators (Belkin et al., 2019).
- Implicit bias of gradient descent: Among infinitely many zero-loss solutions, gradient descent automatically selects the minimum-norm interpolator under squared loss and the maximum-margin separator under logistic loss (Soudry et al., 2018).
- Clean-first learning and early stopping: On noisy datasets, gradient descent fits clean structured patterns long before memorizing corrupted labels (Arpit et al., 2017), making early stopping a potent regularizer.
4.5.1 Memorization and Capacity#
4.5.1.1 Random Labels#
To test raw memorization capacity following Zhang et al. (2021), we draw Fashion-MNIST training images ( for training, for validation) and test images, define ArrayData and Tracker helpers along with a He-initialized 256-unit MLP, and train for 200 epochs once on the true labels (fraction=0) and once on completely random labels (fraction=1):
data = d2l.FashionMNIST(batch_size=2000)
X, y = next(iter(data.train_dataloader())) # 2,000 random images
X_test, y_test = next(iter(data.val_dataloader())) # the first 2,000
X, y, X_test, y_test = (d2l.numpy(a) for a in (X, y, X_test, y_test))
X, X_test = X.reshape(2000, -1), X_test.reshape(2000, -1)
X_train, y_train, X_val, y_val = X[:1000], y[:1000], X[1000:], y[1000:]
Two lightweight helpers streamline the experiments ahead: ArrayData wraps
NumPy arrays into shuffled minibatches, and Tracker subclasses Trainer
to log epoch-by-epoch accuracy across an arbitrary dictionary of named
datasets.
class ArrayData(d2l.DataModule):
"""Minibatches of the arrays X and y; training batches are shuffled."""
def __init__(self, X, y, batch_size=64):
super().__init__()
self.save_hyperparameters()
def get_dataloader(self, train):
return self.get_tensorloader(
(d2l.tensor(self.X), d2l.tensor(self.y)), train)
class Tracker(d2l.Trainer):
"""A Trainer that records the accuracy on named datasets every epoch."""
def __init__(self, max_epochs, datasets):
super().__init__(max_epochs, num_gpus=1)
self.datasets = datasets
self.accuracy = {name: [] for name in datasets}
self.board.display = False # We plot the accuracies ourselves
def validate(self):
for name, dataset in self.datasets.items():
self.val_dataloader = dataset.val_dataloader()
self.accuracy[name].append(super().validate()['acc'])
return {}
Our model is the same 256-unit ReLU MLP from
Section 4.2, upgraded with He initialization
(Section 4.4.2.2) in place of std=0.01 so training takes off
immediately from epoch 1 (with zero biases and pre-flattened inputs).
class MLP(d2l.Classifier):
def __init__(self, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(nn.LazyLinear(num_hiddens), nn.ReLU(),
nn.LazyLinear(10))
def weight_init(self, module):
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
nn.init.zeros_(module.bias)Now we define corrupt(y, fraction, rng) to replace each training label with a uniform random class in with probability fraction, train MLP(num_hiddens=256, lr=0.1) for epochs at fraction = 0 (true labels) and fraction = 1 (pure random labels), and plot both training and test accuracy trajectories:
def corrupt(y, fraction, rng):
"""Replace each label, with probability fraction, by a random class."""
redraw = rng.random(len(y)) < fraction
y = y.copy()
y[redraw] = rng.integers(0, 10, redraw.sum())
return y
rng = np.random.default_rng()
curves = []
for fraction in (0, 1):
labels = corrupt(y_train, fraction, rng)
trainer = Tracker(max_epochs=200, datasets={
'train': ArrayData(X_train, labels, 1000),
'test': ArrayData(X_test, y_test, 1000)})
trainer.fit(MLP(num_hiddens=256, lr=0.1), ArrayData(X_train, labels))
curves += [trainer.accuracy['train'], trainer.accuracy['test']]
d2l.plot(list(range(1, 201)), curves, 'epoch', 'accuracy',
fmts=('C0-', 'C1-', 'C0--', 'C1--'), figsize=(5, 3))
d2l.plt.legend(['train, true labels', 'test, true labels',
'train, random labels', 'test, random labels'],
loc='center right', bbox_to_anchor=(1, 0.4));Look at what the two runs prove:
- On true labels, training accuracy hits within 60–90 epochs while test accuracy plateaus above (even on just training images).
- On completely random labels, the exact same architecture and optimizer still reach training accuracy (taking slightly longer, – epochs) while test accuracy remains at random chance.
4.5.1.2 Limits of Capacity Bounds and Inductive Bias#
Because our MLP achieves zero training error () on random labels where the true population error is , any distribution-free bound of the form that depends only on the hypothesis class must have , making it vacuous on real labels as well (Exercise 1).
By the no free lunch theorem (Wolpert, 1996), no learner can generalize across all distributions; generalization depends on whether the learner's inductive bias—which interpolating function it prefers among infinitely many—matches the structure of real data, just as a 1-nearest-neighbor classifier interpolates of its training data yet generalizes well whenever nearby inputs share labels (Cover and Hart, 1967).
4.5.2 Double Descent#
4.5.2.1 The Interpolation Threshold and Conditioning#
What happens when we increase model width right past the sample size ? Let us test a tractable random-features model (Rahimi and Recht, 2007): we freeze a He-initialized first layer on our centered training images to precompute random ReLU features H and H_test, encode the labels as a one-hot matrix Y, and define error(H, W2, y):
W1 = rng.normal(0, np.sqrt(2 / 784), (784, 10000)) # He-initialized, frozen
mean = X_train.mean(axis=0) # The mean training image
H = np.maximum((X_train - mean) @ W1, 0)
H_test = np.maximum((X_test - mean) @ W1, 0)
Y = np.eye(10)[y_train] # One-hot labels
def error(H, W2, y):
"""Fraction of examples whose largest output is not their label."""
return (np.argmax(H @ W2, axis=1) != y).mean()
We now sweep the hidden width h across 15 values from to , fitting the output weights on the first h feature columns H[:, :h] by minimum-norm least squares (np.linalg.lstsq) while recording the smallest singular value s_min[h] and Frobenius norm norm[h]:
widths = [50, 100, 200, 400, 600, 800, 900, 1000, 1100, 1200, 1500, 2000,
3000, 5000, 10000]
train_err, test_err, s_min, norm = [], [], {}, {}
for h in widths:
W2, _, _, s = np.linalg.lstsq(H[:, :h], Y, rcond=None)
train_err.append(error(H[:, :h], W2, y_train))
test_err.append(error(H_test[:, :h], W2, y_test))
s_min[h], norm[h] = s.min(), np.linalg.norm(W2)
d2l.plot([widths, widths, [1000, 1000]], [train_err, test_err, [0, 1]],
'hidden units h', 'error', legend=['train', 'test', 'h = n'],
xscale='log', fmts=('C0-', 'C1-', 'k:'), figsize=(5, 3))This is the celebrated double-descent curve (Belkin et al., 2019):
- Classical U-curve (): Test error drops from at to around , then shoots up to right at the interpolation threshold .
- Second descent (): As grows past up to , every model interpolates the training set, yet test error plunges back down to , beating the best underparameterized model.
Why does test error spike so violently at and heal for ? Let us inspect the smallest singular value of and the Frobenius norm :
for h in (200, 900, 1000, 1100, 10000):
print(f'h = {h:5d}: smallest singular value {s_min[h]:.1e}, '
f'norm of W2 {norm[h]:6.1f}')h = 200: smallest singular value 1.7e+00, norm of W2 3.7
h = 900: smallest singular value 1.2e-01, norm of W2 20.4
h = 1000: smallest singular value 2.0e-04, norm of W2 1577.9
h = 1100: smallest singular value 2.3e-02, norm of W2 20.4
h = 10000: smallest singular value 2.1e-01, norm of W2 2.2
At , is a square matrix with a tiny smallest singular value , so the unique exact inverse divides label noise by and explodes into the hundreds or more. For , the extra columns open up an -dimensional subspace of exact interpolators, allowing the minimum-norm solution to avoid poorly conditioned directions and shrink all the way down to . In fact, holding fixed, doubling the training set from to lands the unregularized fit squarely on the cliff and drives test error up from to :
for n in (500, 1000):
W2 = np.linalg.lstsq(H[:n, :1000], Y[:n], rcond=None)[0]
test_error = error(H_test[:, :1000], W2, y_test)
print(f'{n} training images: test error {test_error:.2f}')500 training images: test error 0.28
1000 training images: test error 0.89
4.5.3 Implicit Bias of Gradient Descent#
The second descent above relied on lstsq picking the minimum-norm interpolator among infinitely many zero-loss solutions. Remarkably, gradient descent has that exact preference built in—an implicit bias (or implicit regularization) that operates even without any explicit penalty term.
4.5.3.1 Minimum-Norm Interpolation under Squared Loss#
For an overparameterized linear system (, full row rank), the unique minimum-norm interpolator is .
Proposition. Gradient descent on initialized at (with a converging step size) converges to the minimum-norm interpolator .
Proof. Every gradient lies in the row space of . Starting at , every iterate , and hence the limit , remains in the row space of (Figure 4.5.1). Since , we have and . Any other interpolator has (so ) and strictly larger norm .
Gradient descent on an underdetermined linear equation moves strictly perpendicular to the solution hyperplane, so starting from (blue) lands at the minimum-norm solution , whereas starting from (orange) preserves the null-space component of .
Let us verify this proposition numerically on equations in unknowns, comparing against a random initialization:
H_small = rng.normal(size=(20, 100))
y_small = rng.normal(size=20)
w_star = np.linalg.lstsq(H_small, y_small, rcond=None)[0]
lr = 1 / np.linalg.norm(H_small, 2) ** 2 # Below 2 / largest curvature
for name, w in (('zero', np.zeros(100)), ('random', rng.normal(size=100))):
for _ in range(2000):
w = w - lr * H_small.T @ (H_small @ w - y_small)
residual = np.linalg.norm(H_small @ w - y_small)
print(f'start {name:6s}: residual {residual:.0e}, norm '
f'{np.linalg.norm(w):5.2f}, distance to w* '
f'{np.linalg.norm(w - w_star):.1f}')start zero : residual 8e-17, norm 0.79, distance to w* 0.0
start random: residual 3e-15, norm 9.39, distance to w* 9.4
4.5.3.2 Maximum-Margin Classification under Logistic Loss#
On linearly separable binary classification data () under the logistic (cross-entropy) loss , as , and Soudry et al. (2018) proved that the direction converges (at a rate) to the hard-margin SVM maximum-margin separator (Figure 4.5.2), because support vectors with the smallest margins dominate the exponentially decaying tail of (see Exercise 5 for how layer rescaling complicates parameter-norm margins in multi-layer ReLU networks).
Gradient descent on linearly separable logistic regression rotates toward the maximum-margin hyperplane (left) at a logarithmic rate that continues long after training accuracy reaches (right).
4.5.4 Early Stopping#
Even when an MLP has enough capacity to memorize corrupted labels, gradient descent learns clean structured patterns first and memorizes label noise much later (Arpit et al., 2017). Let us corrupt of the labels in our -image training set and track accuracy separately on the clean training examples, the mislabeled training examples (scored against their corrupted labels), and the clean validation images over 200 epochs:
labels = corrupt(y_train, 0.2, rng)
wrong = labels != y_train
trainer = Tracker(max_epochs=200, datasets={
'clean': ArrayData(X_train[~wrong], labels[~wrong], 1000),
'mislabeled': ArrayData(X_train[wrong], labels[wrong], 1000),
'validation': ArrayData(X_val, y_val, 1000),
'test': ArrayData(X_test, y_test, 1000)})
trainer.fit(MLP(num_hiddens=256, lr=0.1), ArrayData(X_train, labels))
acc = trainer.accuracy
d2l.plot(list(range(1, 201)), [acc['clean'], acc['mislabeled'],
acc['validation']], 'epoch', 'accuracy',
legend=['clean training labels', 'wrong training labels',
'validation'], figsize=(5, 3))By epoch 20, the MLP gets over of the clean training images right while memorizing fewer than of the corrupted labels, and validation accuracy reaches its peak in this early window before late-epoch noise memorization drags it down. Early stopping, halting training once validation performance fails to improve for a specified patience window (Exercise 2) and restoring the best validation checkpoint, recovers several percentage points of test accuracy while saving compute (and in linear least squares acts analogously to weight decay; see Exercise 4):
best = int(np.argmax(acc['validation']))
print(f'best validation accuracy after epoch {best + 1}: '
f'test accuracy {acc["test"][best]:.3f}')
print(f'after all 200 epochs: test accuracy {acc["test"][-1]:.3f}')best validation accuracy after epoch 16: test accuracy 0.775
after all 200 epochs: test accuracy 0.716
One famous exception to early stopping is grokking (Power et al., 2022) (Figure 4.5.3, Exercise 6), where networks trained with weight decay on small algorithmic tasks (such as modular addition) memorize the training table rapidly while validation accuracy remains near chance for longer before suddenly jumping to .
Grokking (Power et al. (2022)): on modular arithmetic, training accuracy saturates within steps while validation accuracy jumps to generalization only after steps.
4.5.5 Summary#
Overparameterized neural networks can memorize completely random labels while generalizing well on structured data, rendering distribution-free capacity bounds vacuous and placing the burden of explanation on inductive bias. In random-features least squares, test error spikes at the interpolation threshold , where a tiny smallest singular value inflates , and descends a second time for as minimum-norm interpolation spreads weights across redundant features. Remarkably, gradient descent from zero finds this minimum-norm interpolator automatically under squared loss and converges in direction to the maximum-margin separator under logistic loss. Because gradient descent also fits coherent patterns before memorizing corrupted labels, early stopping on a validation set serves as a simple and effective regularizer.
4.5.6 Exercises#
- Limits of complexity measures. Consider a generalization bound that holds for every data distribution: with probability at least over the draw of training examples, every classifier in a class satisfies
Here is the population error, is the training error, and the term depends only on , , and , as the term of the VC bound does. The text ran the random-label argument against such a bound for 1,000 images.
- Suppose that training also finds a member of with zero training error on all 60,000 Fashion-MNIST training images when their labels are drawn uniformly at random, as Zhang et al. (2021) observed for image classifiers. What lower bound on follows, and what does the bound then guarantee for the network trained on the true labels?
- Many later bounds let the second term depend on the classifier that training returns, for example through the norm of its weights or through its margins on the training examples. Which step of the argument no longer goes through? What must such a quantity do on the random-label run if the bound is to say something on the true labels?
-
[code] Patience-based stopping.
FashionMNISTuses the Fashion-MNIST test set as its validation data, so hold out 10,000 training images as a validation set instead. Train an MLP with one hidden layer of 256 units, as in Section 4.2, on the remaining images for a fixed number of epochs large enough to overfit, and record the validation loss and the test accuracy after every epoch. A patience rule with tolerance and patience stops once the validation loss has failed to improve on its best value by more than for consecutive epochs. It then retains the parameters of the epoch with the lowest validation loss so far.- Fix and apply the rule to the recorded curves for . For each , report the stopping epoch, the retained epoch, and the test accuracy at both.
- How does the test accuracy at the retained epoch depend on ? Relate the dependence to the epoch-to-epoch fluctuation of the validation loss.
Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 3.
-
[code] Weight decay at the threshold. Replace the minimum-norm fit of the double-descent experiment by the ridge solution of Section 2.7, which, as there, averages the squared error over the examples.
- Plot the test error against the width for . What happens to the peak at ?
- Show that the ridge solution approaches the minimum-norm solution as for . Hint: write .
- For each width, choose on the 1,000 validation images. Does the curve of the tuned model still descend twice?
-
Early stopping and weight decay. ● Early stopping limits the number of training epochs where weight decay limits the weights. Linear least squares makes this precise. Let have eigenvalues , let minimize , and run gradient descent on from with learning rate .
- Show that after steps the coordinate of along the -th eigenvector equals times that of .
- The minimizer of scales the same coordinate by (Section 2.7.3). For which , as a function of and , do the two factors approximately agree both in the directions with and in those with ?
Adapted from Ian Goodfellow, Yoshua Bengio, and Aaron Courville, Deep Learning, Section 7.8.
-
Implicit bias of the logistic loss. ● For linearly separable data, gradient descent on the logistic loss converges in direction to the maximum-margin separator (Soudry et al., 2018). Take labels .
- For a linear predictor , show that on separable data the loss is positive for every but has infimum zero. Conclude that grows without bound when gradient descent drives the loss to zero, so that only the direction can converge.
- For a two-layer ReLU network , show that replacing by with leaves unchanged. Find the smallest value of over these rescalings. Explain why a margin measured with the parameter norm of the network, unlike one measured with for the linear predictor, is not a property of the function alone.
-
[extended] Grokking. ●● Reproduce the setup of Power et al. (2022): train a small network (they use a two-layer transformer, but a wide MLP on one-hot pairs also works) to predict from the pair , using a random 50% of all pairs for training, with weight decay, for or more steps. Plot training and validation accuracy against the logarithm of the step count, and compare with Figure 4.5.3. How does the delay before generalization change with the training fraction and with the weight-decay strength?