Lesson 07 · 40 minutes
Spot overfitting with a decision tree
- Show the gap between a training score and a test score
- Limit a model to reduce memorising
- Use a validation set to choose a setting without touching the test set
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A team trained a model on its own incident tickets. In the lab it scores 0.99. In the first week of use it scores 0.70, and a tester also got it to repeat a customer name that was only in the tickets. Your lead asks you to find out whether the model memorised its data, and how to pick its size without cheating. You will see the effect on a decision tree, which you can read, then repeat the test on data with noisy labels.
Recall
In lesson 3, the training accuracy was 1.0 and the test accuracy was 0.96. Which number do you report, and why?
The test accuracy. The model has seen the training data, so a score on it says little about new data.
In lesson 6, what does a low recall for one class tell you that the overall accuracy hides?
The model misses many real examples of that class. The overall accuracy is an average and is dominated by the larger classes.
The idea
A decision tree asks a chain of yes/no questions about the features ("is pixel 21 above 7?") and ends in a label. The depth is the number of questions in one chain. With no limit on depth, a tree keeps asking until each training example has its own leaf (an end of a chain, with a label). It then scores 100 percent on training data, because it memorised it.
| Word | Meaning |
|---|---|
| Overfitting | The model fits the training data, including its noise, and does worse on new data. |
| Underfitting | The model is too simple to learn the pattern: poor on both parts. |
| Generalise | Work well on data the model has not seen. This is the goal. |
| Validation set | A third part of the data, used to choose settings. The test set stays closed. |
The sign of overfitting is a gap: a high training score and a much lower test score.
Worked example
1. See the gap
Go to the lab folder and activate the environment. Create overfit.py. It trains trees of different depths on the digits data. DecisionTreeClassifier is the tree model. Its setting max_depth limits the depth, and None means no limit. After training, get_n_leaves() counts the leaves. In the print line, {x:>4} pads a value to four characters, and str(depth) turns None into text so that it can be padded.
overfit.py
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
for depth in (None, 12, 8, 5, 3, 2):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
print(f"max_depth={str(depth):>4} leaves={tree.get_n_leaves():>3} "
f"train={tree.score(X_train, y_train):.3f} test={tree.score(X_test, y_test):.3f}")cd ~/krlab/how-ai-works
source .venv/bin/activate
python overfit.pymax_depth=None leaves=133 train=1.000 test=0.820
max_depth= 12 leaves=129 train=0.997 test=0.820
max_depth= 8 leaves= 78 train=0.944 test=0.822
max_depth= 5 leaves= 28 train=0.710 test=0.664
max_depth= 3 leaves= 8 train=0.493 test=0.476
max_depth= 2 leaves= 4 train=0.323 test=0.307The free tree has a gap of 0.18. Depth 8 narrows the gap to 0.12 but the test score is the same. On clean data, limiting the tree does not help here. Depths 5, 3 and 2 underfit: both scores fall. Compare with lesson 3: a logistic regression reached 0.962 on the same split, so this model type is weaker on this data.
2. Add noise to the labels
Real labels are never perfect. Change overfit.py: after the split, replace 20 percent of the training labels with random digits, and train on those. A random digit is sometimes the right one, so only about 17 percent of the labels end up wrong. The test labels stay correct. Save the new file as overfit_noisy.py. A random generator, np.random.default_rng(0), makes random numbers that repeat for the same seed. rng.choice(n, size=k, replace=False) picks k different positions out of n. rng.integers(0, 10, k) makes k random whole numbers from 0 to 9.
overfit_noisy.py
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
rng = np.random.default_rng(0)
noisy = y_train.copy()
flip = rng.choice(len(noisy), size=int(0.2 * len(noisy)), replace=False)
noisy[flip] = rng.integers(0, 10, len(flip))
for depth in (None, 12, 8, 6, 4):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, noisy)
print(f"max_depth={str(depth):>4} train={tree.score(X_train, noisy):.3f} test={tree.score(X_test, y_test):.3f}")python overfit_noisy.pymax_depth=None train=1.000 test=0.667
max_depth= 12 train=0.938 test=0.700
max_depth= 8 train=0.817 test=0.762
max_depth= 6 train=0.690 test=0.733
max_depth= 4 train=0.502 test=0.562Now the free tree scores less than the trees of depth 12, 8 and 6. It memorised the wrong labels: its training score is a perfect 1.000 on data that is partly false. Depth 8 gives 0.762 on the test set, nearly 10 points better. Limiting the model made it ignore noise.
3. Choose the depth with a validation set
You cannot pick depth 8 by looking at the test scores: that uses the test set to decide. Instead, cut a validation set out of the training part. The program below calls train_test_split a second time on the training part. It scores each depth on the validation part, keeps the best one, trains the final tree on all the non-test data, and touches the test set once, at the end. Create validate.py.
validate.py
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_digits(return_X_y=True)
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
rng = np.random.default_rng(0)
noisy = y_rest.copy()
flip = rng.choice(len(noisy), size=int(0.2 * len(noisy)), replace=False)
noisy[flip] = rng.integers(0, 10, len(flip))
X_train, X_val, y_train, y_val = train_test_split(
X_rest, noisy, test_size=0.25, random_state=42
)
best_depth, best_score = None, 0
for depth in (3, 5, 6, 8, 10, 12, None):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
score = tree.score(X_val, y_val)
print("depth", depth, "validation", round(score, 3))
if score > best_score:
best_depth, best_score = depth, score
final = DecisionTreeClassifier(max_depth=best_depth, random_state=0).fit(X_rest, noisy)
print("chosen depth:", best_depth)
print("test, used once:", round(final.score(X_test, y_test), 3))python validate.pydepth 3 validation 0.323
depth 5 validation 0.54
depth 6 validation 0.602
depth 8 validation 0.602
depth 10 validation 0.585
depth 12 validation 0.57
depth None validation 0.54
chosen depth: 6
test, used once: 0.733The validation scores rise, peak at depths 6 and 8, and fall again: the shape of overfitting. They are lower than the test score because the validation labels carry the same noise (about 17 percent wrong labels); the test labels are true. The program keeps the first best depth, 6. The final model trains on all the non-test data and the test set gives one honest number, 0.733. Depth 8 scored 0.762 on the test set in step 2, but you could only know that by looking at the test set. The validation choice is not always the best one. It is the honest one.
Your turn
Repeat the noise test on a new split and with more noise. There is no code here: adapt overfit_noisy.py.
- Split the digits with
test_size=0.3,random_state=7andstratify=y. - Make the noise as in step 2 of the worked example, but with
np.random.default_rng(1)and 30 percent of the training labels. - Train trees with
max_depthset toNone, 10, 8, 6 and 4 (random_state=0) on the noisy labels. Score each on the training labels that it saw (the noisy ones) and on the test part with its true labels.
The task chose 30 percent of the labels, but fewer labels differ. Write one sentence that says why. Then say which depth you would choose in real work, and which data you would use to choose it.
Check yourself
A model scores 0.99 on training data and 0.70 on test data. What is the problem and what do you try?
Overfitting: the model memorised the training data. Try a simpler model, a limit on its size, more data or cleaner labels. Then measure the gap again.
Why can a depth chosen from test scores give a score that is too good?
Among many settings, the best one on the test set is partly luck. Choosing it uses the test set to make a decision, so the final score is no longer an honest estimate. A validation set takes that job.
In step 2 the free tree has a training score of 1.000. What does it say about the quality of the training labels?
Nothing good. About seventeen percent of the labels are false (twenty percent were replaced, and one random digit in ten is right by chance), so a perfect fit means that the tree learned the false labels too. A perfect training score is a warning, not a proof.
What does "generalise" mean?
To work well on new data that comes from the same kind of source as the training data. It is the goal of every model. A test score measures it.
Field notes
- A model that memorises can leak its training data. Attacks called membership inference and training-data extraction use the fact that models are more sure on data they have seen. Overfitting is a privacy risk, not only a quality risk.
- With little data, one validation split is noisy. Use cross-validation: scikit-learn's
cross_val_scorerepeats the split several times and averages. - Put the whole preparation of the data (scalers, text vectors) inside the training step, so that validation data never influences it. A
Pipelinedoes this; lesson 12 uses one. - Underfitting and overfitting are two ends of one dial. Plot the training and validation score against the model size and pick the point where validation is highest.
- Data drift is overfitting to the past. A detector that generalised in March can fail in June when attackers change. Watch the score on fresh, labelled data after deployment.