Sub topic 2
Overfitting: when training scores mislead
This chapter assumes you can train a scikit-learn model and read an accuracy score. It also assumes you know that a supervised model learns a mapping from features to labels. The previous chapter explained why we hold data out. Here we look at what goes wrong when we don't.
What overfitting is
A model overfits when it learns details of its training data that don't carry over to new data. Those details include noise, accidental patterns, and even individual rows. The model's training score looks excellent, but its score on unseen data is much lower.
The opposite problem is underfitting. The model is too simple to capture the real pattern, so it scores poorly on both training and unseen data.
| Situation | Training score | Unseen-data score | Typical cause |
|---|---|---|---|
| Underfitting | Low | Low | Model too simple, too few features |
| Good fit | High | Close to training | Complexity matches the signal |
| Overfitting | Very high | Clearly lower | Model too flexible for the amount of data |
The generalization gap is the training score minus the unseen-data score. A large gap signals overfitting.
Seeing it happen
A decision tree is a convenient demonstration. Its max_depth setting controls how flexible it is. With no limit, the tree keeps splitting until it can classify nearly every training row correctly.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
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
)
print("depth train test")
for depth in [1, 2, 4, 8, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=42)
tree.fit(X_train, y_train)
train_acc = tree.score(X_train, y_train)
test_acc = tree.score(X_test, y_test)
print(f"{str(depth):>5} {train_acc:.3f} {test_acc:.3f}")Expect the training accuracy to climb toward 1.0 as depth grows. The test accuracy will rise at first and then flatten or fall. The exact numbers depend on your scikit-learn version, but the shape is consistent. The unlimited tree has memorized the training set, and its perfect training score tells you nothing about new patients.
The left side of the chart is underfitting. The middle is the best trade-off. The right side is overfitting, where the two lines separate.
Why training scores mislead
The training score measures how well the model reproduces answers it has already seen. It rewards memorization as much as understanding. A model with enough flexibility can reach a perfect training score on pure noise.
Overfitting becomes more likely in these situations:
- The dataset is small relative to the number of features.
- The model is highly flexible, such as a deep tree or a high-degree polynomial.
- Training runs for too long, as with a neural network.
- Many different models or settings are tried and only the best-looking one is kept.
Diagnosing and reducing it
Compare the training score with a held-out score. The pattern tells you what to do.
- Both low: the model underfits. Use a more flexible model or better features.
- Training high, held-out much lower: the model overfits. Simplify it, for example by limiting depth or adding regularization (a penalty on model complexity). Collecting more data also helps.
- Both high and close: the fit is reasonable.
Choosing settings such as max_depth by looking at the test score creates a subtler problem. The test set then influences your decisions and stops being an honest measure. The later chapters on validation sets and cross-validation show how to tune a model without this problem.
Exercise
A classifier scores 0.99 accuracy on its training data and 0.78 on held-out data. A second classifier scores 0.80 on training data and 0.79 on held-out data. Which one is overfitting, and which would you expect to generalize better?
Show answer
The first classifier is overfitting, since its generalization gap is 0.21. The second has a gap of 0.01, so its 0.79 held-out score is about what you should expect on new data. The first scores only slightly lower on held-out data (0.78), but the gap shows it has memorized training detail, and simplifying it may improve that score. Based on the held-out numbers alone, the two perform about equally, and the second is the more trustworthy.