πŸ€– AI/ML

Regularization

Regularization

Techniques to prevent overfitting. L1, L2, Dropout. Improves model generalization.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

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()):,}")

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"If the validation loss is higher than the training loss, it's overfitting. Let's raise Dropout from 0.3 to 0.5 and add Weight Decay as well."
πŸ’¬ In an Interview
"L1 regularization induces sparse weights, and L2 induces small weights. If you need feature selection, use L1; in general cases, use L2."
πŸ’¬ In a Technical Discussion
"Dropout gives an ensemble effect, and BatchNorm reduces internal covariate shift. Using the two together creates synergy."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Dropout enabled at test time: If you forget to call model.eval(), Dropout is also applied during testing. Always switch to evaluation mode.
❌
Excessive regularization: If regularization is too strong, underfitting occurs. Adjust it while monitoring the gap between the training loss and the validation loss.
βœ…
Gradual application: Add regularization in the order of base model β†’ Weight Decay β†’ Dropout β†’ Data Augmentation, and check the effect at each step.

πŸ”— Related Terms

πŸ“š Learn More