Model Optimization · Beginner
Understanding Overfitting in Machine Learning
Learn how to recognize overfitting using training and validation error and choose appropriate remedies.
Applied Machine Learning ·
What is overfitting?
Overfitting occurs when a model learns patterns specific to its training data that do not generalize to unseen examples. Low training error alone is not evidence of good generalization.
A reproducible example
The following example compares training and validation accuracy for decision trees with different maximum depths. Install scikit-learn before running it.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
for depth in [2, 5, 10, None]:
model = DecisionTreeClassifier(max_depth=depth, random_state=42)
model.fit(X_train, y_train)
print(depth, model.score(X_train, y_train), model.score(X_val, y_val))
Compare the two scores rather than assuming that the deepest tree is best. The exact pattern depends on the dataset. A widening gap is a warning sign, not a definitive diagnosis.
How to reduce overfitting
Consider limiting model complexity, collecting more representative data, applying regularization, or using cross-validation. Keep a separate test set for final evaluation after selecting hyperparameters.
For grouped observations, split by group rather than randomly splitting related samples across training and validation sets.