◆ AI All-in-One

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
↗ Plan a path here

Read first

Supervised LearningEntropy, Cross-Entropy and KL Divergence

This leads to

Gradient Boosting: XGBoost and LightGBMRandom Forests and Bagging
The full path from zero — 7 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. How Machines Learn
  4. Probability Distributions
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Entropy, Cross-Entropy and KL Divergence
  7. Supervised Learning
  8. 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.

Owns a home? 10 people · 6 repaid, 4 defaulted · Gini 0.48 Income ≤ 51.5k? 6 people · 2 repaid, 4 defaulted · Gini 0.44 Predict: repaid 4 people · 4 repaid · Gini 0 Predict: default 4 people · 4 defaulted · Gini 0 Predict: repaid 2 people · 2 repaid · Gini 0 yes no yes no internal node asks one question about one feature leaf gives the answer: the majority class bars: share repaid (green) and defaulted (red) among the people reaching each node
Fig. 1 A decision tree learned from ten loan applicants. The root asks whether the applicant owns a home. All four owners repaid, so that branch stops. The six non-owners are split again by income, which separates them perfectly. Each leaf predicts the majority class of the training examples that reach it.

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 p1,…,pKp_1, \dots, p_K:

G=1−∑k=1Kpk2G = 1 - \sum_{k=1}^{K} p_k^2

A pure group has one pk=1p_k = 1, so G=0G = 0. A 50/50 mix of two classes gives G=1−(0.25+0.25)=0.5G = 1 - (0.25 + 0.25) = 0.5, 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:

H=−∑k=1Kpklog⁡2pkH = -\sum_{k=1}^{K} p_k \log_2 p_k

It is 0 for a pure group and 1 bit for a 50/50 two-class mix.

0 0 0.5 0.5 1 1 p = share of the node in one class impurity entropy max 1 bit at p = 0.5 Gini impurity max 0.5 at p = 0.5 error rate too flat to guide splits well dots: our root node, 6 repaid / 4 defaulted all three are zero for a pure node and largest for a 50/50 mix
Fig. 2 Three ways to measure how mixed a two-class node is, as the share p of one class goes from 0 to 1. Entropy and Gini both peak at a 50/50 mix and are zero for pure nodes. Plain error rate has the same ends but is a straight tent, which makes it a poor guide for choosing splits.

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 nLn_L examples left and nRn_R right. Its quality is the size-weighted average impurity of the two children:

Gsplit=nLnGL+nRnGRG_{\text{split}} = \frac{n_L}{n} G_L + \frac{n_R}{n} G_R

The information gain is how much the split lowers impurity: the parent's impurity minus GsplitG_{\text{split}}. 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 G=1−(0.62+0.42)=1−0.52=0.48G = 1 - (0.6^2 + 0.4^2) = 1 - 0.52 = 0.48.

Candidate split A: "owns a home?"

  • Yes: 4 people, all repaid. G=0G = 0.
  • No: 6 people, 2 repaid and 4 defaulted. G=1−((2/6)2+(4/6)2)=1−0.556=0.444G = 1 - \left((2/6)^2 + (4/6)^2\right) = 1 - 0.556 = 0.444.
  • Weighted: 410×0+610×0.444=0.267\frac{4}{10} \times 0 + \frac{6}{10} \times 0.444 = 0.267. Gain: 0.48−0.267=0.2130.48 - 0.267 = 0.213.

Candidate split B: "income ≤ 50?"

  • Yes: 7 people (25, 30, 35, 40, 42, 45, 48), of whom 3 repaid. G=1−((3/7)2+(4/7)2)=0.490G = 1 - \left((3/7)^2 + (4/7)^2\right) = 0.490.
  • No: 3 people (55, 80, 90), all repaid. G=0G = 0.
  • Weighted: 710×0.490+310×0=0.343\frac{7}{10} \times 0.490 + \frac{3}{10} \times 0 = 0.343. Gain: 0.48−0.343=0.1370.48 - 0.343 = 0.137.

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 H=0.971H = 0.971 bits, split A leaves 0.6×0.918=0.5510.6 \times 0.918 = 0.551 (gain 0.420) and split B leaves 0.7×0.985=0.6900.7 \times 0.985 = 0.690 (gain 0.281). Same winner.

Growing the whole tree

The full procedure is called recursive partitioning:

  1. At the current node, try every feature and every threshold. Compute the gain of each.
  2. Apply the best split, creating two child nodes.
  3. Repeat steps 1 and 2 on each child.
  4. 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.

max_depth = 2 4 leaves · training accuracy 90% accuracy on new data 90% no depth limit 44 leaves · training accuracy 100% accuracy on new data 88%
Fig. 3 The same noisy two-class data split by a tree limited to depth 2 (left) and an unlimited tree (right). Every split is a straight cut along one axis, so regions are rectangles. The unlimited tree grows 44 leaves and fits the training data perfectly, including thin slivers around single noisy points, and does worse on new data.

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 α\alpha per leaf, and keeps a branch only if it reduces the error by more than α\alpha 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. Set max_depth or min_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 "x1+x2>10x_1 + x_2 > 10", a tree needs many splits to approximate it, while Logistic Regression gets it in one. Adding a feature x1+x2x_1 + x_2 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

  1. In the hand example, compute the weighted Gini of the split "income ≤ 41?". Does it beat "owns a home?"?
  2. 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?
  3. Harder: turn best_split into a recursive build_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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A node has 6 examples that repaid and 4 that defaulted. What is its Gini impurity?

  2. Your unlimited decision tree reaches 100% training accuracy and 88% on new data, while a depth-2 tree gets 90%. What is happening?

  3. The true boundary between classes is x₁ + x₂ > 10. Why does a decision tree struggle with it?

  4. House prices rise beyond anything in the training data. What will a regression tree predict for these new houses?

  5. Why do trees choose splits with Gini or entropy rather than the plain error rate?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Decision Forests course

Google · Beginner · Free

A short, clear course on decision trees, random forests and gradient-boosted trees, with diagrams.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Docs

scikit-learn: Decision Trees

scikit-learn · Intermediate · Free

How scikit-learn grows, prunes and visualises trees, with practical tips on depth and leaf size.

Book

Interpretable Machine Learning

Christoph Molnar · Intermediate · Free

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