TExcelTAD
Home › Math for Deep Learning & LLMs › Regularization in Deep Learning

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 λ2∥w∥2\frac{\lambda}{2}\lVert\mathbf{w}\rVert^2 to the loss adds λw\lambda\mathbf{w} to the gradient, so a gradient step becomes

w←w−η(∇L+λw)=(1−ηλ)w−η∇L\mathbf{w} \leftarrow \mathbf{w} - \eta(\nabla\mathcal{L} + \lambda\mathbf{w}) = (1 - \eta\lambda)\mathbf{w} - \eta\nabla\mathcal{L}

The weights decay by a factor 1−ηλ1 - \eta\lambda every step. Probabilistically it is a Gaussian prior on the weights (MAP Estimation). For a quadratic loss with Hessian eigenvalues λi\lambda_i, the penalty shrinks the optimum along each eigenvector by λiλi+λ\frac{\lambda_i}{\lambda_i + \lambda}: directions the data barely constrains (small λi\lambda_i) are shrunk most.

python · try it yourself
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 λ\lambda shrinks the weights and cuts the test error sharply, while a very large one shrinks the useful weights too and underfits.

With Adam, adding λw\lambda\mathbf{w} 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

λ∥w∥1\lambda\lVert\mathbf{w}\rVert_1 has a constant-size subgradient λsign⁡(w)\lambda\operatorname{sign}(w), 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 pp during training. It prevents units from relying on specific partners (co-adaptation) and approximately trains an ensemble of 2n2^n 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.

python · try it yourself
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 w0=0\mathbf{w}_0 = \mathbf{0}, stopping after tt steps of size η\eta behaves like L2 regularization with λ≈1tη\lambda \approx \frac{1}{t\eta}: 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 1−ε1 - \varepsilon 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 η=0.01\eta = 0.01 and λ=0.1\lambda = 0.1, by how much does weight decay alone shrink the weights over 1000 steps?

Answer

To about 0.3680.368 of their value.

Solution

(1−0.001)1000≈e−1≈0.368(1 - 0.001)^{1000} \approx e^{-1} \approx 0.368.

Exercise 2: Shrinkage per direction

The Hessian has eigenvalues 1010 and 0.10.1, and λ=1\lambda = 1. By what factor is the optimum shrunk along each eigenvector?

Answer

10/11≈0.9110/11 \approx 0.91 and 0.1/1.1≈0.090.1/1.1 \approx 0.09.

Solution

The factor is λi/(λi+λ)\lambda_i/(\lambda_i + \lambda). 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 12(w−0.3)2+0.5∣w∣\frac{1}{2}(w - 0.3)^2 + 0.5\lvert w \rvert with the proximal (soft-threshold) update and report ww.

Answer

w=0w = 0: the penalty 0.50.5 exceeds the pull 0.30.3.

Solution

The minimizer is the soft threshold sign⁡(0.3)max⁡(0,0.3−0.5)=0\operatorname{sign}(0.3)\max(0, 0.3 - 0.5) = 0.

python · try it yourself
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 λ2∥w∥2\frac{\lambda}{2}\lVert\mathbf{w}\rVert^2 is equivalent to…

  1. dropout
  2. multiplying the weights by 1−ηλ1 - \eta\lambda every step
  3. early stopping
  4. doubling the learning rate

Which penalty tends to produce exactly-zero weights?

  1. L2
  2. L1
  3. dropout
  4. label smoothing

Early stopping on a quadratic from w0=0\mathbf{w}_0 = \mathbf{0} behaves like…

  1. L1 regularization
  2. L2 regularization with strength about 1/(tη)1/(t\eta)
  3. no regularization
  4. data augmentation