30 Mins

4. Regularization & Overfitting Prevention

Diagnosing Overfitting and Weight Decay

Overfitting manifests when a model achieves high performance on training data but fails to generalize to unseen validation data. Visually, this is diagnosed by a divergence in loss curves where training loss continues to decrease while validation loss begins to rise. This indicates the model is memorizing noise rather than learning representative features.

L1 and L2 regularization, often termed Weight Decay in optimizer configurations, combat this by adding a penalty term to the loss function. L2 regularization, or Weight Decay, adds the sum of squared weights to the loss, effectively pushing parameters toward zero and constraining model complexity, which promotes smoother decision boundaries.

Operator Note: Always monitor both training and validation loss simultaneously. If training loss plateaus while validation loss fluctuates, consider increasing your regularization strength or reducing model capacity.
Python 3
import torch
import torch.nn as nn
import torch.optim as optim

# Defining a model with weight decay in the optimizer
model = nn.Linear(10, 1)
# L2 penalty applied via weight_decay parameter
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)

# Mock training step
data = torch.randn(1, 10)
target = torch.tensor([[1.0]])
optimizer.zero_grad()
output = model(data)
loss = nn.MSELoss()(output, target)
loss.backward()
optimizer.step()

Dropout: Breaking Co-adaptation

Dropout is a stochastic regularization technique where individual neurons are randomly 'dropped' (set to zero) during each training forward pass. This prevents units from relying on the presence of other specific neurons, thereby reducing complex co-adaptation and forcing the network to learn more robust, redundant feature representations.

During inference, dropout is typically disabled, and the layer output is scaled by the dropout probability to account for the expected activation magnitude during training. This ensures that the neurons operate at an appropriate scale in the production environment.

Operator Note: Dropout is most effective in fully connected layers with high parameter counts. Be cautious when applying it to small layers, as it can cause underfitting.
Python 3
import torch.nn as nn

# Implementing Dropout layer with 50% probability
# This forces the network to avoid relying on specific feature paths
layer = nn.Sequential(
    nn.Linear(128, 64),
    nn.ReLU(),
    nn.Dropout(p=0.5),
    nn.Linear(64, 10)
)

# During evaluation, ensure model is set to eval() to disable Dropout
layer.eval()

Early Stopping Mechanisms

Early stopping is a practical heuristic that halts training when performance on a held-out validation set ceases to improve. By defining a 'patience' threshold—the number of epochs to wait for an improvement before terminating—we prevent the model from entering the overtraining regime where it begins to overfit the training distribution.

To implement this correctly, one must save the model state whenever a new 'best' validation loss is achieved. This ensures that even if training continues for a few epochs past the point of optimality due to patience, the final checkpoint retrieved is the one with the best generalization characteristics.

Operator Note: Combine early stopping with a learning rate scheduler to allow the model to fine-tune its weights as it approaches the global or local minimum.
Python 3
class EarlyStopping:
    def __init__(self, patience=5):
        self.patience = patience
        self.best_loss = float('inf')
        self.counter = 0

    def __call__(self, val_loss):
        if val_loss < self.best_loss:
            self.best_loss = val_loss
            self.counter = 0
        else:
            self.counter += 1
        return self.counter >= self.patience

Knowledge Check

Ready to test your understanding of 4. Regularization & Overfitting Prevention?

Back