A decision tree is a model that makes a prediction by asking a series of simple yes/no questions about the data, exactly like the flowchart a person might draw by hand: is the applicant's income above this value? Is the temperature below that one? What makes it a machine learning algorithm is that the questions are not written by a human. They are learned from examples, by repeatedly choosing the question that best separates the classes. Decision trees are one of the most readable models in machine learning, they need almost no data preparation, and they are the building block of the most successful methods for tabular data: random forests and gradient boosting.
This article explains how a classification tree is learned, using a small example that can be followed by hand, then implements the algorithm from scratch in Python. It then shows that the very same code also solves a regression problem, predicting a number instead of a class, and looks at the most important weakness of trees: overfitting.
A characteristic example: will the student pass?
Sixteen students recorded how many hours they studied for an exam and how many hours they slept the night before. Some passed, some failed:
| # | Study (h) | Sleep (h) | Result | # | Study (h) | Sleep (h) | Result |
|---|---|---|---|---|---|---|---|
| 1 | 1 | 5 | fail | 9 | 5 | 7 | pass |
| 2 | 2 | 8 | fail | 10 | 6 | 6.5 | pass |
| 3 | 2 | 6 | fail | 11 | 6 | 8 | pass |
| 4 | 3 | 7 | fail | 12 | 7 | 6 | pass |
| 5 | 4 | 6.5 | fail | 13 | 7 | 8.5 | pass |
| 6 | 5 | 4 | fail | 14 | 9 | 7 | pass |
| 7 | 6 | 5 | fail | 15 | 8 | 4.5 | pass |
| 8 | 7 | 4.5 | fail | 16 | 9 | 5.5 | pass |
We want a model that, given a new student's study and sleep hours, predicts whether they will pass. It is a binary classification problem with two numeric features. Plotted, the students look like this; the shading and the dashed lines will be explained below.
The idea
A decision tree consists of three kinds of elements:
- an internal node asks a question about one feature, such as
study ≤ 4.5; - each answer leads along a branch to another node;
- a leaf gives the prediction, usually the majority class of the training examples that reached it.
To classify a new example, you start at the root, answer the question, follow the branch, and repeat until you reach a leaf. Learning the tree means answering two questions: which question should each node ask, and when should we stop asking?
How mixed is a node? Gini impurity and entropy
A good question produces groups that are purer than before, that is, groups that contain mostly one class. To compare questions we need a number that measures how mixed a group is. Two measures are in common use. For a node in which a fraction $p_k$ of the examples belongs to class $k$:
Both are $0$ for a pure node and largest when the classes are evenly mixed. For two classes the curves look like this:
Our whole dataset has 8 failures and 8 passes, the worst possible mix: $\text{Gini} = 1 - 0.5^2 - 0.5^2 = 0.5$ and $\text{Entropy} = 1$ bit.
Choosing the best question
For a candidate question that splits $n$ examples into a left group (with $n_L$ examples) and a right group ($n_R$), the quality of the split is the weighted impurity of the two groups:
The impurity decrease is $G(\text{parent}) - G_{\text{split}}$. When the impurity measure is entropy, this decrease is called the information gain. The algorithm picks the question with the largest decrease.
For a numeric feature the candidate questions are of the form feature ≤ t. It is enough to try one threshold $t$ halfway between each pair of consecutive distinct values in the data, since any threshold in between would split the examples in exactly the same way. Doing that for both features at the root gives:
| Best question per feature | Left (fail / pass) | Right (fail / pass) | Weighted Gini | Gini decrease | Information gain |
|---|---|---|---|---|---|
study ≤ 4.5 | 5 / 0 | 3 / 8 | 0.273 | 0.227 | 0.419 |
sleep ≤ 5.25 | 4 / 1 | 4 / 7 | 0.418 | 0.082 | 0.124 |
The question about study hours wins: it isolates five students who all failed in a perfectly pure group. Gini and entropy agree here, and in practice they almost always pick the same or a very similar tree, so the choice between them rarely matters.
The algorithm
Learning a tree is greedy recursive partitioning:
- Start with all the training examples in one node.
- If the node should be a leaf (see below), make it one and predict its majority class.
- Otherwise try every feature and every candidate threshold, and choose the split with the largest impurity decrease.
- Send the examples to the left or right child and repeat from step 2 for each child.
A node becomes a leaf when it is pure (only one class left), when it has too few examples, when a maximum depth has been reached, or when no split improves the impurity. The method is "greedy" because every node simply takes the best split for itself; it never looks ahead, and it never revisits an earlier choice. Finding the truly smallest tree is a much harder problem (it is NP-complete), so this simple strategy is what everyone uses.
The example, step by step
- Root, 16 students (Gini 0.50). The best question is
study ≤ 4.5. The left group of five students is pure (all failed) and becomes a leaf. - Right child, 11 students: 3 failed and 8 passed (Gini 0.40). The best split is
sleep ≤ 5.25: the group with more sleep contains 7 students who all passed, a pure leaf. The group with less sleep has 4 students (Gini 0.375). The weighted impurity falls to 0.136, a decrease of 0.260. - The 4 students who studied more than 4.5 hours but slept at most 5.25 hours: 3 failed and 1 passed. The split
study ≤ 7.5separates them perfectly, and both groups are pure.
Read from the root, the tree is a set of rules a person can check: a student who studied up to 4.5 hours is predicted to fail; of those who studied more, anyone who slept more than 5.25 hours is predicted to pass; and a student with little sleep passes only if they studied more than 7.5 hours. Geometrically (Figure 1), every leaf is a rectangle whose sides are the thresholds on the path to it.
Implementation in Python
Here is the whole algorithm in a few dozen lines of standard-library Python: the impurity measures, the search for the best split, the recursive construction, and prediction. The tree is stored as nested dictionaries. The impurity function and the way a leaf's value is computed are parameters: they default to Gini and the majority class (classification), and they are the only two things that change for regression, as shown further below.
from collections import Counter
def gini(labels):
"""Gini impurity: 0 for a pure node, 0.5 for a 50/50 two-class node."""
n = len(labels)
return 1 - sum((c / n) ** 2 for c in Counter(labels).values())
def variance(values):
"""Impurity for regression: the mean squared deviation from the node's mean."""
m = sum(values) / len(values)
return sum((v - m) ** 2 for v in values) / len(values)
def majority(labels):
return Counter(labels).most_common(1)[0][0]
def mean(values):
return sum(values) / len(values)
def best_split(X, y, impurity=gini):
"""Best axis-aligned split (feature, threshold, weighted impurity), or (None, None, ...)."""
n = len(y)
best = (None, None, impurity(y))
for j in range(len(X[0])):
values = sorted({row[j] for row in X})
for lo, hi in zip(values, values[1:]):
t = (lo + hi) / 2 # candidate: midpoint between neighbours
left = [y[i] for i in range(n) if X[i][j] <= t]
right = [y[i] for i in range(n) if X[i][j] > t]
score = (len(left) * impurity(left) + len(right) * impurity(right)) / n
if score < best[2] - 1e-12: # strictly better than the best so far
best = (j, t, score)
return best
def build(X, y, depth=0, max_depth=3, min_samples=2, impurity=gini, leaf_value=majority):
"""Grow the tree recursively; a node is a dict. Classification: gini + majority. Regression: variance + mean."""
node = {"n": len(y), "impurity": impurity(y), "value": leaf_value(y)}
if depth == max_depth or len(y) < min_samples or node["impurity"] == 0:
return node # a leaf
j, t, _ = best_split(X, y, impurity)
if j is None: # no split reduces the impurity
return node
L = [i for i in range(len(y)) if X[i][j] <= t]
R = [i for i in range(len(y)) if X[i][j] > t]
kw = dict(max_depth=max_depth, min_samples=min_samples, impurity=impurity, leaf_value=leaf_value)
return {**node, "feature": j, "threshold": t,
"left": build([X[i] for i in L], [y[i] for i in L], depth + 1, **kw),
"right": build([X[i] for i in R], [y[i] for i in R], depth + 1, **kw)}
def predict(tree, x):
while "feature" in tree:
tree = tree["left"] if x[tree["feature"]] <= tree["threshold"] else tree["right"]
return tree["value"]
def show(tree, names, indent="", fmt="{}"):
if "feature" not in tree:
print(f"{indent}-> {fmt.format(tree['value'])} (n = {tree['n']})")
return
print(f"{indent}if {names[tree['feature']]} <= {tree['threshold']:g}:")
show(tree["left"], names, indent + " ", fmt)
print(f"{indent}else:")
show(tree["right"], names, indent + " ", fmt)
if __name__ == "__main__":
# Classification: (hours studied, hours slept) -> passed the exam?
X = [(1, 5), (2, 8), (2, 6), (3, 7), (4, 6.5), (5, 4), (6, 5), (7, 4.5),
(5, 7), (6, 6.5), (6, 8), (7, 6), (7, 8.5), (9, 7), (8, 4.5), (9, 5.5)]
y = ["fail"] * 8 + ["pass"] * 8
tree = build(X, y, max_depth=3)
show(tree, ["study", "sleep"])
print("training accuracy:", sum(predict(tree, x) == t for x, t in zip(X, y)) / len(y))
print("new student (6 h study, 5 h sleep):", predict(tree, (6, 5)))
Running it prints the tree and shows that it classifies all sixteen training students correctly:
if study <= 4.5:
-> fail (n = 5)
else:
if sleep <= 5.25:
if study <= 7.5:
-> fail (n = 3)
else:
-> pass (n = 1)
else:
-> pass (n = 7)
training accuracy: 1.0
new student (6 h study, 5 h sleep): fail
The splits are exactly the ones found by hand above. This version rescans the data for every threshold, so it takes time proportional to $n^2$ per feature at each node, which is fine for a teaching example. Real libraries sort each feature once and update the class counts incrementally as the threshold moves, which brings the cost down to $O(n \log n)$.
In practice you would use scikit-learn, which implements the same algorithm (with the same midpoint thresholds):
from sklearn.tree import DecisionTreeClassifier, export_text
clf = DecisionTreeClassifier(criterion="gini", max_depth=3, random_state=0)
clf.fit(X, y)
print(export_text(clf, feature_names=["study", "sleep"]))
Use criterion="entropy" to select splits by information gain instead of Gini impurity.
Regression trees: predicting a number
Nothing in the idea of a tree is specific to classes. If the target is a number, the tree still splits the data into groups that are as similar as possible; each leaf now predicts the mean of the target values that reached it. Only two ingredients change:
- the impurity of a node is the variance of its target values, $\text{Var} = \frac{1}{n}\sum_i (y_i - \bar y)^2$, which is $0$ when all the values are equal;
- the prediction of a leaf is the mean $\bar y$ of its values, instead of the majority class.
The split criterion is the same weighted impurity as before, now called the variance reduction, and the recursive procedure is unchanged.
A characteristic example: the power curve of a wind turbine
The electrical power of a wind turbine is a textbook non-linear relationship: nothing below the cut-in speed of about 3 m/s, a steep rise (power grows roughly with the cube of the wind speed), and a flat plateau at the rated power once the wind is strong enough. No straight line describes it. We simulate 100 noisy readings of wind speed (2–16 m/s) and power (kW), using 60 to train the tree and keeping 40 aside to test it.
import random
def power_curve(v):
"""Idealised turbine power (kW): cut-in at 3 m/s, cubic rise, rated 2000 kW from 12 m/s."""
if v < 3:
return 0.0
return 2000 * ((v - 3) / 9) ** 3 if v < 12 else 2000.0
def make_data(n=100, noise=90.0, seed=11):
rnd = random.Random(seed)
data = []
for _ in range(n):
v = round(rnd.uniform(2, 16), 2) # wind speed in m/s
data.append((v, round(max(0.0, power_curve(v) + rnd.gauss(0, noise)), 1)))
return data[:60], data[60:] # 60 for training, 40 for testing
train, test = make_data()
X = [(v,) for v, _ in train]
y = [p for _, p in train]
# Same functions as before: only the impurity and the leaf value change.
tree = build(X, y, max_depth=2, impurity=variance, leaf_value=mean)
show(tree, ["speed"], fmt="{:.0f} kW")
print(f"prediction at 10.5 m/s: {predict(tree, (10.5,)):.0f} kW")
The four leaves describe the behaviour of the turbine:
if speed <= 9.605:
if speed <= 7.305:
-> 28 kW (n = 27)
else:
-> 455 kW (n = 11)
else:
if speed <= 11.46:
-> 1251 kW (n = 7)
else:
-> 2000 kW (n = 15)
prediction at 10.5 m/s: 1251 kW
The very first split already does most of the work. On the 60 training readings the power has a mean of 742 kW and a variance of 679,833 kW² (a standard deviation of 825 kW). The best split, speed ≤ 9.605, creates a group of 38 low-wind readings with mean 152 kW and variance 42,627 kW², and a group of 22 windy readings with mean 1,762 kW and variance 138,931 kW². The weighted variance drops to $\tfrac{38}{60}\cdot 42{,}627 + \tfrac{22}{60}\cdot 138{,}931 \approx 77{,}939$ kW², a reduction of about 89%. Splitting again on each side gives the four steps above.
The picture shows two typical features of regression trees. First, the prediction is a staircase: a piecewise-constant function with one step per leaf, and the more leaves, the finer the steps. Second, the usual trade-off between a simple and a complex tree appears again, in terms of the root-mean-square error (RMSE), $\sqrt{\frac{1}{n}\sum_i (y_i - \hat y_i)^2}$, on the training and on the unseen data:
| Model | Leaves | Training RMSE | Test RMSE |
|---|---|---|---|
| no tree: always predict the mean | 1 | 825 kW | 837 kW |
| depth 1 | 2 | 279 kW | 359 kW |
| depth 2 | 4 | 98 kW | 139 kW |
| depth 3 | 8 | 69 kW | 111 kW |
| depth 4 | 16 | 58 kW | 116 kW |
| depth 5 | 27 | 47 kW | 108 kW |
| fully grown | 56 | 8 kW | 122 kW |
Even a single split brings the test error far below the 837 kW of a model that always predicts the mean. Beyond depth 3 the training error keeps falling, from 69 kW to just 8 kW for the fully grown tree, but the error on unseen readings stops improving: it hovers between 108 and 116 kW for depths 3 to 5 and then rises to 122 kW for the fully grown tree, which is the same overfitting that we meet in classification. Because every leaf is a constant, a regression tree also cannot extrapolate: for a wind speed outside the range it was trained on, it simply repeats the value of the nearest leaf.
In scikit-learn the regression version is DecisionTreeRegressor:
from sklearn.tree import DecisionTreeRegressor
reg = DecisionTreeRegressor(max_depth=3, random_state=0) # criterion="squared_error" by default
reg.fit(X, y)
print(reg.predict([[10.5]]))
A civil engineering example: the strength of concrete
Civil engineers meet the same kind of problem all the time: a measured quantity that depends on several inputs in a non-linear way. A classic one is the compressive strength of concrete. Two inputs dominate it. The first is the water–cement ratio $w/c$: the more water per kilogram of cement, the more porous and weaker the hardened paste (a relationship known as Abrams' law). The second is the age of the concrete when it is tested: strength keeps growing as the cement hydrates, quickly in the first days and then ever more slowly. Eurocode 2 expresses the age effect as $\beta_{cc}(t) = \exp\{s\,[1 - \sqrt{28/t}]\}$, with $s = 0.25$ for normal-hardening cement. When more ingredients come into play (admixtures, fly ash, different aggregates) no simple law is available, and engineers fit empirical models to test data; a well-known public dataset of this kind is the UCI "Concrete Compressive Strength" dataset.
To keep the example transparent we simulate the specimens from the two laws above, with illustrative constants ($f_{28} = 95 / 8^{w/c}$ MPa for Abrams' law) and a random scatter of 2.5 MPa. The generator below creates 150 specimens with $w/c$ between 0.35 and 0.75, tested at the usual ages of 3, 7, 14, 28, 56 and 90 days; 100 are used for training and 50 for testing. The tree now has two features, and the code does not change at all.
import math
import random
def strength(wc, age):
"""Idealised compressive strength (MPa): Abrams' law times the Eurocode 2 age function."""
f28 = 95.0 / 8.0 ** wc # strength at 28 days falls as w/c rises
return f28 * math.exp(0.25 * (1 - math.sqrt(28.0 / age))) # ... and grows with age
def make_data(n=150, noise=2.5, seed=5):
rnd = random.Random(seed)
data = []
for _ in range(n):
wc = round(rnd.uniform(0.35, 0.75), 3) # water-cement ratio
age = rnd.choice([3, 7, 14, 28, 56, 90]) # age at testing, days
data.append(((wc, age), round(strength(wc, age) + rnd.gauss(0, noise), 1)))
return data[:100], data[100:] # 100 specimens to train, 50 to test
train, test = make_data()
X = [features for features, _ in train]
y = [mpa for _, mpa in train]
tree = build(X, y, max_depth=3, impurity=variance, leaf_value=mean)
show(tree, ["wc", "age"], fmt="{:.1f} MPa")
print(f"w/c = 0.45 at 28 days: {predict(tree, (0.45, 28)):.1f} MPa")
if wc <= 0.5005:
if age <= 21:
if age <= 5:
-> 24.1 MPa (n = 3)
else:
-> 31.8 MPa (n = 13)
else:
if wc <= 0.414:
-> 45.6 MPa (n = 7)
else:
-> 38.8 MPa (n = 13)
else:
if age <= 5:
if wc <= 0.666:
-> 17.2 MPa (n = 6)
else:
-> 11.5 MPa (n = 6)
else:
if wc <= 0.579:
-> 29.7 MPa (n = 15)
else:
-> 23.7 MPa (n = 37)
w/c = 0.45 at 28 days: 38.8 MPa
Read like an engineer, the tree has rediscovered what the theory says:
- The first question is about the water–cement ratio, at 0.50. The 36 specimens below it average 36.4 MPa and the 64 above it 23.4 MPa; this one split removes about 48% of the variance of the strengths.
- Within each group the tree then asks about age. The thresholds 5 and 21 days lie halfway between the tested ages (3 and 7 days, 14 and 28 days), exactly as the midpoint rule dictates. The 3-day specimens are clearly the weakest in every group.
- Further questions on $w/c$ refine the groups: among the older low-$w/c$ specimens, those below 0.414 are the strongest of all (45.6 MPa).
Adding up the variance reduction of every split shows which input the tree relied on: about two thirds comes from the water–cement ratio and one third from age. This built-in feature importance is a useful first look at what drives the result, though it should be taken as a rough guide, since impurity-based importances favour features with many distinct values. The accuracy follows the same pattern as before:
| Model | Leaves | Training RMSE | Test RMSE |
|---|---|---|---|
| no tree: always predict the mean | 1 | 9.0 MPa | 7.9 MPa |
| depth 1 | 2 | 6.5 MPa | 8.1 MPa |
| depth 2 | 4 | 4.5 MPa | 6.3 MPa |
| depth 3 | 8 | 3.5 MPa | 4.0 MPa |
| depth 4 | 16 | 2.5 MPa | 3.8 MPa |
| depth 5 | 30 | 1.8 MPa | 3.8 MPa |
| fully grown | 95 | 0.3 MPa | 4.0 MPa |
| the true law (noise floor) | – | – | 2.3 MPa |
For a specimen with $w/c = 0.45$ tested at 28 days, the tree predicts 38.8 MPa, while the noise-free law gives 37.3 MPa. The depth-3 tree cuts the test error from 7.9 MPa (always predicting the mean) to 4.0 MPa. (A single split on $w/c$ alone is no better than the mean on this particular test set; with only 50 test specimens, small differences like that are noise.) It does not reach the floor of about 2.3 MPa, which is the random scatter we added to the data, because the true relationship is a smooth surface and eight flat rectangles cannot follow it exactly. More depth helps only until about depth 5; the fully grown tree has 95 leaves and a training error of 0.3 MPa, but its test error of 4.0 MPa is no better than that of a much smaller tree.
The catch: overfitting
A tree can always be grown until every leaf is pure (or, for regression, until every leaf holds a single value), and then it reproduces the training data perfectly. But a perfect score on the data it has already seen says little: such a tree has partly memorised noise, as the fully grown regression tree above shows. Notice the leaf of our own tree that holds a single student (the one who studied 8 hours and slept 4.5, and passed). It may be a real effect, or it may be luck; with sixteen examples we cannot tell.
The effect is just as easy to see for classification on a larger, noisier problem. The experiment below uses a synthetic two-class dataset (two interleaving half-circles with Gaussian noise, 100 points for training and 100 for testing), grows the same tree to different maximum depths, and averages the result over 10 random splits.
The usual remedies all limit how complex the tree can get:
- maximum depth or maximum number of leaves;
- a minimum number of examples to split a node or to be allowed in a leaf (
min_samples_split,min_samples_leaf); - a minimum impurity decrease for a split to be worth making;
- pruning: grow a large tree and cut back the branches that do not pay for themselves (cost-complexity pruning,
ccp_alphain scikit-learn); - and above all, choosing these settings with cross-validation rather than by looking at the training score.
Strengths and limitations
| Strengths | Limitations |
|---|---|
| Easy to read, explain and visualise: the model is a set of rules. | Splits are axis-aligned, so a diagonal boundary needs a staircase of many splits. |
| No feature scaling or normalisation needed. | High variance: a small change in the data can produce a very different tree. |
| Captures non-linear effects and interactions between features automatically. | Greedy, so the tree is not guaranteed to be the best one. |
| Fast to apply: a prediction needs only as many comparisons as the tree is deep. | Overfits unless its size is controlled. |
| Works with numeric and (suitably encoded) categorical features. | Predictions are piecewise constant, so a regression tree cannot extrapolate beyond the training range. |
From one tree to many
The instability of a single tree is also the reason ensembles work so well. A random forest trains many trees, each on a random resample of the data and with random subsets of features at each split, and averages their votes (or, for regression, their predictions), which removes most of the variance. Gradient boosting builds shallow trees one after another, each correcting the errors of the ones before it. Both are built from exactly the trees described above, which is why understanding a single tree is the best first step towards them.
Summary
- A decision tree is a learned flowchart of yes/no questions; leaves hold the predictions.
- At each node the algorithm picks the question that most reduces the impurity (Gini or entropy) of the resulting groups, then recurses on each group.
- The result is a set of rectangular regions with readable rules, and it takes only a few lines of Python.
- For regression, use the variance as the impurity and the mean as the leaf value: the tree becomes a staircase fit.
- Left to grow freely, a tree overfits; limit its depth and size, prune it, and choose the settings by cross-validation.
- For the best accuracy, combine many trees in a random forest or with gradient boosting.