Overfitting
Overfitting
A phenomenon in which a model fits the training data too closely, reducing its ability to generalize to new data.
Overfitting
A phenomenon in which a model fits the training data too closely, reducing its ability to generalize to new data.
Overfitting is a phenomenon in which a machine learning model memorizes even the noise and fine-grained patterns of the training data, so its predictive performance on new data declines. It shows nearly perfect performance on the training data, but its performance drops significantly on test data or in a real service. This is because the model has learned the particular characteristics of the training data rather than the general patterns of the data.
The main causes of overfitting are cases where model complexity is high relative to the amount of data, training runs for too long, or the training data is biased. For example, if a deep learning model with millions of parameters is trained on 100 data points, the model ends up memorizing all of the data. Also, if the number of training epochs keeps increasing without validation, a point comes where the training loss decreases but the validation loss instead increases.
Representative techniques for preventing overfitting include Regularization, Dropout, Early Stopping, and Data Augmentation. L1/L2 regularization limits model complexity by imposing a penalty on the size of the weights. Dropout randomly deactivates neurons during training to reduce dependence on specific neurons. Early stopping halts training when the validation loss no longer improves. Data augmentation artificially increases the training data through image rotation, cropping, and so on.
The concept opposite to overfitting is Underfitting. Underfitting is a state in which the model is too simple or insufficiently trained, so it fails to capture even the patterns of the training data. A good model finds the optimal point between overfitting and underfitting and balances the Bias-Variance Tradeoff. To do this, cross-validation, hyperparameter tuning, ensemble techniques, and the like are used.
This is an example of preventing overfitting in PyTorch using dropout and early stopping.
# pip install torch scikit-learn matplotlib
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# 데이터 생성 (일부러 작은 데이터셋)
X, y = make_classification(n_samples=200, n_features=20, n_informative=10,
n_redundant=5, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42)
# 텐서 변환
X_train = torch.FloatTensor(X_train)
y_train = torch.FloatTensor(y_train).unsqueeze(1)
X_val = torch.FloatTensor(X_val)
y_val = torch.FloatTensor(y_val).unsqueeze(1)
# 과적합 방지를 위한 모델 (드롭아웃 적용)
class RegularizedModel(nn.Module):
def __init__(self, dropout_rate=0.5):
super().__init__()
self.fc1 = nn.Linear(20, 128)
self.dropout1 = nn.Dropout(dropout_rate)
self.fc2 = nn.Linear(128, 64)
self.dropout2 = nn.Dropout(dropout_rate)
self.fc3 = nn.Linear(64, 1)
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.dropout1(x)
x = self.relu(self.fc2(x))
x = self.dropout2(x)
x = self.sigmoid(self.fc3(x))
return x
# 조기 종료 클래스
class EarlyStopping:
def __init__(self, patience=10, min_delta=0.001):
self.patience = patience
self.min_delta = min_delta
self.counter = 0
self.best_loss = float('inf')
self.early_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.early_stop = True
# 모델 학습
model = RegularizedModel(dropout_rate=0.5)
criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-4) # L2 정규화
early_stopping = EarlyStopping(patience=15)
train_losses, val_losses = [], []
for epoch in range(500):
# 학습
model.train()
optimizer.zero_grad()
outputs = model(X_train)
train_loss = criterion(outputs, y_train)
train_loss.backward()
optimizer.step()
# 검증
model.eval()
with torch.no_grad():
val_outputs = model(X_val)
val_loss = criterion(val_outputs, y_val)
train_losses.append(train_loss.item())
val_losses.append(val_loss.item())
# 조기 종료 체크
early_stopping(val_loss.item())
if early_stopping.early_stop:
print(f"조기 종료! Epoch: {epoch+1}")
break
if (epoch + 1) % 50 == 0:
print(f"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}")
# 학습 곡선 시각화
plt.figure(figsize=(10, 5))
plt.plot(train_losses, label='Train Loss')
plt.plot(val_losses, label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Training vs Validation Loss (Overfitting Prevention)')
plt.savefig('learning_curve.png')
print("학습 곡선 저장: learning_curve.png")