2.7 Weight Decay
In Section 2.6, we controlled model complexity in the bluntest way possible: by changing the discrete number of polynomial features . Yet discrete feature selection quickly hits a wall. In high-dimensional problems with hundreds or thousands of features, there are possible feature subsets, and worse still, we saw that when a polynomial overfits, its weights explode into the millions and beyond to cancel almost-collinear features against one another.
To see the core pathology in its simplest two-feature form, imagine predicting room temperature from two noisy thermometers placed side by side, and , each reading the true temperature plus a tiny independent noise wiggle. Consider two linear models whose weights sum to :
- Model A sets , averaging the two sensors and cutting the sensor noise variance in half.
- Model B sets . Whenever the two thermometers agree, gives the same average, yet any tiny discrepancy between the two sensors gets amplified by .
On a small training sample where happened by chance to correlate slightly with the label noise, unregularized least squares will choose to shave a sliver off the training error, only to fail badly on new readings. How can we keep all features in the model while preventing the weights from blowing up along poorly determined directions?
The classic remedy, known as ridge regression or Tikhonov regularization in statistics (Hoerl and Kennard, 1970; Tikhonov and Arsenin, 1977) and weight decay in deep learning, adds a smooth penalty on the squared Euclidean norm directly to the loss function. In this section, we derive weight decay from four complementary perspectives (penalized optimization, per-step multiplicative decay in SGD, Bayesian Gaussian priors, and spectral shrinkage along eigenvectors of ) and implement it both from scratch and concisely in all four frameworks.
2.7.1 Norm Penalties#
2.7.1.1 The Penalized Loss#
Rather than restricting the number of features, we control a linear model's effective capacity by penalizing the squared norm of its weight vector . Adding this penalty to the mean squared error loss with a nonnegative regularization constant yields the regularized objective:
Once again, the factor of cancels the when we differentiate . Notice three basic properties of (2.7.1):
- Trade-off via : Setting recovers unregularized least squares; increasing places a steeper tax on large weights, pulling toward (and driving as ).
- Why we leave the bias unpenalized: The bias simply shifts the average output level to match the mean of the target ; shrinking toward zero would bias every prediction toward zero if were measured in, say, Kelvin instead of Celsius, without reducing the model's sensitivity to input perturbations at all.
- Feature scaling matters: Because sums raw squared coefficients across coordinates, re-expressing one feature in millimeters instead of meters divides its weight by and cuts its penalty contribution by . In practice, one standardizes features to comparable scales (zero mean, unit variance) before applying an isotropic penalty.
Why penalize the squared norm? In our two-thermometer example, has , whereas has , so even a tiny strongly prefers averaging the two sensors over subtracting them.
2.7.1.2 Weight Decay in the Gradient Step#
How does the penalty change our minibatch SGD update rule? Since , the penalized gradient step is
Look at the first term on the right: before taking the usual data-driven gradient step , we multiply the weight vector by , shrinking ("decaying") it slightly toward zero on every update. That multiplicative shrinkage factor is why deep learning practitioners call regularization weight decay. (For plain SGD, adding to the loss and decaying weights by are algebraically identical; for adaptive optimizers like Adam in Chapter 9, decoupling multiplicative weight decay into AdamW makes an important difference.)
2.7.1.3 The Penalty and Sparsity#
What if we replaced the squared norm with the norm , a method known in statistics as the Lasso (Tibshirani, 1996)? Comparing the geometry of their constraint sets (Figure 2.7.1) reveals a striking difference. Minimizing the data loss subject to searches inside a smooth round disk (or sphere in ), where the elliptical loss contours almost always touch the boundary at a point where every coordinate is small but nonzero. Minimizing subject to , by contrast, searches inside a sharp-cornered diamond (cross-polytope) whose vertices lie directly on the coordinate axes. Elliptical loss contours frequently collide with one of those sharp corners first, setting many coordinates to exact zero and performing automatic feature selection (sparsity).
Constraint geometry of ridge regression (left) vs. Lasso regression (right). Elliptical contours of the data loss expanding from the unregularized minimum typically meet the smooth circle away from the axes (keeping both weights nonzero), whereas they often hit a sharp corner of the diamond right on an axis (setting ).
2.7.1.4 A Gaussian Prior on the Weights#
Just as maximum likelihood under Gaussian observation noise gave us the squared data loss in Section 2.1.3, Bayesian statistics gives weight decay an equally clean probabilistic interpretation. Suppose that before observing any data, we place an isotropic zero-mean Gaussian prior distribution on the weights, independently, so , while the labels follow .
By Bayes' theorem, the posterior density is maximized by minimizing its negative logarithm (maximum a posteriori or MAP estimation):
Dividing through by recovers our weight-decay objective (2.7.1) with . Notice how sensible that ratio is: stronger prior belief that weights are small (smaller ) or noisier observations (larger ) calls for stronger regularization , whereas as the sample size , the penalty because abundant data eventually speak for themselves.
2.7.2 Weight Decay from Scratch#
To see weight decay rescue a model with nearly as many weights as training examples, let us construct a high-dimensional synthetic regression problem where the dimension comes close to the training sample size . Specifically, we draw inputs and generate labels from
with training examples (in minibatches of 20) and validation examples, using SyntheticRegressionData from Section 2.4. The true weights have coordinate scale , and the noise is substantial: its standard deviation is comparable to that of the noise-free signal, . While 300 examples are technically enough to identify all 200 weights, we will soon see that many linear combinations of them are pinned down only weakly.
tau, sigma, n = 0.1, 1.0, 300 # size of the weights, noise, examples
data = d2l.SyntheticRegressionData(w=d2l.ones(200) * tau, b=0.05,
noise=sigma, num_train=n, num_val=1000,
batch_size=20)
Before training anything, let us set two benchmarks for the validation loss. For independent standard normal inputs and noise , the expected loss at equals (Section 2.3). A trivial constant model that ignores all 200 inputs and predicts everywhere therefore incurs an expected loss of , while the oracle parameters achieve . Any learned model must land comfortably below 1.5 to justify its 200 weights.
2.7.2.1 The Penalized Model#
We define l2_penalty(w) to return :
def l2_penalty(w):
return d2l.reduce_sum(w**2) / 2
We subclass LinearRegressionScratch from Section 2.4 (our
object-oriented version of the scratch model in
Section 2.3). Only training_step needs to change so that
it returns the penalized objective (2.7.1) for
differentiation and optimization. Crucially, validation_step continues to
report the unpenalized squared loss, ensuring that validation losses across
different values of remain directly comparable measures of
predictive accuracy.
class WeightDecayScratch(d2l.LinearRegressionScratch):
def __init__(self, num_inputs, lambd, lr, sigma=0.01):
super().__init__(num_inputs, lr, sigma)
self.save_hyperparameters()
def training_step(self, batch):
loss = super().training_step(batch)
return loss + self.lambd * l2_penalty(self.w)2.7.2.2 Training with and without the Penalty#
Let us write train_scratch(lambd, data) to train WeightDecayScratch for 50 epochs at learning rate (750 SGD steps) while plotting the training and validation curves, and to return the fitted model, the per-epoch validation losses, and the learned weight norm (for comparison, the true weight vector has ):
def train_scratch(lambd, data):
trainer = d2l.Trainer(max_epochs=50)
model = WeightDecayScratch(num_inputs=200, lambd=lambd, lr=0.05)
trainer.fit(model, data)
norm = float(torch.linalg.vector_norm(model.w.detach()))
return model, [float(v) for v in trainer.history['val_loss']], normWe begin with lambd = 0, disabling regularization altogether.
model_0, val_losses, norm = train_scratch(0, data)print(f'validation loss {val_losses[-1]:.3f} (lowest {min(val_losses):.3f}, '
f'epoch {val_losses.index(min(val_losses)) + 1}), norm of w {norm:.2f}')validation loss 1.610 (lowest 0.891, epoch 2), norm of w 2.03
The training loss plunges to roughly 0.2–0.3, far below the irreducible noise floor of 0.5 achieved by the true parameters, confirming that the model is memorizing noise in its 300 training labels. Meanwhile, the validation loss hits a minimum of 0.8–1.0 after just two or three epochs and then climbs steadily, typically finishing between 1.1 and 1.9. After 50 epochs, this 200-weight model has given back much of its early gain and often does no better than (and sometimes worse than) the trivial constant at 1.5: a textbook display of overfitting. Why does validation loss bottom out so early, after only 30 to 45 gradient steps? We will uncover the reason once we examine which directions in weight space gradient descent learns first.
Next, we turn on weight decay. Rather than guessing blindly, we consult the Gaussian prior formula: for , , and true weight scale , MAP estimation prescribes .
lambd = sigma**2 / (n * tau**2) # the value the prior suggests, 1/3
model_lambd, val_losses, norm = train_scratch(lambd, data)print(f'validation loss {val_losses[-1]:.3f}, norm of w {norm:.2f}')validation loss 0.874, norm of w 1.17
Now the training curve tracks the penalized objective, which stays safely above 0.5: the penalty keeps the model from chasing noise in the training labels. Validation loss settles at roughly 0.75–1.05 and stays flat, well below the 1.5 baseline of the constant predictor, while the weight norm shrinks from roughly 2 to about 1.2, actually shorter than the true norm . Even though the regularized weights are shrunk below the true length, they generalize dramatically better than the unregularized weights.
Let us be honest about what we gained here. Compared with the unpenalized model trained for all 50 epochs, weight decay slashes the validation loss by a quarter to a half. Compared with that same unpenalized model stopped at its best epoch, however, the gain is small: both reach roughly 0.8–1.0. The practical difference is stability. Because weight decay changes the objective itself, its solution stays good no matter how long we train, whereas the unpenalized run must be halted at a sweet spot that the training loss alone gives no hint of. To understand why both regularization and early stopping behave this way, let us look inside the weight vector and ask which components the penalty actually removed.
2.7.3 Shrinkage Along Eigenvectors#
Why does adding improve validation error so dramatically instead of just scaling every weight down blindly? We can answer that question in closed form by looking at the exact minimizer of the ridge objective in the eigenbasis of the feature covariance matrix.
2.7.3.1 The Ridge Estimator#
Suppose the features and labels are centered so , and write the ridge objective (2.7.1) in matrix form:
Setting the gradient gives the regularized normal equations:
Notice the immediate algebraic consequence: even when is singular (as it is whenever there are fewer examples than features: with and , has 180 zero eigenvalues, exercise 6), adding for any shifts every eigenvalue upward by , making strictly positive definite and invertible.
2.7.3.2 Shrinkage Factors#
To see how (2.7.6) acts along each direction in feature space, let be the sample second-moment (covariance) matrix of the features. Since is symmetric and positive semidefinite (Section 1.3), it admits an orthonormal eigendecomposition with eigenvalues and orthonormal eigenvectors . Here measures the empirical variance (spread) of the training inputs along direction .
In this eigenbasis, acts on by multiplying it by , while acts on by dividing by . Whenever , comparing the ridge component against the unregularized least-squares component yields
Each eigendirection is multiplied by its own shrinkage factor (Figure 2.7.2):
The ridge shrinkage factor along an eigenvector with eigenvalue , against the regularization constant (log scale). A direction well determined by the data is kept nearly untouched while and is strongly shrunk toward zero once ; the factor is at (dots). Directions with are set to zero for every (dashed).
Here lies the secret of ridge regression: weight decay is not uniform shrinkage; it is variance-adaptive directional filtering.
- Along well-determined directions where the data vary richly (), the slope is tightly pinned down by observations, and the shrinkage factor leaves the least-squares estimate nearly untouched.
- Along poorly determined directions where the data barely vary (), such as the difference between our two almost-identical thermometers, unregularized least squares divides noise by a tiny and blows up (with coefficient variance ), whereas ridge regression multiplies by and damps the noisy component.
- Along unobserved null-space directions (), ridge regression sets the weight component identically to .
2.7.3.3 The Directions Our Data Determine#
Let us verify this spectral picture on our dataset data. First, we compute the eigenvalues of for the 300 training inputs (uncentered, which scarcely alters the spectrum) along with the shrinkage factors at . As in Section 1.3, eigh returns the eigenvalues in ascending order with the eigenvectors as the columns of its second output. We also count how many eigenvalues fall below , marking the poorly determined directions where ridge removes more than half of the least-squares coordinate:
X = data.X[:n] # the 300 training inputs
mu, V = torch.linalg.eigh(X.T @ X / n) # increasing eigenvalues
factors = mu / (mu + lambd) # shrinkage at lambda = 1/3
k = int((mu < lambd).sum()) # the poorly determined ones
print(f'mu from {float(mu[0]):.2f} to {float(mu[-1]):.1f}, '
f'{k} of {len(mu)} below lambda')
print(f'factors from {float(factors[0]):.2f} to {float(factors[-1]):.2f}, '
f'df = {float(factors.sum()):.0f}')mu from 0.04 to 3.2, 54 of 200 below lambda
factors from 0.10 to 0.91, df = 127
None of the eigenvalues is zero: 300 examples are enough to span all 200 dimensions of weight space. Yet the data constrain some directions far more tightly than others. The eigenvalues span nearly two orders of magnitude, from a few hundredths up to about 3.2, with roughly a quarter of them (50 to 60 directions) lying below . The corresponding shrinkage factors range from about 0.1 to 0.9. Their sum defines the effective number of parameters , and here : out of 200 raw weights, the regularized model behaves as though it has roughly 127 effective parameters.
Just how much damage does a tiny eigenvalue inflict on least squares? Along
eigenvector , label noise injects
into
, a random
perturbation with standard deviation
(because ). Least squares divides
by , which shifts its coordinate by roughly
: about 0.06 when , but a whopping 0.3
when . Since the true coordinates are only around
in magnitude, least squares along the
smallest-eigenvalue directions is swamped by noise. Meanwhile, validation
inputs are isotropic standard normal, so orthogonal invariance of means that an error along
inflates the expected validation loss by ,
regardless of . Let us verify this directly by projecting the
parameter error of both trained models onto the
eigenvectors (V.T @ (w - w_star)) and comparing the total squared error
accumulated in the poorly determined directions versus the remaining
ones:
w_star = d2l.reshape(data.w, (-1, 1))
for name, model in (('lambda = 0', model_0), ('lambda = 1/3', model_lambd)):
c = V.T @ (model.w.detach() - w_star) # error along each eigenvector
print(f'{name:>12}: squared error {float((c[:k] ** 2).sum()):.2f} in the '
f'{k} poorly determined directions, '
f'{float((c[k:] ** 2).sum()):.2f} in the rest') lambda = 0: squared error 1.49 in the 54 poorly determined directions, 0.52 in the rest
lambda = 1/3: squared error 0.30 in the 54 poorly determined directions, 0.40 in the rest
The breakdown tells the whole story. Without regularization, roughly one quarter of the eigenvectors account for more than half of the total squared parameter error: typically between 0.8 and 2.2, versus only about 0.5 across all the remaining directions combined. Turning on weight decay slashes that poorly determined error by a factor of two to six while trimming the rest modestly, leaving roughly 0.3 to 0.5 in each group. Even along the better-determined directions, label noise is nontrivial relative to the true coordinates, so shrinking them by 0.5–0.9 still discards more noise than signal. As a quick sanity check, half the total squared parameter error plus roughly matches the validation loss we observed for both runs. In effect, weight decay performed across some fifty ill-conditioned directions simultaneously the same selective damping it performs on the difference direction of our two thermometers.
This spectral lens also solves the mystery we left hanging earlier: why did the unpenalized run hit its lowest validation loss after just two or three epochs? On the unpenalized loss, each gradient step contracts the gap between the current coordinate along and its least-squares solution by a factor of . After a single epoch of 15 steps at , a large-eigenvalue direction () has already closed of its gap, whereas a small-eigenvalue direction () has closed a mere . After two epochs, gradient descent has essentially converged along the well-determined directions while barely moving along the noisy ones—closely mimicking the ridge estimator. The resemblance can be made quantitative. Starting from weights near zero, steps build up the fraction of the least-squares coordinate along , and this is close to the ridge factor with : both are nearly when and nearly when . Our best stopping point of 30 to 45 steps at gives between and , the same order as the that the prior prescribed. Keep training, however, and those poorly determined directions steadily soak up label noise, driving validation loss back up. Early stopping is therefore a genuine form of regularization in its own right, and in this experiment it matches weight decay in accuracy. It is trickier to deploy, however, because the optimal stopping point shifts with the learning rate and minibatch noise and must be monitored on validation data throughout every run (exercise 5).
2.7.4 Concise Implementation#
Because weight decay is ubiquitous in neural network training, every major deep learning framework lets the optimizer apply the update (2.7.2), so you need not modify the loss function. Beyond convenience, this integration is computationally clean: the optimizer already visits every parameter once per step, so applying the decay factor adds virtually no overhead. Frameworks also support per-parameter update rules, allowing us to decay weights while leaving biases untouched.
We simply subclass d2l.LinearRegression into WeightDecay and pass the weight decay hyperparameter wd to the framework's SGD optimizer in configure_optimizers (excluding the bias parameter from decay so that only the weights are penalized, matching (2.7.1)).
PyTorch optimizers accept a weight_decay argument. By splitting the
parameters into two parameter groups, we apply weight_decay only to
net.weight while leaving net.bias unregularized. Just as in
Section 2.5, we initialize the weights from
and the bias to zero by applying weight_init
after the first forward pass materializes the lazy layer's parameters.
class WeightDecay(d2l.LinearRegression):
def __init__(self, wd, lr):
super().__init__(lr)
self.save_hyperparameters()
def configure_optimizers(self):
return torch.optim.SGD([
{'params': self.net.weight, 'weight_decay': self.wd},
{'params': self.net.bias}], lr=self.lr)To match train_scratch(lambd, data) exactly, we must rescale both
hyperparameters. Because the built-in squared-error loss omits our factor
of , we halve the learning rate to 0.025 just as in
Section 2.5. However, the decay term
is injected inside the optimizer rather than multiplied by the loss
gradient. With the learning rate cut in half, the optimizer's weight decay
must therefore be doubled to so that every step
retains the exact same contraction factor
.
trainer = d2l.Trainer(max_epochs=50)
model = WeightDecay(wd=2 * lambd, lr=0.025)
model(data.X[:1]) # Creates the parameters of the lazy layer
model.net.apply(model.weight_init)
trainer.fit(model, data)
norm = float(torch.linalg.vector_norm(model.get_w_b()[0]))print(f'validation loss {trainer.history["val_loss"][-1]:.3f}, '
f'norm of w {norm:.2f}')validation loss 1.785, norm of w 1.17
The resulting weight norm (around 1.2) reproduces our from-scratch run at , and the validation loss (about twice the from-scratch value) agrees too once we account for the factor of 2 in the framework's mean squared error. Note that the plotted training curve now tracks plain mean squared error rather than the penalized loss, because the decay lives inside the optimizer rather than the loss function.
In everyday practice, enabling weight decay is as simple as passing this single optimizer hyperparameter. Outside synthetic benchmarks we rarely know the noise level or prior scale in advance, so is typically tuned on validation data across candidate runs. Keep in mind that our norm-based story applies directly to linear models, whose weights are the slopes of the function itself. For nonlinear functions, measuring complexity rigorously is subtler: frameworks such as reproducing kernel Hilbert spaces (RKHS) extend norm penalties to nonlinear functions, though classical kernel methods scale poorly to massive datasets. Even so, applying weight decay to the weights of neural network layers remains one of the most reliable regularizers in modern deep learning.
2.7.5 Summary#
Adding a squared penalty to the training objective (while leaving the bias unpenalized) keeps high-dimensional models from amplifying noise along nearly collinear feature combinations. In minibatch SGD, this penalty multiplies by before each gradient step—hence the name weight decay—and corresponds to maximum a posteriori estimation under an isotropic Gaussian prior with . Whereas the sharp corners of an penalty drive weights to exact zero, the smooth penalty acts as a directional filter in the eigenbasis of : multiplying each least-squares component by preserves directions well determined by the data (), strongly damps noisy directions (), and zeroes unobserved null-space directions ().
2.7.6 Exercises#
-
The update. Replace the penalty by .
- Derive the minibatch SGD update for , using the subgradient of exercise 2 in place of the derivative of .
- Compare the change that the penalty alone makes to in one step of this update with the change it makes in the update (2.7.2), once for large and once for small .
- The update of (a) almost never sets exactly to zero. Split it into a gradient step on followed by the penalty step, and modify the penalty step so that it sets to zero whenever it would change the sign of . Relate the result to the feature selection that lasso performs. The modified step is soft-thresholding, the proximal step of the norm (Section 23.6.4.1).
-
Shrinkage versus penalty. Weight decay can be applied by shrinking the weights before the gradient step or by adding to the loss .
- Show that the update is identical to a gradient step on the penalized loss .
- Suppose that the gradient is rescaled coordinate-wise by fixed constants before the step. Shrinking and then stepping gives the first update below, and stepping on the penalized gradient gives the second:
Determine for which the two coincide, and the factor by which the second update shrinks in a step with . Many optimizers used in deep learning rescale the gradient in this way. Which of the two updates keeps a rate of decay that is the same for every weight?
Adapted from Simon Prince, Understanding Deep Learning, Problem 9.5.
-
[code] Ridge as augmented least squares. Center the 300 training inputs and labels so that the bias drops out, and compute the ridge estimator for in two ways.
- Solve the linear system (2.7.6) directly, for
instance with
np.linalg.solve. - Run ordinary least squares with
lstsqon stacked on top of , with the labels followed by zeros.
Confirm that the two agree up to rounding errors, and explain why. Then compare the norm of the result with the norm that
train_scratch(lambd, data)returned, and name the differences between the two procedures that could account for any gap.Adapted from Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning, Exercise 3.12.
- Solve the linear system (2.7.6) directly, for
instance with
-
[code] The sweep. Train
WeightDecayScratchondatafor .- Plot the final validation loss and the norm of against
on a logarithmic axis, with the values of
train_scratch(0, data)as horizontal lines, and report the with the smallest validation loss. - Compute for the same values from the eigenvalues of Section 2.7.3, and plot the validation loss against . Compare the shape with Figure 2.6.1.
- Is the value that the prior suggests close to the best value of the sweep? Generate data with noise and with , recompute the prior's for each, and check whether it follows the best value of a sweep.
- Plot the final validation loss and the norm of against
on a logarithmic axis, with the values of
-
[code] Stopping early versus decay. The unpenalized run of this section reaches its lowest validation loss after two or three epochs, about as low as the run with ends.
- From weights near zero, gradient descent on the unpenalized loss multiplies the gap between the coordinate along and its least-squares value by per step, so after steps it has built up the fraction of that coordinate. Plot this factor against for the eigenvalues of Section 2.7.3, with equal to one, two, and fifty epochs of 15 steps at , next to the ridge factor at . Which comes closest to ridge?
- Train
WeightDecayScratchwith for two epochs and split its error along the eigenvectors as Section 2.7.3 does. Compare the squared error in the poorly determined directions and in the rest with the values printed there for 50 epochs at and at . - Repeat the unpenalized run at and at and
read the best epoch from
trainer.history. Explain how it moves, and state what early stopping requires in practice that the penalty does not.
-
[code] More weights than examples. ● Generate data with 200 features and only 20 training examples, true weights , bias , and noise , in minibatches of 5.
- Compute the eigenvalues of for the 20 training inputs. How many are zero, and why does gradient descent never change the weights along their eigenvectors?
- Train with and with for 30 epochs at
learning rate 0.01, once from the random initialization of
WeightDecayScratchand once from (passsigma=0). Before you run, predict the four validation losses from the norm of the initial weights in the undetermined directions; then compare. - Compare all four losses with that of a model that predicts everywhere. What did weight decay achieve here, and what could no value of achieve?