πŸ€– AI/ML

Overfitting

Overfitting

Fitting the training data too closely. Fails to generalize to new data.

πŸ“– Detailed Explanation

Overfitting is a phenomenon in which a machine learning model fits the training data too closely, so its predictive performance on new data declines. It memorizes even the noise and chance patterns in the training data, which weakens its generalization ability.

The concept of overfitting originates from the Bias-Variance Tradeoff in statistics. As a model becomes more complex, it fits the training data well (low bias), but its predictions on new data become unstable (high variance). It came to the fore as a particularly important problem in neural network research in the 1990s.

Overfitting occurs when the training loss keeps decreasing while the validation loss increases. It mainly appears when the number of model parameters is excessively large relative to the amount of training data, or when training runs for too long. The opposite phenomenon, underfitting, is the case where the model is too simple to learn the patterns in the data.

In practice, preventing overfitting is key to model performance. Techniques such as Dropout, Early Stopping, data augmentation, and regularization (L1/L2) are widely used. You must separate the validation set from the test set to evaluate the model's generalization performance objectively.

πŸ’» Code Example

# 과적합 λ°©μ§€ 기법 예제 (PyTorch)
import torch
import torch.nn as nn
from torch.optim import Adam

# 과적합 λ°©μ§€ 기법이 적용된 λͺ¨λΈ
class RegularizedModel(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim, dropout_rate=0.5):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(dropout_rate),  # 1. Dropout: λ¬΄μž‘μœ„λ‘œ λ‰΄λŸ° λΉ„ν™œμ„±ν™”
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(dropout_rate),
            nn.Linear(hidden_dim, output_dim)
        )

    def forward(self, x):
        return self.layers(x)

model = RegularizedModel(10, 64, 1, dropout_rate=0.3)

# 2. L2 μ •κ·œν™” (Weight Decay)
optimizer = Adam(model.parameters(), lr=0.001, weight_decay=0.01)

# 3. Early Stopping κ΅¬ν˜„
class EarlyStopping:
    def __init__(self, patience=5, min_delta=0.001):
        self.patience = patience
        self.min_delta = min_delta
        self.counter = 0
        self.best_loss = float('inf')
        self.should_stop = False

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

early_stopping = EarlyStopping(patience=10)

# ν•™μŠ΅ λ£¨ν”„μ—μ„œ 과적합 λͺ¨λ‹ˆν„°λ§
for epoch in range(1000):
    # ν•™μŠ΅ 단계...
    train_loss = 0.1  # μ˜ˆμ‹œ
    val_loss = 0.15   # μ˜ˆμ‹œ - 검증 손싀

    # 검증 손싀이 μ¦κ°€ν•˜λ©΄ μ‘°κΈ° μ’…λ£Œ
    if early_stopping(val_loss):
        print(f"Early stopping at epoch {epoch}")
        break

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

πŸ’¬ In a Meeting
"Training accuracy is 98%, but test accuracy is 75%. It's a typical overfitting situation, so we plan to raise Dropout from 0.3 to 0.5 and add data augmentation."
πŸ’¬ In an Interview
"Overfitting is a phenomenon in which a model memorizes the training data and its generalization ability declines. From the bias-variance tradeoff perspective, it is a state of increased variance, and it is prevented with Dropout, Early Stopping, regularization, and so on."
πŸ’¬ In a Technical Discussion
"When training data is scarce, you should lower model complexity or use transfer learning. If the number of parameters is far greater than the number of training samples, the risk of overfitting is high."

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

⚠️ Common Mistakes & Cautions

❌
Hyperparameter tuning on the test set

If you use the test set for model selection, the model will overfit to the test set. Be sure to use a separate validation set.

❌
Ignoring learning curves

If you judge model performance by looking only at the training loss, you will miss overfitting. Be sure to monitor the training and validation losses together.

βœ…
The right way

Split the data three ways into Train/Validation/Test, and visualize the learning curves to identify the point at which overfitting begins. Use Early Stopping together with model checkpoints.

πŸ”— Related Terms

πŸ“š Learn More