Level 3 In-Depth AI · Classical Machine Learning
Decision Trees
A model that predicts by asking a short series of yes/no questions about the features, like a game of twenty questions. Easy to read and explain, and the building block of random forests and gradient boosting.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 7 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 7 concepts before this one
- What Is AI?
- Probability Basics
- How Machines Learn
- Probability Distributions
- Supervised, Unsupervised and Reinforcement Learning
- Entropy, Cross-Entropy and KL Divergence
- Supervised Learning
- Decision Trees
Read them roughly in this order. See it on the concept map →
Why it matters
A doctor deciding whether chest pain is urgent, a bank deciding whether to approve a loan, a mechanic diagnosing a car: people often reason as a flowchart. Is the pain spreading to the arm? If yes, act now. If no, how old is the patient? A decision tree learns a flowchart like that from data.
Trees matter for three reasons:
- They are readable. A small tree can be printed on a page and checked by a domain expert, a regulator or a customer. Few other models can explain themselves this directly.
- They handle messy tabular data well. Mixed units, numbers and categories, skewed values, interactions between features: a tree copes with all of these without scaling or careful Feature Engineering.
- They are the building block of the best tabular models. On their own trees overfit badly. Hundreds of them combined become Random Forests and Bagging and gradient-boosted trees (XGBoost, LightGBM), which as of late 2026 are still usually the default choice for spreadsheet-style data (newer tabular foundation models such as TabPFN now rival them on many benchmarks, especially smaller datasets).
The intuition
Think of the game twenty questions. A good player doesn't start with "Is it a hedgehog?". They ask "Is it alive?", a question that splits the possibilities roughly in half whatever the answer. Each good question leaves you much less uncertain than before.
A decision tree is built the same way. It looks at all the training examples and asks: which single yes/no question about one feature would best separate the classes? It splits the data by that question, then asks the same thing again inside each half, and keeps going until the groups are pure (all one class) or too small to split.
To predict for a new person, start at the top and follow the answers down until you reach a leaf, a node with no further questions. The leaf's answer is the prediction.
Key idea A decision tree greedily picks, at each step, the one question that makes the resulting groups as pure as possible, then repeats inside each group. Prediction is just following the questions from the root to a leaf.
How it works
The parts of a tree
- A node is one box in the tree. The top one is the root.
- An internal node holds a split: a question about one feature, such as "income ≤ 51.5?" for a number or "owns a home?" for a yes/no feature.
- A leaf holds a prediction: the majority class of its training examples for classification (with the class shares as probabilities), or their average value for regression.
- The depth is the number of questions from the root to the deepest leaf. The tree above has depth 2.
Measuring purity
To choose a question, the algorithm needs a number that says how mixed a group is. Two are standard.
Gini impurity is the chance that two examples drawn at random from the group (with replacement) have different classes. If the class shares are :
A pure group has one , so . A 50/50 mix of two classes gives , the worst possible for two classes.
Entropy, from Entropy, Cross-Entropy and KL Divergence, measures how many bits of surprise the label carries on average:
It is 0 for a pure group and 1 bit for a 50/50 two-class mix.
Gini and entropy almost always choose the same splits. Gini is slightly faster (no logarithm), which is why it is the default in scikit-learn. Why not simply use the error rate? Because it is too blunt. A split can make both groups noticeably purer without changing either group's majority class, so the error rate doesn't move and the split looks useless. Gini and entropy are curved, so they reward that progress.
Scoring a split
A split sends examples left and right. Its quality is the size-weighted average impurity of the two children:
The information gain is how much the split lowers impurity: the parent's impurity minus . The best split is the one with the largest gain. (Strictly, "information gain" is the name used with entropy; with Gini it is often called the impurity decrease. The idea is identical.)
A worked example by hand
Ten loan applicants, with income (thousands of dollars), whether they own a home, and whether they repaid:
| Income | 80 | 42 | 45 | 30 | 90 | 55 | 48 | 40 | 35 | 25 |
|---|---|---|---|---|---|---|---|---|---|---|
| Owns home | yes | yes | yes | yes | no | no | no | no | no | no |
| Repaid | yes | yes | yes | yes | yes | yes | no | no | no | no |
The root. 6 repaid and 4 defaulted, so .
Candidate split A: "owns a home?"
- Yes: 4 people, all repaid. .
- No: 6 people, 2 repaid and 4 defaulted. .
- Weighted: . Gain: .
Candidate split B: "income ≤ 50?"
- Yes: 7 people (25, 30, 35, 40, 42, 45, 48), of whom 3 repaid. .
- No: 3 people (55, 80, 90), all repaid. .
- Weighted: . Gain: .
Split A wins. The algorithm tries every income threshold too (midway between each pair of neighbouring sorted values) and none beats 0.267, so "owns a home?" becomes the root.
The next level. The owners' branch is pure, so it becomes a leaf: "repaid". For the six non-owners (incomes 90, 55 repaid; 48, 40, 35, 25 defaulted), the threshold halfway between 48 and 55, "income ≤ 51.5?", separates them perfectly. Both children are pure and the tree stops. That is the tree in the first figure.
With entropy instead of Gini the root is bits, split A leaves (gain 0.420) and split B leaves (gain 0.281). Same winner.
Growing the whole tree
The full procedure is called recursive partitioning:
- At the current node, try every feature and every threshold. Compute the gain of each.
- Apply the best split, creating two child nodes.
- Repeat steps 1 and 2 on each child.
- Stop when a node is pure, or a stopping rule says so (see below). Make it a leaf.
It is greedy: each split is the best one right now, with no look-ahead. Finding the truly optimal tree is computationally intractable, but greedy trees work well in practice.
For regression trees, the leaf predicts the mean target of its examples, and impurity is replaced by variance (equivalently, mean squared error). The best split is the one that most reduces the squared error around each child's mean. The prediction surface is a staircase of flat steps.
Why trees overfit
Left alone, the procedure keeps splitting until every leaf is pure. With noisy data that means carving out a tiny region around every stray point.
Two things stand out in the picture. First, every boundary is horizontal or vertical, because each split looks at one feature. A diagonal boundary has to be approximated by a staircase. Second, the unlimited tree has memorised the noise: 100% on training data, 88% on fresh data, against 90% for the depth-2 tree. This is Overfitting and the Bias–Variance Tradeoff in its purest form. A deep tree has low bias but very high variance: change a few training examples and you can get a completely different tree.
Controlling size: stopping and pruning
There are two ways to keep a tree in check.
Stop early (pre-pruning) with hyperparameters:
max_depth: at most this many questions in a row. The single most useful knob.min_samples_leaf: every leaf must hold at least this many examples (say 5 or 20), so no leaf rests on one point.min_samples_split,max_leaf_nodes,min_impurity_decrease: similar limits.
Grow, then cut back (post-pruning). Grow a big tree, then remove branches that don't earn their keep. Cost-complexity pruning, from the CART method, adds a penalty per leaf, and keeps a branch only if it reduces the error by more than times the number of leaves it adds. In scikit-learn this is the ccp_alpha parameter. Pick it, like max_depth, by Cross-Validation.
Reading a tree
A trained tree also tells you which features it relied on. A feature's importance is the total impurity decrease from all splits on it, weighted by how many examples pass through those splits. The exact rules are readable too: every path from root to leaf is an "if … and … then …" rule. For a tree of depth 3 or 4 you can show the whole thing to a non-specialist. Beyond depth 6 or so the readability argument fades.
In code
The heart of the algorithm, finding the best split, from scratch in NumPy:
import numpy as np
# income (k$), owns home (1/0) -> repaid (1) or defaulted (0)
X = np.array([[80, 1], [42, 1], [45, 1], [30, 1], [90, 0],
[55, 0], [48, 0], [40, 0], [35, 0], [25, 0]])
y = np.array([1, 1, 1, 1, 1, 1, 0, 0, 0, 0])
def gini(labels):
p = np.bincount(labels, minlength=2) / len(labels)
return 1 - np.sum(p ** 2)
def best_split(X, y):
best = (None, None, gini(y)) # (feature, threshold, impurity)
for j in range(X.shape[1]):
values = np.unique(X[:, j])
for t in (values[:-1] + values[1:]) / 2: # midpoints between sorted values
left, right = y[X[:, j] <= t], y[X[:, j] > t]
w = (len(left) * gini(left) + len(right) * gini(right)) / len(y)
if w < best[2]:
best = (j, t, w)
return best
print("root gini:", round(gini(y), 3))
j, t, w = best_split(X, y)
print(f"best split: feature {j} <= {t} weighted gini {w:.3f}")
mask = X[:, j] > t # owns home = 1 goes right
j2, t2, w2 = best_split(X[~mask], y[~mask])
print(f"then, for non-owners: feature {j2} <= {t2} weighted gini {w2:.3f}")
# root gini: 0.48
# best split: feature 1 <= 0.5 weighted gini 0.267
# then, for non-owners: feature 0 <= 51.5 weighted gini 0.000
Wrap best_split in a function that calls itself on each side and you have a complete tree learner. In scikit-learn, on a real medical dataset, you can watch depth trade training accuracy for test accuracy, and print the rules:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
data = load_breast_cancer()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, test_size=0.3, random_state=0)
for depth in (1, 2, 3, 5, None):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_tr, y_tr)
print(f"max_depth={str(depth):4} leaves={tree.get_n_leaves():2d} "
f"train={tree.score(X_tr, y_tr):.3f} test={tree.score(X_te, y_te):.3f}")
small = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_tr, y_tr)
print(export_text(small, feature_names=list(data.feature_names)))
# max_depth=1 leaves= 2 train=0.930 test=0.895
# max_depth=2 leaves= 4 train=0.960 test=0.947
# max_depth=3 leaves= 7 train=0.967 test=0.947
# max_depth=5 leaves=14 train=0.987 test=0.936
# max_depth=None leaves=19 train=1.000 test=0.912
# |--- worst concave points <= 0.14
# | |--- worst area <= 952.90
# | | |--- class: 1
# | |--- worst area > 952.90
# | | |--- class: 0
# |--- worst concave points > 0.14
# | |--- area error <= 13.93
# | | |--- class: 1
# | |--- area error > 13.93
# | | |--- class: 0
Training accuracy climbs to 100% as depth grows, while test accuracy peaks at depth 2 or 3 and then falls. A four-leaf tree that a doctor can read scores 94.7% on unseen tumours. (Class 1 means benign in this dataset.) sklearn.tree.plot_tree draws the same tree as a picture.
Common pitfalls
- No depth limit. The default
DecisionTreeClassifier()grows until leaves are pure and almost always overfits. Setmax_depthormin_samples_leaf, chosen by cross-validation. - Instability. Small changes in the data can change the root split and hence the whole tree. Don't over-interpret one tree's structure; check whether it is stable across resamples. Ensembles fix this.
- Staircase boundaries. Trees can only cut along one feature at a time. If the true boundary is "", a tree needs many splits to approximate it, while Logistic Regression gets it in one. Adding a feature helps.
- No extrapolation. A regression tree predicts the average of a leaf, so it never predicts beyond the range of targets it saw. If house prices rise past anything in the training data, the tree's predictions stay flat. This matters for Time Series Forecasting.
- Biased importances. Impurity-based feature importance favours features with many distinct values (such as IDs or continuous noise). Prefer permutation importance on held-out data.
Watch out An unpruned decision tree can reach 100% training accuracy on almost anything, including random labels. That number tells you nothing. Always judge a tree on data it hasn't seen.
Where it leads
- Random forests average hundreds of deep trees, each trained on a random resample of the data and features. The averaging cancels the variance that makes single trees unstable. See Random Forests and Bagging.
- Gradient boosting adds many shallow trees one after another, each fixing the errors of the ones before. It is the method behind XGBoost and LightGBM. See Gradient Boosting: XGBoost and LightGBM.
- Isolation forests use random trees to find anomalies. See Anomaly Detection.
- Explaining other models. A shallow tree trained to mimic a complex model is a common way to summarise what that model does. See Interpretability and Explainability.
A bit of history
Tree-structured classification has roots in 1960s social-science survey analysis, notably the AID (Automatic Interaction Detection) program of Morgan and Sonquist in 1963. The modern methods arrived in the 1980s from two directions at once. In statistics, Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone published Classification and Regression Trees (CART) in 1984, introducing Gini splits, regression trees and cost-complexity pruning. In machine learning, Ross Quinlan published ID3 in 1986, which used entropy-based information gain, followed by C4.5 in 1993, which handled continuous features and missing values and became one of the most widely used learning programs of the 1990s.
Single trees were then overtaken by ensembles of them: bagging (1996), random forests (2001) and gradient boosting (1999–2001). scikit-learn's tree implementation is an optimised version of CART.
Try it
- In the hand example, compute the weighted Gini of the split "income ≤ 41?". Does it beat "owns a home?"?
- Add an eleventh applicant, a non-owner with income 60 who defaulted. Recompute the best split for the non-owners. Can a single threshold still separate them?
- Harder: turn
best_splitinto a recursivebuild_tree(X, y, depth)that returns nested dictionaries and stops at depth 3 or when a node is pure. Test it on the iris dataset.Hint for 1: the left side is {25, 30, 35, 40} with 1 repaid; the right side has 5 repaid and 1 defaulted.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Decision Forests course
A short, clear course on decision trees, random forests and gradient-boosted trees, with diagrams.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn: Decision Trees
How scikit-learn grows, prunes and visualises trees, with practical tips on depth and leaf size.
The Elements of Statistical Learning
The graduate-level reference for classical statistical learning. Free PDF.
Interpretable Machine Learning
A clear guide to making black-box models explainable: feature importance, SHAP, LIME and more.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/decision-trees.md