A set of techniques used to prevent a machine learning model from overfitting to its training data by adding a penalty for complexity, forcing it to learn broader, more generalizable patterns.
A rule that stops a student from just memorizing the exact answers to the practice test. Instead, regularization forces the student to actually understand the underlying concepts so they can pass a completely new, unseen final exam.
When a model is too complex, it memorizes the noise and specific quirks of the training data (overfitting). Regularization introduces a constraint.
Packing for a trip. Without regularization, you pack every single item you own “just in case” (overfitting, heavy, inefficient). Regularization is the rule that you can only bring one carry-on, forcing you to pack only the versatile, essential items (generalization).
# Conceptual: L2 Regularization (Weight Decay) in PyTorch
import torch.nn as nn
# The weight_decay parameter applies L2 regularization to the weights
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-4)
# Conceptual: Dropout in a neural network
class MyNetwork(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(100, 50)
self.dropout = nn.Dropout(p=0.5) # Randomly zeros 50% of inputs during training
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.dropout(x) # Applied during training, automatically disabled during eval
return x