Learning the Pattern, Not the Examples
In the classifier lesson, the decision tree classified every training wine correctly but scored 0.889 on the test wines. That gap is the subject of this lesson. A model's purpose is to generalise: to capture the pattern behind its training examples well enough to handle new ones. It can fail in two opposite ways:
- Underfitting: the model is too simple to capture the pattern. It does poorly on the training data and on new data alike.
- Overfitting: the model is so flexible that it learns the training examples themselves, including their noise and mistakes. It does very well on the training data and noticeably worse on new data.
Every real dataset contains noise: measurement errors, mislabelled examples, cases that are simply unusual. A model that reproduces its training data perfectly has learned that noise as if it were part of the pattern.
Reading the Two Scores Together
Comparing the training score with the test score diagnoses the problem:
| Training score | Test score | Diagnosis |
|---|---|---|
| Low | Low, similar | Underfitting |
| High | Clearly lower | Overfitting |
| Good | Close to training | Reasonable fit |
Neither score alone is enough. A high training score can hide overfitting; a low test score could mean underfitting or overfitting, and only the training score tells you which.
Complexity Controls the Balance
Most models have settings that control how flexible, or complex, they can
become. For a decision tree, the main one is max_depth, the number of
question levels it may ask. A depth-1 tree asks one question; a tree with no
limit keeps splitting until every training sample is classified correctly.
As complexity grows, the training score rises steadily, while the test score
first rises, then levels off or falls once the model starts learning noise.

Read the diagram from left to right. The solid line is the training score and the dashed line the test score. The distance between them is the gap. On the left, both are low and close together. In the middle, the test score is at its highest. On the right, the training line keeps climbing while the test line falls away: the widening gap is the sign of overfitting.
Exercise: Watch a Tree Overfit
You will train trees with depths 1 to 12 on noisy generated data and find where they stop generalising.
Starting state: the course environment, active in your terminal. The script generates its own data.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/tree-depths cd ~/ai-practice/tree-depthsWindows PowerShell:
mkdir $HOME\ai-practice\tree-depths cd $HOME\ai-practice\tree-depthsSave this as
tree_depths.pyin that folder:"""Train decision trees of increasing depth and compare training and test accuracy.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier X, y = make_classification(n_samples=600, n_features=10, n_informative=4, flip_y=0.15, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y) depths = range(1, 13) train_scores, test_scores = [], [] print("depth train test") for depth in depths: tree = DecisionTreeClassifier(max_depth=depth, random_state=1).fit(X_train, y_train) train_scores.append(tree.score(X_train, y_train)) test_scores.append(tree.score(X_test, y_test)) print(f"{depth:5} {train_scores[-1]:.3f} {test_scores[-1]:.3f}") fig, ax = plt.subplots() ax.plot(depths, train_scores, marker="o", label="training") ax.plot(depths, test_scores, marker="s", linestyle="--", label="test") ax.set_xlabel("max_depth") ax.set_ylabel("accuracy") ax.legend() fig.savefig("tree_depths.png") print("Saved tree_depths.png") -
Run it:
python tree_depths.pyOutput, which should match exactly:
depth train test 1 0.711 0.720 2 0.747 0.720 3 0.842 0.813 4 0.867 0.827 5 0.889 0.800 6 0.924 0.793 7 0.953 0.780 8 0.971 0.793 9 0.982 0.760 10 0.993 0.747 11 1.000 0.747 12 1.000 0.747 Saved tree_depths.pngThe chart in
tree_depths.pngshows the same twelve pairs of numbers as two lines.
How the Script Works
Noisy data. make_classification generates 600 samples with 10
features, of which 4 carry information. flip_y=0.15 gives a random 15% of
the samples the wrong label, so no model can be right about all of them on new
data.
The loop. For each depth from 1 to 12, the script trains a tree on the
training samples only, then records its accuracy on the training samples and
on the test samples. The two lists, train_scores and test_scores, grow by
one value each time, and [-1] picks the value just added for printing.
The chart. Two ax.plot calls draw the training and test scores against
depth, with different markers and line styles so the lines differ without
relying on colour, and ax.legend() labels them.
What the results show. At depth 1, both scores are about 0.71: the tree is too simple, underfitting. The test score peaks at 0.827 at depth 4, where the training score is 0.867, a small gap. From there the training score keeps climbing until it reaches 1.000 at depth 11, while the test score drifts down to 0.747. The deep trees have memorised the training samples, including the deliberately wrong labels. A depth around 4 generalises best here.
Looking at test scores for twelve depths is fine for seeing the pattern, but choosing the depth this way would use the test set to make a decision, which the split lesson warned against. The next lesson shows how to choose fairly.
Success: the output matches; you can point to the underfitting region, the best depth and the overfitting region, using both columns.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Different numbers | random_state, flip_y or n_samples was changed | Restore the values shown |
| The training score is 1.000 at every depth | max_depth=depth is missing, so every tree is unlimited | Pass max_depth=depth |
No tree_depths.png | The script stopped before the chart lines, or ran in another folder | Read the error message; run ls in the exercise folder |
ModuleNotFoundError | The course environment is not active | Activate it and rerun |
-
Clean up. macOS and Linux:
cd ~/ai-practice ls rm -rf tree-depths lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse tree-depths lsCheck that the first
lsshowstree-depthsbefore removing it. Do the independent task first.
Independent task: change n_samples=600 to n_samples=1200 and predict
how the gap between the training and test scores at the deepest trees will
change. Run the script and compare.
Check Your Understanding
Label each pair of training and test accuracy as underfitting, overfitting or a reasonable fit:
- Training 0.99, test 0.71.
- Training 0.62, test 0.60.
- Training 0.86, test 0.84.
- Training 0.75, test 0.88.
Answer and Reasoning
Independent task
With 1,200 samples, the training score climbs more slowly: it reaches only 0.979 at depth 12, instead of 1.000 at depth 11. At depth 12 the gap is 0.979 against 0.750, about 0.23, slightly smaller than the 0.25 with 600 samples. The best test score, 0.783, now comes at depth 5. More data makes memorising harder, so overfitting sets in a little later and a little less sharply. It does not remove the problem: 15% of the labels are wrong, and a deep enough tree still learns them.
Understanding check
- Overfitting: nearly perfect on training data, much worse on test data.
- Underfitting: both scores are low and close together.
- A reasonable fit: both are good and close.
- None of the three patterns. A test score far above the training score is unusual and worth investigating: the test set may be too small, easier by chance, or contaminated, for example by duplicates of training samples or by leakage.