Sub topic 2
Overfitting: when training scores mislead
This chapter assumes you can read basic Python and NumPy, know that a supervised model learns a mapping from features to labels, and have seen scikit-learn's fit and predict pattern. Earlier, you saw that we hold data out to estimate performance on new data. Here you will see what goes wrong when we don't, and how to recognize it.
The problem in one sentence
A model's score on the data it was trained on tells you how well it memorized that data. It does not tell you how well it will handle new data.
Training means choosing parameters that minimize error on the training rows. A flexible enough model can drive that error to nearly zero by fitting everything in the training set, including accidents. Those accidents will not repeat in new data, so the model's predictions there get worse.
Signal, noise, and what a model can fit
Every real dataset mixes two things:
- Signal is the pattern that holds across the whole population, such as "larger tumors are more often malignant."
- Noise is variation that does not repeat. Sources include measurement error, mislabeled rows, and unrecorded factors that affected one particular sample.
A model cannot tell the two apart. It sees only training rows and tries to reduce error on them. If it has enough freedom, it will also fit the noise in those rows. That is overfitting: the model's training performance is better than its performance on new data because it learned noise specific to the training sample.
Underfitting is the opposite failure. The model is too simple to capture the signal, so it performs poorly on training data and on new data alike. A straight line fitted to a curved relationship is the usual example.
The generalization gap is the difference between training performance and performance on unseen data. A large gap with a strong training score signals overfitting. A weak score on both signals underfitting.
Complexity and the two error curves
Model complexity is how much freedom a model has to bend to the data. It is set by things such as polynomial degree, tree depth, the number of neural network weights, or the strength of regularization. Regularization is a penalty that discourages extreme parameter values.
As complexity grows, training error almost always falls. Error on unseen data usually falls at first, then rises once the model starts fitting noise. The diagram shows this shape. The numbers are illustrative, not measured.
The left side of the chart is underfitting: both errors are high. The right side is overfitting: training error is tiny but the other error is large. The best model sits near the minimum of the unseen-data curve, not at the point where training error is lowest.
Seeing it with a regression curve
The following example fits polynomials of three degrees to 30 noisy points from a sine curve. It then scores each fit on 200 fresh points from the same process.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0)
def make_data(n):
x = rng.uniform(-3, 3, size=(n, 1))
y = np.sin(x).ravel() + rng.normal(scale=0.3, size=n)
return x, y
x_train, y_train = make_data(30)
x_new, y_new = make_data(200)
for degree in [1, 4, 15]:
model = make_pipeline(
PolynomialFeatures(degree, include_bias=False),
StandardScaler(),
LinearRegression(),
)
model.fit(x_train, y_train)
train_mse = mean_squared_error(y_train, model.predict(x_train))
new_mse = mean_squared_error(y_new, model.predict(x_new))
print(f"degree={degree:2d} train MSE={train_mse:.3f} new-data MSE={new_mse:.3f}")Mean squared error (MSE) is the average of the squared differences between predictions and true values. Lower is better.
What to expect when you run it:
- Training MSE falls as the degree rises. Each higher-degree model contains the lower-degree ones, so least squares can only do as well or better on the data it was fitted to.
- Degree 1 is a straight line, so it underfits. Both errors are high and close together.
- Degree 4 is flexible enough to follow the sine shape. Both errors are low and close to the noise floor, about 0.09 (the noise standard deviation of 0.3, squared).
- Degree 15 has far more freedom than 30 points justify. Its training MSE is the lowest of the three, but its new-data MSE is typically much higher than degree 4's, especially near the edges of the range.
Exact values depend on the random draw. The ordering of training errors is guaranteed. The ordering of new-data errors is typical, not guaranteed.
Seeing it with a classifier
Tree depth plays the same role as polynomial degree. A decision tree that is allowed to grow until every training row is classified correctly will memorize the training set.
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
)
for depth in [1, 2, 3, 5, 10, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=42)
tree.fit(X_train, y_train)
print(
f"max_depth={str(depth):>4} "
f"train acc={tree.score(X_train, y_train):.3f} "
f"test acc={tree.score(X_test, y_test):.3f}"
)With max_depth=None the tree usually reaches 1.000 training accuracy, since it keeps splitting until each leaf is pure. Test accuracy is lower, and it often does not improve beyond a modest depth. The split itself is covered in the next chapter. For now, treat X_test as rows the model never saw while fitting.
A training accuracy of 1.000 is a warning on real, noisy data. It usually means the model has capacity to spare.
Reading the gap
You diagnose a model by comparing two numbers: its score on training data and its score on data held out from training.
| Training score | Held-out score | Likely diagnosis | Typical responses |
|---|---|---|---|
| Poor | Poor | Underfitting (high bias) | Add features, use a more flexible model, reduce regularization |
| Good | Much worse | Overfitting (high variance) | Get more data, simplify the model, add regularization, remove noisy features |
| Good | Close to training | Fits well | Check that the score is good enough for the task |
| Poor | Better than training | Suspicious | Check for leakage, a mismatched split, or a tiny held-out set |
Bias and variance are the usual names for the two failures. High bias means the model's assumptions are too rigid, so it is consistently wrong. High variance means the fitted model would change a lot if you trained it on a different sample from the same population.
"Much worse" has no universal threshold. A gap of two points may be fine for one task and alarming for another. Judge it against the noise in your held-out estimate, which is large when the held-out set is small.
What causes overfitting
Several factors raise the risk, and they combine:
- Too little data for the model's capacity. Fifteen polynomial terms on 30 points is an extreme case. The more parameters per training row, the easier it is to memorize.
- Too many features. With many irrelevant columns, some will correlate with the label by chance in a small sample. The model uses them anyway.
- Noisy labels. If some labels are wrong, a model that fits them perfectly has learned the errors.
- Training for too long. Iterative learners such as gradient boosting and neural networks keep reducing training loss after they stop improving on new data.
- Repeated tuning against the same held-out data. This is a quieter form of the same problem. If you try hundreds of settings and keep the one that scores best on a particular set of rows, you have fitted your choices to that set. Later chapters on the validation set and test-set discipline address this directly.
Common errors
- Reporting the training score as the result. This is the central mistake the chapter is about. Report performance on data the model did not fit.
- Assuming a big gap always means "use a simpler model." More data or stronger regularization may fix it while keeping the model's capacity. Check the learning curve if you can: if held-out error is still falling as you add training rows, more data helps.
- Assuming a small gap means a good model. A model can underfit with a tiny gap. Both scores are just low.
- Judging from one small held-out set. With 30 test rows, one extra mistake moves accuracy by over three points. A gap that size may be noise.
- Treating a perfect held-out score as good news. On real problems it more often points to leakage than to a perfect model. Leakage gets its own chapter.
Quick checklist
Before trusting any score, ask:
- Was this number computed on rows the model never saw during fitting?
- How large is the held-out set, and how much could the score move by chance?
- How does the gap between training and held-out scores compare with what you expected?
- Did any choice, such as features, settings, or a threshold, depend on the held-out rows?
Exercise
A decision tree with no depth limit scores 1.00 accuracy on the training set and 0.91 on a held-out set. A second tree limited to depth 3 scores 0.95 on the training set and 0.93 on the same held-out set. Which model would you prefer, and what does the comparison say about the first tree?
Show answer
Prefer the depth-3 tree, since it has the higher held-out score (0.93 against 0.91) and a smaller gap (0.02 against 0.09). The unlimited tree has the higher training score only because it memorized the training rows, including their noise. That is overfitting. One caveat is that a 0.02 difference on a small held-out set may be within chance variation. If you plan to choose between the two trees, do it on a separate validation set or with cross-validation, as later chapters describe.