Overfitting means a model memorises the training data, including its noise, and performs poorly on new data. Underfitting means the model is too simple to capture the pattern. The bias–variance trade-off explains both.
What You Will Learn
- Recognise overfitting and underfitting from train vs test scores
- See them with polynomial regression
- See them with decision-tree depth
- Bias and variance explained
- Fixes for each problem
Prerequisites
Polynomial Regression Example
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 1, 40))
y = np.sin(2 * np.pi * x) + rng.normal(0, 0.2, 40) # true curve + noise
X_tr, X_te, y_tr, y_te = train_test_split(x.reshape(-1, 1), y, test_size=0.3, random_state=1)
for d in [1, 4, 15]:
m = make_pipeline(PolynomialFeatures(d), LinearRegression()).fit(X_tr, y_tr)
print(d, round(mean_squared_error(y_tr, m.predict(X_tr)), 3),
round(mean_squared_error(y_te, m.predict(X_te)), 3))
1 0.289 0.365 4 0.033 0.064 15 0.027 0.128
| Degree | Train MSE | Test MSE | Diagnosis |
|---|---|---|---|
| 1 (straight line) | 0.289 | 0.365 | Underfitting – both errors high |
| 4 | 0.033 | 0.064 | Good fit |
| 15 | 0.027 | 0.128 | Overfitting – lowest train error, test error doubles |
Explanation: As the model becomes more flexible, training error always falls. Test error first falls, then rises once the model starts fitting noise. The best model is the one with the lowest test (or validation) error.
Decision-Tree Depth
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
for d in [1, 3, None]:
t = DecisionTreeClassifier(max_depth=d, random_state=0).fit(X_tr, y_tr)
print(d, round(t.score(X_tr, y_tr), 3), round(t.score(X_te, y_te), 3))
1 0.923 0.923 3 0.977 0.944 None 1.0 0.937
Explanation: An unlimited tree reaches 100% training accuracy – a classic sign of memorisation – but scores lower on the test set than a depth-3 tree.
Bias and Variance
| High bias | High variance | |
|---|---|---|
| Meaning | Wrong assumptions; model too simple | Too sensitive to the particular training sample |
| Symptom | Poor train and test scores | Great train score, much worse test score |
| Problem | Underfitting | Overfitting |
| Example | Straight line for a curve | Degree-15 polynomial, unpruned tree |
Expected test error ≈ bias² + variance + irreducible noise. Making a model more complex lowers bias but raises variance; the goal is the sweet spot in between.
How to Fix
| Overfitting (high variance) | Underfitting (high bias) |
|---|---|
| Get more training data | Use a more flexible model |
| Simplify: fewer features, lower depth or degree | Add better features – feature engineering |
| Regularization (Ridge, Lasso, dropout) | Reduce regularization |
| Ensembles like random forest (bagging) | Train longer (neural networks) |
| Early stopping, data augmentation | Use boosting – ensembles |
sklearn.model_selection.learning_curve) to diagnose reliably instead of a single split.Series
ML fundamentals series: What is ML · Types of ML · Train/Test Split · Overfitting & Bias-Variance · Regularization · Confusion Matrix · ROC & AUC · Cross-Validation · Ensembles · DBSCAN
Interview Questions
Q: How do you detect overfitting?
A large gap between training and validation/test performance.
Q: Explain the bias–variance trade-off.
Simple models have high bias, complex models high variance; total error is minimised at a balance between them.
Q: Name three ways to reduce overfitting.
More data, regularization, simpler model, cross-validated early stopping, ensembling (bagging).
Practice Exercises
- Try degrees 2–10 in the polynomial example and find the best test MSE.
- Plot train and test accuracy of the tree for max_depth 1–15.
Summary
Underfitting: both scores poor (high bias). Overfitting: train great, test poor (high variance). Tune complexity with validation data, regularization and more data.
Machine Learning Tutorials, Courses and Certifications