Sub topic 12
Overfitting and underfitting
This chapter assumes you can train a scikit-learn model, you know what a train/test split is, and you have seen cross-validation scores. It shows how to tell whether a model is too simple or too tailored to its training data.
Two ways to be wrong
A model underfits when it is too simple to capture the pattern in the data. It scores poorly on the training data and poorly on new data.
A model overfits when it memorizes details and noise specific to the training rows. It scores very well on the training data and noticeably worse on new data.
The goal is a model that generalizes, meaning it performs about as well on unseen rows as on the rows it learned from.
Reading the gap
Compare two numbers, both measured with the same metric: the training score and the cross-validation score computed on the training set only.
| Training score | Validation score | Likely diagnosis |
|---|---|---|
| Low | Low | Underfitting (high bias) |
| High | Much lower | Overfitting (high variance) |
| High | Close to training | Good fit |
A small gap is not enough on its own. If both scores are low, the model is underfitting even though the gap is small. Judge the absolute level against your baseline as well.
Seeing it in code
A decision tree is a good demonstration because its max_depth setting directly controls its flexibility. Depth 1 gives a single split, and None lets the tree grow until it fits every training row.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
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
)
for depth in [1, 3, None]:
model = DecisionTreeClassifier(max_depth=depth, random_state=42)
cv_score = cross_val_score(model, X_train, y_train, cv=5).mean()
train_score = model.fit(X_train, y_train).score(X_train, y_train)
print(f"max_depth={depth}: train={train_score:.3f}, cv={cv_score:.3f}")With max_depth=None, the training accuracy is 1.000 because the tree memorizes every row, while the cross-validation score is lower. That gap is the signature of overfitting. The shallow tree has train and CV scores that sit close together but at a lower level, which points toward underfitting. Exact numbers depend on your scikit-learn version.
The test set is not used here. Choosing a depth by looking at test scores would turn the test set into a validation set.
What to change
Common remedies:
- For underfitting: use a more flexible model, add informative features, or reduce regularization (for logistic regression, raise
C). - For overfitting: limit model complexity (such as
max_depth), increase regularization, remove noisy features, or collect more training data.
Hyperparameter tuning, covered later, is largely a systematic search along this complexity axis.
Exercise
A model has 0.99 accuracy on training data and 0.72 mean accuracy in 5-fold cross-validation on the same training data. A majority-class baseline scores 0.70. What is the problem, and name two fixes?
Show answer
The model is overfitting. The large gap between training and validation scores shows it memorizes the training rows, and its validation score barely beats the baseline. Possible fixes include limiting complexity (for example, a smaller max_depth), increasing regularization, removing noisy features, or collecting more training data.