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:]4.5 Generalization in Deep Learning
In Section 2.6, a degree-19 polynomial with \(20\) parameters interpolated \(20\) noisy data points and blew up on test data. By that classical intuition, our Fashion-MNIST MLP in Section 4.2, with \(203{,}530\) parameters for \(60{,}000\) training images (\(3.4\) parameters per image), ought to overfit severely, especially if trained until it interpolates every single training image. Yet it reached \(\sim 87\%\) accuracy on unseen images. And as we will see below, the same architecture given only \(1{,}000\) training images and driven to \(100\%\) training accuracy still classifies about \(80\%\) 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 \(100\%\) 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 \(h = n\) reveals a spike in test error at \(h = n\) (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 \(2{,}000\) Fashion-MNIST training images (\(1{,}000\) for training, \(1{,}000\) for validation) and \(2{,}000\) 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):
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)class MLP(d2l.Classifier):
def __init__(self, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
# One initializer per layer: an unseeded Keras initializer returns
# the same values on every call
he = lambda: tf.keras.initializers.VarianceScaling(
2.0, 'fan_in', 'untruncated_normal')
self.net = tf.keras.models.Sequential([
tf.keras.layers.Dense(num_hiddens, activation='relu',
kernel_initializer=he()),
tf.keras.layers.Dense(10, kernel_initializer=he())])class MLP(d2l.Classifier):
def __init__(self, num_hiddens, lr, num_inputs=784, rngs=None):
super().__init__()
self.save_hyperparameters(ignore=['rngs'])
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
he = nnx.initializers.variance_scaling(2.0, 'fan_in', 'normal')
self.net = nnx.Sequential(
nnx.Linear(num_inputs, num_hiddens, kernel_init=he, rngs=rngs),
nnx.relu,
nnx.Linear(num_hiddens, 10, kernel_init=he, rngs=rngs))class MLP(d2l.Classifier):
def __init__(self, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential()
self.net.add(nn.Dense(num_hiddens, activation='relu'), nn.Dense(10))
# Normal weights with variance 2 / fan_in; biases stay zero
self.net.initialize(init.Xavier(rnd_type='gaussian', factor_type='in',
magnitude=2))Now we define corrupt(y, fraction, rng) to replace each training label with a uniform random class in \(\{0, \ldots, 9\}\) with probability fraction, train MLP(num_hiddens=256, lr=0.1) for \(200\) 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 \(100\%\) within 60–90 epochs while test accuracy plateaus above \(80\%\) (even on just \(1{,}000\) training images).
- On completely random labels, the exact same architecture and optimizer still reach \(100\%\) training accuracy (taking slightly longer, \(\sim 120\)–\(150\) epochs) while test accuracy remains at \(10\%\) random chance.
4.5.1.2 Limits of Capacity Bounds and Inductive Bias
Because our MLP achieves zero training error (\(\epsilon_{\mathcal{S}}(f) = 0\)) on random labels where the true population error is \(\epsilon(f) = 0.90\), any distribution-free bound of the form \(\epsilon(f) \leq \epsilon_{\mathcal{S}}(f) + B(\mathcal{F}, n, \delta)\) that depends only on the hypothesis class \(\mathcal{F}\) must have \(B(\mathcal{F}, n, \delta) \geq 0.90\), 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 \(100\%\) 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 \(h\) right past the sample size \(n\)? Let us test a tractable random-features model (Rahimi and Recht 2007): we freeze a He-initialized first layer \(\mathbf{W}^{(1)} \in \mathbb{R}^{784 \times 10000}\) on our \(n = 1{,}000\) centered training images to precompute \(10{,}000\) 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 \(50\) to \(10{,}000\), fitting the output weights \(\mathbf{W}^{(2)} \in \mathbb{R}^{h \times 10}\) 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 (\(h < n\)): Test error drops from \(\sim 30\%\) at \(h = 50\) to \(\sim 23\%\) around \(h = 200\), then shoots up to \(\sim 90\%\) right at the interpolation threshold \(h = n = 1{,}000\).
- Second descent (\(h > n\)): As \(h\) grows past \(n = 1{,}000\) up to \(10{,}000\), every model interpolates the training set, yet test error plunges back down to \(\sim 20\%\), beating the best underparameterized model.
Why does test error spike so violently at \(h = n\) and heal for \(h \gg n\)? Let us inspect the smallest singular value \(s_{\min}\) of \(\mathbf{H}_{:, :h}\) and the Frobenius norm \(\|\mathbf{W}^{(2)}\|_{\textrm{F}}\):
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
h = 200: smallest singular value 1.7e+00, norm of W2 3.7
h = 900: smallest singular value 1.1e-01, norm of W2 22.6
h = 1000: smallest singular value 4.5e-03, norm of W2 142.1
h = 1100: smallest singular value 9.4e-02, norm of W2 22.0
h = 10000: smallest singular value 2.0e+00, norm of W2 2.4
h = 200: smallest singular value 1.7e+00, norm of W2 3.7
h = 900: smallest singular value 1.1e-01, norm of W2 22.2
h = 1000: smallest singular value 1.7e-03, norm of W2 410.4
h = 1100: smallest singular value 9.7e-02, norm of W2 24.2
h = 10000: smallest singular value 2.1e+00, norm of W2 2.4
h = 200: smallest singular value 1.7e+00, norm of W2 3.6
h = 900: smallest singular value 1.1e-01, norm of W2 21.2
h = 1000: smallest singular value 8.8e-04, norm of W2 567.0
h = 1100: smallest singular value 1.1e-01, norm of W2 23.0
h = 10000: smallest singular value 2.3e+00, norm of W2 2.4
At \(h = n = 1{,}000\), \(\mathbf{H}\) is a square \(1000 \times 1000\) matrix with a tiny smallest singular value \(s_{\min}\), so the unique exact inverse \(\mathbf{H}^{-1}\mathbf{Y}\) divides label noise by \(s_{\min}\) and explodes \(\|\mathbf{W}^{(2)}\|_{\textrm{F}}\) into the hundreds or more. For \(h \gg n\), the extra columns open up an \((h - n)\)-dimensional subspace of exact interpolators, allowing the minimum-norm solution to avoid poorly conditioned directions and shrink \(\|\mathbf{W}^{(2)}\|_{\textrm{F}}\) all the way down to \(\sim 2\). In fact, holding \(h = 1{,}000\) fixed, doubling the training set from \(n = 500\) to \(n = 1{,}000\) lands the unregularized fit squarely on the \(h = n\) cliff and drives test error up from \(\sim 30\%\) to \(85\text{--}90\%\):
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
500 training images: test error 0.30
1000 training images: test error 0.85
500 training images: test error 0.29
1000 training images: test error 0.87
500 training images: test error 0.29
1000 training images: test error 0.87
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 \(\mathbf{H}\mathbf{w} = \mathbf{y}\) (\(h > n\), full row rank), the unique minimum-norm interpolator is \(\mathbf{w}^\star = \mathbf{H}^\top(\mathbf{H}\mathbf{H}^\top)^{-1}\mathbf{y}\).
Proposition. Gradient descent on \(L(\mathbf{w}) = \frac{1}{2}\|\mathbf{H}\mathbf{w} - \mathbf{y}\|_2^2\) initialized at \(\mathbf{w}_0 = \mathbf{0}\) (with a converging step size) converges to the minimum-norm interpolator \(\mathbf{w}^\star\).
Proof. Every gradient \(\nabla L(\mathbf{w}) = \mathbf{H}^\top(\mathbf{H}\mathbf{w} - \mathbf{y})\) lies in the row space of \(\mathbf{H}\). Starting at \(\mathbf{w}_0 = \mathbf{0}\), every iterate \(\mathbf{w}_t\), and hence the limit \(\mathbf{w}_{\infty} = \mathbf{H}^\top\mathbf{a}\), remains in the row space of \(\mathbf{H}\) (Figure 4.5.1). Since \(\mathbf{H}\mathbf{w}_{\infty} = \mathbf{H}\mathbf{H}^\top\mathbf{a} = \mathbf{y}\), we have \(\mathbf{a} = (\mathbf{H}\mathbf{H}^\top)^{-1}\mathbf{y}\) and \(\mathbf{w}_{\infty} = \mathbf{w}^\star\). Any other interpolator \(\mathbf{w}^\star + \mathbf{v}\) has \(\mathbf{H}\mathbf{v} = \mathbf{0}\) (so \(\mathbf{v} \perp \mathbf{w}^\star\)) and strictly larger norm \(\|\mathbf{w}^\star\|_2^2 + \|\mathbf{v}\|_2^2\). \(\blacksquare\)
Let us verify this proposition numerically on \(20\) equations in \(100\) unknowns, comparing \(\mathbf{w}_0 = \mathbf{0}\) 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
start zero : residual 4e-17, norm 0.54, distance to w* 0.0
start random: residual 3e-15, norm 8.94, distance to w* 8.9
start zero : residual 2e-16, norm 0.47, distance to w* 0.0
start random: residual 2e-15, norm 9.14, distance to w* 9.1
start zero : residual 1e-17, norm 0.56, distance to w* 0.0
start random: residual 1e-15, norm 8.39, distance to w* 8.4
4.5.3.2 Maximum-Margin Classification under Logistic Loss
On linearly separable binary classification data (\(y_i \in \{-1, +1\}\)) under the logistic (cross-entropy) loss \(\sum_i \log(1 + \exp(-y_i \mathbf{w}^\top\mathbf{x}_i))\), \(\|\mathbf{w}_t\|_2 \to \infty\) as \(t \to \infty\), and Soudry et al. (2018) proved that the direction \(\mathbf{w}_t / \|\mathbf{w}_t\|_2\) converges (at a \(1/\log t\) 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 \(\log(1 + e^{-m})\) (see Exercise 5 for how layer rescaling complicates parameter-norm margins in multi-layer ReLU networks).
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 \(20\%\) of the labels in our \(1{,}000\)-image training set and track accuracy separately on the clean training examples, the mislabeled training examples (scored against their corrupted labels), and the \(1{,}000\) 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 \(80\%\) of the clean training images right while memorizing fewer than \(20\%\) 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 \(\ell_2\) 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
best validation accuracy after epoch 10: test accuracy 0.767
after all 200 epochs: test accuracy 0.721
best validation accuracy after epoch 14: test accuracy 0.766
after all 200 epochs: test accuracy 0.735
best validation accuracy after epoch 20: test accuracy 0.771
after all 200 epochs: test accuracy 0.718
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 \(100\times\) longer before suddenly jumping to \(100\%\).
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 \(h = n\), where a tiny smallest singular value \(s_{\min}(\mathbf{H})\) inflates \(\|\mathbf{W}^{(2)}\|\), and descends a second time for \(h \gg n\) 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 \(1 - \delta\) over the draw of \(n\) training examples, every classifier \(f\) in a class \(\mathcal{F}\) satisfies
\[\epsilon(f) \leq \epsilon_{\mathcal{S}}(f) + B(\mathcal{F}, n, \delta). \tag{4.5.1}\]
Here \(\epsilon(f)\) is the population error, \(\epsilon_{\mathcal{S}}(f)\) is the training error, and the term \(B\) depends only on \(\mathcal{F}\), \(n\), and \(\delta\), as the term \(c\sqrt{(v + \log(1/\delta))/n}\) 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 \(\mathcal{F}\) 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 \(B(\mathcal{F}, 60{,}000, \delta)\) 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 \(\theta\) and patience \(k\) stops once the validation loss has failed to improve on its best value by more than \(\theta\) for \(k\) consecutive epochs. It then retains the parameters of the epoch with the lowest validation loss so far.- Fix \(\theta\) and apply the rule to the recorded curves for \(k \in \{1, 5, 20\}\). For each \(k\), report the stopping epoch, the retained epoch, and the test accuracy at both.
- How does the test accuracy at the retained epoch depend on \(k\)? 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 \(\mathbf{W}^{(2)} = (\frac{1}{n}\mathbf{H}^\top\mathbf{H} + \lambda \mathbf{I})^{-1}\frac{1}{n}\mathbf{H}^\top\mathbf{Y}\) of Section 2.7, which, as there, averages the squared error over the \(n\) examples.
- Plot the test error against the width for \(\lambda \in \{10^{-5}, 10^{-3}, 10^{-1}\}\). What happens to the peak at \(h = n\)?
- Show that the ridge solution approaches the minimum-norm solution as \(\lambda \to 0\) for \(h > n\). Hint: write \((\frac{1}{n}\mathbf{H}^\top\mathbf{H} + \lambda \mathbf{I})^{-1}\frac{1}{n}\mathbf{H}^\top = \mathbf{H}^\top(\mathbf{H}\mathbf{H}^\top + n\lambda \mathbf{I})^{-1}\).
- For each width, choose \(\lambda\) 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 \(\mathbf{X}^\top\mathbf{X}/n\) have eigenvalues \(\mu_i > 0\), let \(\mathbf{w}^*\) minimize \(L(\mathbf{w}) = \frac{1}{2n}\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2\), and run gradient descent on \(L\) from \(\mathbf{w}_0 = \mathbf{0}\) with learning rate \(\eta < 1/\max_i \mu_i\).
- Show that after \(t\) steps the coordinate of \(\mathbf{w}_t\) along the \(i\)-th eigenvector equals \(1 - (1 - \eta\mu_i)^t\) times that of \(\mathbf{w}^*\).
- The minimizer of \(L(\mathbf{w}) + \frac{\lambda}{2}\|\mathbf{w}\|^2\) scales the same coordinate by \(\mu_i/(\mu_i + \lambda)\) (Section 2.7.3). For which \(\lambda\), as a function of \(\eta\) and \(t\), do the two factors approximately agree both in the directions with \(\eta\mu_i t \ll 1\) and in those with \(\eta\mu_i t \gg 1\)?
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 \(y_i \in \{-1, +1\}\).
- For a linear predictor \(f(\mathbf{x}) = \mathbf{w}^\top\mathbf{x}\), show that on separable data the loss \(\sum_i \log\left(1 + \exp(-y_i \mathbf{w}^\top\mathbf{x}_i)\right)\) is positive for every \(\mathbf{w}\) but has infimum zero. Conclude that \(\|\mathbf{w}_t\|\) grows without bound when gradient descent drives the loss to zero, so that only the direction \(\mathbf{w}_t/\|\mathbf{w}_t\|\) can converge.
- For a two-layer ReLU network \(f(\mathbf{x}) = \sum_j v_j \max(0, \mathbf{w}_j^\top\mathbf{x})\), show that replacing \((\mathbf{w}_j, v_j)\) by \((c_j\mathbf{w}_j, v_j/c_j)\) with \(c_j > 0\) leaves \(f\) unchanged. Find the smallest value of \(\sum_j (\|\mathbf{w}_j\|^2 + v_j^2)\) over these rescalings. Explain why a margin measured with the parameter norm of the network, unlike one measured with \(\|\mathbf{w}\|\) for the linear predictor, is not a property of the function \(f\) 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 \(c = (a + b) \bmod 97\) from the pair \((a, b)\), using a random 50% of all pairs for training, with weight decay, for \(10^5\) 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?