Regularization: Weight Decay, Dropout and Early Stopping
Regularization is any change to learning meant to reduce test error rather than training error. Deep networks use several kinds at once: a penalty on the weights, noise injected during training, more (augmented) data, and stopping before the training loss bottoms out. Each has a clean mathematical reading, and some turn out to be the same thing in disguise.
L2 penalty and weight decay
Adding to the loss adds to the gradient, so a gradient step becomes
The weights decay by a factor every step. Probabilistically it is a Gaussian prior on the weights (MAP Estimation). For a quadratic loss with Hessian eigenvalues , the penalty shrinks the optimum along each eigenvector by : directions the data barely constrains (small ) are shrunk most.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(25, 20)); w_true = np.zeros(20); w_true[:3] = [2.0, -1.0, 0.5] # 25 examples, 20 features
y = X @ w_true + rng.normal(0, 1.0, 25)
X_te = rng.normal(size=(1000, 20)); y_te = X_te @ w_true + rng.normal(0, 1.0, 1000)
for lam in (0.0, 1.0, 10.0, 100.0):
w = np.linalg.solve(X.T @ X + lam * np.eye(20), X.T @ y)
print(f"lambda {lam:5.1f}: |w| = {np.linalg.norm(w):.3f}, test MSE {np.mean((X_te @ w - y_te)**2):.4f}")lambda 0.0: |w| = 5.039, test MSE 16.3342
lambda 1.0: |w| = 2.540, test MSE 1.8443
lambda 10.0: |w| = 1.501, test MSE 2.4004
lambda 100.0: |w| = 0.458, test MSE 4.7607
With only 25 examples for 20 weights, the unregularized fit chases noise; a moderate shrinks the weights and cuts the test error sharply, while a very large one shrinks the useful weights too and underfits.
With Adam, adding to the gradient is not the same as decaying the weights, because Adam rescales the gradient per coordinate. AdamW applies the decay separately (Adam and AdamW).
L1 penalty and sparsity
has a constant-size subgradient , which pushes small weights exactly to zero: a sparse model. It is used for pruning and feature selection more than in standard network training.
Dropout
Dropout (Probability for DL) zeroes each unit with probability during training. It prevents units from relying on specific partners (co-adaptation) and approximately trains an ensemble of sub-networks that share weights. For a linear model with inputs dropped, the expected loss equals the plain loss plus an L2-like penalty scaled by each feature's variance.
import numpy as np
rng = np.random.default_rng(1)
x = np.array([1.0, 2.0, -1.0]); w = np.array([0.5, -0.3, 0.8]); y = 1.0; p = 0.5
losses = []
for _ in range(200000):
m = (rng.uniform(size=3) > p) / (1 - p)
losses.append((y - w @ (m * x))**2)
print("Monte Carlo expected loss:", round(np.mean(losses), 3))
theory = (y - w @ x)**2 + p / (1 - p) * np.sum(w**2 * x**2)
print("plain loss + penalty :", round(theory, 3))Monte Carlo expected loss: 4.849
plain loss + penalty : 4.86
Early stopping
Stop training when the validation loss stops improving and keep the best checkpoint. For gradient descent on a quadratic from , stopping after steps of size behaves like L2 regularization with : directions with small curvature have not been learned yet.
Data augmentation and label smoothing
Flipping, cropping or color-jittering images (or masking tokens) encodes invariances and enlarges the dataset. Label smoothing replaces a one-hot target with on the true class, which caps how large the logit gaps grow.
In software
torch.optim.AdamW(weight_decay=0.1)is the standard for transformers; biases and normalization gains are usually excluded from decay.nn.Dropout(p=0.1)in transformer blocks; many large LLMs train with no dropout at all because they see each token once.- Early stopping is a callback in Keras and Lightning.
Exercises
Exercise 1: Decay factor
With and , by how much does weight decay alone shrink the weights over 1000 steps?
Answer
To about of their value.
Solution
.
Exercise 2: Shrinkage per direction
The Hessian has eigenvalues and , and . By what factor is the optimum shrunk along each eigenvector?
Answer
and .
Solution
The factor is . The well-determined direction keeps most of its value; the poorly determined one is nearly zeroed.
Exercise 3: L1 drives weights to zero (code)
Minimize with the proximal (soft-threshold) update and report .
Answer
: the penalty exceeds the pull .
Solution
The minimizer is the soft threshold .
import numpy as np
soft = lambda v, t: np.sign(v) * np.maximum(0, np.abs(v) - t)
print(soft(0.3, 0.5), soft(1.3, 0.5))0.0 0.8
Test yourself
With plain SGD, an L2 penalty is equivalent to…
- dropout
- multiplying the weights by every step
- early stopping
- doubling the learning rate
Which penalty tends to produce exactly-zero weights?
- L2
- L1
- dropout
- label smoothing
Early stopping on a quadratic from behaves like…
- L1 regularization
- L2 regularization with strength about
- no regularization
- data augmentation