MLDay 36 of 50Deep Learning
Regularize Networks
Dropout and Weight Decay
A network with 669,706 weights learns 1,000 photos of clothes until its training loss is 0.007. It has memorized them. Meanwhile its validation loss climbs from 0.57 to 1.00. You want to keep the big network but stop the memorizing.
The idea
Two cheap fixes push a network toward patterns that hold on new data.
- Dropout switches off a random share of a layer's units at every training step: their outputs become
0. No unit can count on a given neighbour being there, so the network spreads what it knows across many
units instead of leaning on a few. Dropout runs only in training. At evaluation every unit works. That is
why the training loop from
D32 calls
model.train()before training andmodel.eval()before scoring: the two calls turn dropout on and off. - Weight decay shrinks every weight a little toward 0 at every step. A weight stays big only if the data
keeps pushing it back up. It's the same pull toward small weights as the ridge penalty from
D11.
In PyTorch it's the
weight_decaysetting of theAdamWoptimizer.
Early stopping, from D25, is the third tool: keep the model from the epoch with the lowest validation loss. All three combine.
A tiny example
Dropout with on a layer whose four units output (2.0, 1.0, 3.0, 0.5). The coin flips keep units 1 and 3 and zero the others. The kept outputs are doubled, so the layer passes on (4.0, 0, 6.0, 0).
Why double? Each unit survives half the time. Doubling keeps its average output at 2.0, the value it gives at evaluation, when nothing is dropped and the layer passes on (2.0, 1.0, 3.0, 0.5) unchanged.
Weight decay with a shrink factor of 0.95 per step turns a weight of 2.0 into 1.90, then 1.805, unless the gradients push it back.
The formula
Dropout keeps each unit with probability and scales the kept ones up (inverted dropout):
| Symbol | Meaning |
|---|---|
| unit 's output | |
| the dropout rate: the chance a unit is switched off (PyTorch's default is 0.5) | |
| a fresh random mask: 0 with probability , else 1 | |
| what the next layer sees during training; at evaluation it's just |
Worked: turns a kept into .
AdamW shrinks every weight before it takes its usual step:
| Symbol | Meaning |
|---|---|
| one weight | |
| the learning rate | |
the weight-decay strength (weight_decay) |
|
| the step Adam takes from the gradients anyway |
Worked: and give a factor of per step. Left alone for 800 steps, a weight would shrink to of its size.
Try it
A degree-12 curve has 13 weights for 12 training points, so, like the network, it can memorize them. The slider is D11's ridge penalty, here playing weight decay.
Shrink the weights of a curve that memorizes
Round dots are the training points (the fit sees them); squares are validation points (held back). Raise the degree and watch both errors.
degree 12train RMSE 0.01validation RMSE 25.57weights' size ‖w‖ 20431.72
Fitted by least squares, with x rescaled to −1…1 first; ‖w‖ leaves out the intercept.
At α = 0 the curve passes through every training hour (train RMSE 0.01) but misses the held-back hours by 25.57, and the weights' size ‖w‖ is over 20,000. Nudge weight decay to 0.01: validation RMSE falls to 2.43 and ‖w‖ to 96. Drag it to 1 and the curve goes too stiff: validation RMSE climbs back to 6.75. Watch train RMSE too: at 0.01 it rises from 0.01 to 2.92, just as weight decay raised the network's training loss from 0.007 to 0.245 below. Giving up some training fit is the price of every regularizer.
In code
This uses the Fashion-MNIST split shared by the Phase 4 lessons, but keeps only the first 1,000 of its 5,000
training images, so overfitting shows within a few epochs. The network is wide: two hidden layers of 512
units. AdamW with weight_decay=0 is plain Adam.
# script_id: day_036_dropout_and_weight_decay/regularize
import os
from pathlib import Path
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X = torch.tensor(d["X_train"] / 255, dtype=torch.float32)
X_tr, X_val, y_tr, y_val = train_test_split(X, torch.tensor(d["y_train"]).long(), test_size=1000,
stratify=d["y_train"], random_state=42)
X_tr, y_tr = X_tr[:1000], y_tr[:1000] # 1,000 training images, so overfitting shows fast
loss_fn = nn.CrossEntropyLoss()
def train(p_drop=0.0, decay=0.0, epochs=50):
torch.manual_seed(42)
model = nn.Sequential(nn.Flatten(), nn.Linear(784, 512), nn.ReLU(), nn.Dropout(p_drop),
nn.Linear(512, 512), nn.ReLU(), nn.Dropout(p_drop), nn.Linear(512, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=decay)
batches = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True,
generator=torch.Generator().manual_seed(42))
curves = [] # (train loss, validation loss) per epoch
for _ in range(epochs):
model.train() # dropout on
for xb, yb in batches:
opt.zero_grad()
loss_fn(model(xb), yb).backward()
opt.step()
model.eval() # dropout off
with torch.no_grad():
curves.append((loss_fn(model(X_tr), y_tr).item(), loss_fn(model(X_val), y_val).item()))
return model, curves
runs = {"no regularizer": train(), "dropout p=0.5": train(p_drop=0.5), "weight decay 5": train(decay=5.0)}
for name, (model, curves) in runs.items():
with torch.no_grad():
acc = (model(X_val).argmax(1) == y_val).float().mean().item()
best = min(range(50), key=lambda e: curves[e][1])
print(f"{name:15s} epoch 50: train {curves[-1][0]:.3f} val {curves[-1][1]:.3f} acc {acc:.3f}"
f" | lowest val {curves[best][1]:.3f} at epoch {best + 1}")
no regularizer epoch 50: train 0.007 val 0.999 acc 0.791 | lowest val 0.571 at epoch 11
dropout p=0.5 epoch 50: train 0.115 val 0.725 acc 0.780 | lowest val 0.548 at epoch 15
weight decay 5 epoch 50: train 0.245 val 0.563 acc 0.794 | lowest val 0.560 at epoch 15
Without a regularizer, the gap between training and validation loss reaches 0.99 by epoch 50. Dropout cuts it to 0.61 and weight decay to 0.32. Weight decay's validation loss stays roughly flat from epoch 10 on, around 0.6 (it happens to end on a dip, 0.563). Accuracy barely moves: 0.791 with no regularizer, 0.780 with dropout, 0.794 with weight decay. The fixes mostly stop the network from growing sure of its wrong answers, which is what a rising validation loss measures. Early stopping would have kept the unregularized model from epoch 11, at a validation loss of 0.571, almost as low as weight decay's best (0.560).
# script_id: day_036_dropout_and_weight_decay/regularize
import matplotlib.pyplot as plt
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, axes = plt.subplots(1, 3, figsize=(6, 4), sharey=True)
epochs = range(1, 51)
for ax, (name, (_, curves)) in zip(axes, runs.items()):
ax.plot(epochs, [c[0] for c in curves], color="#2a78d6", lw=2, label="train")
ax.plot(epochs, [c[1] for c in curves], color="#eb6834", lw=2, label="validation")
ax.set(title=name, xlabel="epoch")
ax.grid(alpha=0.3)
axes[0].set_ylabel("cross-entropy loss")
axes[0].legend()
fig.suptitle("Dropout slows the climb in validation loss; weight decay holds it flat")
fig.tight_layout()
fig.savefig(FIG_DIR / "regularized_curves.png", dpi=120)
plt.close(fig)

Quick check
Quick check
1. With dropout p = 0.2, a kept unit outputs 3.0 before scaling. What does the next layer see during training?
2. You score a dropout network on validation data but forget model.eval(). What happens?
3. Training loss is 0.01 and validation loss keeps rising. Which change makes sense?
Next
D37: Convolutional Networks and an Image Classifier builds a network made for images, and adds augmentation, another way to stop memorizing.
Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.