Sub topic 12
Overfitting and underfitting
This chapter assumes you can train a scikit-learn model, split data into training and test sets, and read a cross-validation score. It covers how to tell whether a model is too simple, too flexible, or about right, and what to change in each case.
The two failure modes
A model learns patterns from training rows and is then used on rows it has never seen. Two things can go wrong.
- Underfitting: the model is too simple to capture the real pattern. It scores poorly on the training data and poorly on new data. The error is high bias.
- Overfitting: the model is flexible enough to memorize noise and quirks of the training rows. It scores very well on training data and noticeably worse on new data. The error is high variance.
A well-fitted model scores similarly on both, and that score is as good as the problem allows.
| Symptom | Training score | Validation score | Likely cause |
|---|---|---|---|
| Underfitting | Low | Low, close to training | Model too simple, weak features, too much regularization |
| Overfitting | High | Much lower than training | Model too flexible, too few rows, too many features |
| Good fit | High | Close to training | Complexity matches the data |
"Low" and "high" are relative. Compare against the baseline from the previous chapter and against what a domain expert would consider achievable. A training accuracy of 0.80 is low if a simple rule reaches 0.95.
Reading the gap
The diagnostic is the pair of numbers: training score and validation score, computed with the same metric. Never judge from the training score alone, because it only tells you how well the model remembers.
Use the validation folds from cross-validation, or a separate validation set. Do not use the test set for this. If you tune the model by looking at test results, the test set stops being an honest estimate. The final chapter on test evaluation returns to this.
Seeing it with a validation curve
A validation curve varies one complexity setting and plots training and validation scores for each value. A decision tree is a clear example, because max_depth directly controls flexibility.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, validation_curve
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
depths = np.arange(1, 16)
train_scores, val_scores = validation_curve(
DecisionTreeClassifier(random_state=42),
X_train,
y_train,
param_name="max_depth",
param_range=depths,
cv=5,
scoring="f1",
)
for d, tr, va in zip(depths, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"depth={d:2d} train F1={tr:.3f} validation F1={va:.3f}")Typical output has three phases:
- At depth 1 or 2, both scores are modest. The tree cannot express the pattern, so this is underfitting.
- At moderate depths, the validation score peaks and stays close to the training score.
- At large depths, the training F1 reaches 1.000 because the tree memorizes every row, while the validation F1 stays flat or drops slightly. The widening gap is overfitting.
Pick the depth near the validation peak, not the depth with the best training score. When several depths score almost the same, prefer the simpler one.
Learning curves
A validation curve varies complexity. A learning curve varies the amount of training data and shows whether more data would help.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import learning_curve
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
sizes, train_scores, val_scores = learning_curve(
model, X, y, train_sizes=np.linspace(0.1, 1.0, 5), cv=5, scoring="f1"
)
for n, tr, va in zip(sizes, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"n={n:3d} train F1={tr:.3f} validation F1={va:.3f}")How to read the result:
- Both curves are low and close together. Adding rows will not help. The model or features are the limit, so this is underfitting.
- A large gap that narrows as data grows. The model is overfitting, and more data should help.
- Both curves are high and converge. The model is fine. Further gains need better features or a different problem framing.
The pipeline matters here. learning_curve refits the scaler on each training subset, so the validation folds stay clean, as discussed in the leakage chapter.
Fixing underfitting
Try these in order of cost:
- Check the features. A model cannot use information it does not receive. Add informative columns or interactions.
- Use a more flexible model, such as a deeper tree, a gradient boosted ensemble, or polynomial features.
- Reduce regularization. In
LogisticRegression, a largerCmeans weaker regularization. - Train longer, for models trained iteratively, and confirm that the optimizer has converged. A
ConvergenceWarningcan look like underfitting.
Fixing overfitting
- Get more data, if the learning curve says it helps.
- Simplify the model: limit
max_depth, raisemin_samples_leaf, or use fewer parameters. - Add regularization. A smaller
Cin logistic regression penalizes large coefficients. - Remove noisy or redundant features.
- Use ensembles that reduce variance, such as random forests, which average many trees.
- Stop training early for iterative learners, when validation performance stops improving.
Change one thing at a time and re-measure with cross-validation. Several changes at once make it impossible to know which one helped.
Common errors
- Diagnosing with the training score. A high training score proves nothing about new data.
- Tuning against the test set. Repeated peeking turns the test score into a validation score. The result is overfitting to the test set, which is hard to notice.
- Overfitting through the validation set. Trying hundreds of settings and keeping the best one also inflates the validation score a little. This is one reason to hold out an untouched test set.
- Mistaking leakage for a good fit. A validation score that is suspiciously high, with a tiny gap, can come from leaked information rather than a good model. Check that preprocessing happens inside the pipeline.
- Ignoring noise in the estimate. With small data, the standard deviation across folds may be larger than the difference between two settings. Look at
scores.std()before declaring a winner. - Using the wrong metric. A gap measured with accuracy on imbalanced data can hide a model that ignores the minority class.
Regularization as a dial
Regularization adds a penalty for complexity to the training objective. It does not remove overfitting, it trades variance for bias. Turn the dial too far and the model underfits. This is why regularization strength is a hyperparameter to tune with cross-validation, covered in the tuning chapter.
Exercise
A random forest gets a training F1 of 0.99 and a cross-validated F1 of 0.82. A logistic regression on the same data gets 0.81 training and 0.80 validation. Which model overfits, and which would you pick as a starting point for improvement?
Show answer
The random forest overfits, because its gap is 0.17. The logistic regression has a gap of 0.01, so it is not overfitting and may be slightly underfitting. The random forest still has the higher validation score (0.82 against 0.80), so it is the better predictor so far. A sensible next step is to regularize it, for example by limiting depth or raising minsamplesleaf, and see whether the validation score rises. Also check the fold standard deviation, because 0.02 may be within noise.
Exercise
A learning curve shows training F1 of 0.70 and validation F1 of 0.68, and both stay flat as you add more rows. What does this indicate, and what should you try?
Show answer
Both scores are low and close together, and more data does not move them. This is underfitting from limited model capacity or weak features. Try better features, a more flexible model, or weaker regularization. Collecting more rows of the same kind will not help.