Regularization
Regularization
Techniques to prevent overfitting. L1, L2, Dropout. Improves model generalization.
Regularization
Techniques to prevent overfitting. L1, L2, Dropout. Improves model generalization.
Regularization is a general term for techniques used to prevent a machine learning model from overfitting to its training data. By constraining model complexity, it improves generalization performance on new data, and there are various methods such as L1, L2, Dropout, and Early Stopping.
The concept of regularization originated in the bias-variance tradeoff of statistics and was developed in earnest in neural network research in the 1990s. With the emergence of Dropout in 2012, regularization became established as an essential technique in deep learning.
The core principle of regularization is "imposing a penalty on complex models." L1 (Lasso) adds the sum of the absolute values of the weights to the loss function, and L2 (Ridge) adds the sum of the squared weights. Dropout randomly deactivates neurons during training, and BatchNorm normalizes layer outputs. Each technique prevents overfitting through a different mechanism.
In practice, regularization is essential for all deep learning models. Typically, Dropout (0.1~0.5), Weight Decay (L2, 1e-4~1e-2), and BatchNorm are used in combination. Data augmentation is also regularization in a broad sense and is particularly effective in image classification.
Here is an example of applying various regularization techniques in PyTorch.
import torch
import torch.nn as nn
class RegularizedModel(nn.Module):
"""λ€μν μ κ·ν κΈ°λ²μ΄ μ μ©λ λͺ¨λΈ"""
def __init__(self, input_dim, hidden_dim, output_dim, dropout_rate=0.3):
super().__init__()
# λ μ΄μ΄ μ μ (BatchNorm ν¬ν¨)
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.bn1 = nn.BatchNorm1d(hidden_dim) # BatchNorm μ κ·ν
self.dropout = nn.Dropout(dropout_rate) # Dropout μ κ·ν
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.bn2 = nn.BatchNorm1d(hidden_dim)
self.fc3 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = self.dropout(torch.relu(self.bn1(self.fc1(x))))
x = self.dropout(torch.relu(self.bn2(self.fc2(x))))
return self.fc3(x)
# λͺ¨λΈ μ΄κΈ°ν
model = RegularizedModel(784, 256, 10, dropout_rate=0.3)
# L2 μ κ·ν (Weight Decay) - μ΅ν°λ§μ΄μ μμ μ€μ
optimizer = torch.optim.AdamW(
model.parameters(),
lr=1e-3,
weight_decay=1e-4 # L2 μ κ·ν κ°λ
)
# L1 μ κ·ν - μμ€ ν¨μμ μ§μ μΆκ°
def l1_regularization(model, lambda_l1=1e-5):
l1_penalty = sum(p.abs().sum() for p in model.parameters())
return lambda_l1 * l1_penalty
# νμ΅ λ£¨νμμ μ¬μ©
# loss = criterion(output, target) + l1_regularization(model)
print(f"λͺ¨λΈ νλΌλ―Έν° μ: {sum(p.numel() for p in model.parameters()):,}")
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free