Sign in

Decision tree

Decision tree (Classification and Regression Trees, CART)

A CART decision tree: a sequence of yes or no tests on single features that ends in a prediction at each leaf.

Overview

A decision tree predicts by asking a series of simple questions, each of the form: is this feature at most some value? Each answer sends the row left or right, and the last node reached, called a leaf, gives the prediction. The tree is built from the top. At each node it tries every feature and every cut point and picks the one that makes the two resulting groups as pure as possible, meaning each group holds mostly one class or similar target values. It then repeats the process inside each group. The result reads like a set of rules, and it does not care about the scale of the features.

A short history

Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone published Classification and Regression Trees in 1984, giving the CART procedure of binary splits, impurity measures and pruning. Ross Quinlan developed the related ID3 algorithm in 1986 and later C4.5. Trees mattered because their output is a set of rules that a person can read, and they later became the building block of random forests and gradient boosting.

How it works

  1. Start with all training rows in the root node.
  2. For each feature, sort the rows and consider a cut at every midpoint between consecutive distinct values.
  3. For each cut, compute the impurity of the left and right groups (Gini or entropy for classes, variance for regression) and their weighted average.
  4. Choose the cut with the largest drop in impurity. If no cut passes min_samples_leaf and min_impurity_decrease, make the node a leaf.
  5. Split the rows and repeat inside each child, until max_depth or min_samples_split stops the growth.
  6. At a leaf, predict the majority class (or class shares) for classification, or the mean target for regression.

Watch out for

  • A tree grown without limits keeps splitting until every leaf is pure, which memorises noise. There is no pruning after growth here, so set max_depth or min_samples_leaf.
  • Small changes in the data can change the top split and with it the whole tree. Single trees are unstable, which is why ensembles average many of them.
  • Each split is greedy: it is the best single step, not part of a best overall plan. On XOR-like patterns the first split gains almost nothing, so min_impurity_decrease can stop growth too early.
  • Splits are parallel to the axes. A diagonal boundary has to be approximated by a staircase of many small splits.

Use cases

When to use it

When the model must be readable as rules, when features are on mixed scales, or as the base learner of forests and boosting.

In industry

Healthcare
Triage rules: a short sequence of yes or no questions on vital signs that sorts patients into risk groups.
Lending
Credit policy rules that staff and auditors can read, showing exactly why an application was accepted or declined.
Customer service
Routing and next-step rules learned from past cases and then reviewed by the people who apply them.

Choosing it: what must hold

  • Tabular data with a class or number to predict.
  • A need to show or audit the exact rule behind each prediction.
  • A depth limit or pruning, because an unrestricted tree memorises its training data.

When to choose something else

IfUse instead
Accuracy matters more than a readable rule setA random forest, XGBoost or LightGBM
The relationship is smooth and close to linearLinear regression or logistic regression
Small changes in the data should not change the model muchA random forest, which averages many trees

Math foundations

  1. Gini impurity

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

    The chance that two rows drawn at random from the node (with replacement) have different classes. It is 0 for a pure node and largest when the classes are equally mixed.

  2. Entropy

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

    The average number of bits needed to name the class of a row in the node. Like Gini it is 0 for a pure node. The two usually choose similar splits.

  3. Variance, for regression

    V=1n∑i=1nyi2−yˉ 2V = \frac{1}{n} \sum_{i=1}^{n} y_i^2 - \bar{y}^{\,2}

    The mean squared distance of the targets from their mean. Predicting the mean at a leaf gives exactly this squared error.

  4. Impurity decrease of a split

    Δ=I(parent)−nLn I(left)−nRn I(right)\Delta = I(\text{parent}) - \frac{n_L}{n}\, I(\text{left}) - \frac{n_R}{n}\, I(\text{right})

    How much purer the children are than the parent, with each child weighted by its share of the rows. The tree picks the split with the largest Δ\Delta. With entropy this is called the information gain.

  5. Feature importance

    imp⁡(j)  ∝∑nodes t that split on jntN Δt\operatorname{imp}(j) \;\propto \sum_{\text{nodes } t \text{ that split on } j} \frac{n_t}{N}\, \Delta_t

    The total impurity decrease credited to feature jj, each node weighted by the share of training rows that reach it. The values are scaled to sum to 1.

Symbols

pkp_k
share of the node's rows that belong to class k
KK
number of classes
yi,yˉy_i, \bar{y}
target of row i and the mean target in the node
II
the chosen impurity: Gini, entropy or variance
n,nL,nRn, n_L, n_R
rows in the node, in its left child and in its right child
Δ\Delta
impurity decrease of a split
NN
total number of training rows
ntn_t
number of rows that reach node t

Worked by hand

A node holds 10 rows, 5 of class A and 5 of class B. A candidate split sends 4 rows left (all A) and 6 rows right (1 A and 5 B). Use Gini.

Gparent=1−(0.52+0.52)=0.5G_{\text{parent}} = 1 - (0.5^2 + 0.5^2) = 0.5
Gleft=1−(12+02)=0G_{\text{left}} = 1 - (1^2 + 0^2) = 0
Gright=1−((16)2+(56)2)=1−2636=0.278G_{\text{right}} = 1 - \left( \left(\tfrac{1}{6}\right)^2 + \left(\tfrac{5}{6}\right)^2 \right) = 1 - \tfrac{26}{36} = 0.278
Δ=0.5−410⋅0−610⋅0.278=0.5−0.167=0.333\Delta = 0.5 - \tfrac{4}{10} \cdot 0 - \tfrac{6}{10} \cdot 0.278 = 0.5 - 0.167 = 0.333

The split removes two thirds of the impurity. The left child is pure and becomes a leaf, and the right child still has one misplaced row that a further split could isolate.

Visual example

Loading the example.

Try this

  • Depth 1 is a single cut. Add depth one step at a time.
  • At depth 6 on the moons data, look for regions drawn around single points.

Code sample

import numpy as np
from impl import DecisionTree
from config import DecisionTreeConfig

rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(400, 2))
y = (X[:, 0] * X[:, 1] > 0).astype(int)                 # XOR pattern
tree = DecisionTree(DecisionTreeConfig(criterion="gini", max_depth=4)).fit(X, y)
print((tree.predict(X) == y).mean())                    # training accuracy
print(tree.feature_importances_)
print(tree.export_text(["a", "b"]).splitlines()[0])     # the root test
Read the implementation (156 lines)
"""DecisionTree: CART decision tree for classification and regression.

NumPy only. The tree is grown top down: at each node every feature and every midpoint between consecutive
distinct values is tried, and the split with the largest impurity decrease is kept. Candidate splits of one
feature are scored together from cumulative sums over the sorted rows, so a node costs O(d * n log n).
"""
from __future__ import annotations

import numpy as np

try:
    from .config import DecisionTreeConfig
except ImportError:  # run from the template's own folder
    from config import DecisionTreeConfig


class DecisionTree:
    """Binary tree of `feature <= threshold` tests. Leaves hold class probabilities or a mean value."""

    def __init__(self, config: DecisionTreeConfig | None = None) -> None:
        self.config = config or DecisionTreeConfig()
        self.tree_: dict | None = None            # nested dicts: leaf {"value", "n"} or split {..., "left", "right"}
        self.classes_: np.ndarray | None = None
        self.feature_importances_: np.ndarray | None = None  # impurity decrease per feature, sums to 1
        self.n_leaves_ = 0

    # ---- impurity --------------------------------------------------------------------------------------
    def _impurity(self, S: np.ndarray, n: np.ndarray) -> np.ndarray:
        """Impurity of groups described by their statistics.

        S: (m, k) per-group class counts (classification) or (m, 2) sums of y and y^2 (regression).
        n: (m,) group sizes, all above zero. Returns (m,).
        """
        if self.config.criterion == "mse":
            return np.maximum(S[:, 1] / n - (S[:, 0] / n) ** 2, 0.0)
        p = S / n[:, None]
        if self.config.criterion == "gini":
            return 1.0 - np.sum(p**2, axis=1)
        logp = np.zeros_like(p)
        np.log2(p, out=logp, where=p > 0)
        return -np.sum(p * logp, axis=1)

    def _best_split(self, X: np.ndarray, T: np.ndarray):
        """Best (gain, feature, threshold) for the rows of a node, or None when no valid split exists.

        X: (n, d). T: (n, k) per-row statistics whose column sums feed `_impurity`.
        """
        n, d = X.shape
        leaf_min = self.config.min_samples_leaf
        total = T.sum(axis=0)
        parent = self._impurity(total[None, :], np.array([float(n)]))[0]
        best = None
        for j in range(d):
            order = np.argsort(X[:, j], kind="stable")
            xs = X[order, j]
            left = np.cumsum(T[order], axis=0)[:-1]            # stats of rows 0..i for a cut after row i
            n_left = np.arange(1, n, dtype=float)
            valid = (xs[1:] > xs[:-1]) & (n_left >= leaf_min) & (n - n_left >= leaf_min)
            if not valid.any():
                continue
            left, n_left = left[valid], n_left[valid]
            child = (n_left * self._impurity(left, n_left) + (n - n_left) * self._impurity(total - left, n - n_left)) / n
            i = int(np.argmin(child))
            gain = parent - child[i]
            if best is None or gain > best[0] + 1e-12:
                cut = np.flatnonzero(valid)[i]
                best = (float(gain), j, float((xs[cut] + xs[cut + 1]) / 2.0))
        return best

    # ---- growing ---------------------------------------------------------------------------------------
    def _grow(self, X: np.ndarray, T: np.ndarray, depth: int, n_total: int) -> dict:
        cfg = self.config
        n = len(X)
        value = T.sum(axis=0) / n if cfg.criterion != "mse" else np.array([T[:, 0].mean()])
        node = {"value": value, "n": n}
        if (cfg.max_depth is not None and depth >= cfg.max_depth) or n < cfg.min_samples_split:
            self.n_leaves_ += 1
            return node
        split = self._best_split(X, T)
        if split is None or split[0] <= cfg.min_impurity_decrease:
            self.n_leaves_ += 1
            return node
        gain, feature, threshold = split
        self._importance[feature] += gain * n / n_total
        go_left = X[:, feature] <= threshold
        node.update(feature=feature, threshold=threshold,
                    left=self._grow(X[go_left], T[go_left], depth + 1, n_total),
                    right=self._grow(X[~go_left], T[~go_left], depth + 1, n_total))
        return node

    def fit(self, X: np.ndarray, y: np.ndarray) -> "DecisionTree":
        """Grow the tree. X: (n, d) numeric features. y: (n,) labels (gini, entropy) or values (mse)."""
        X = np.asarray(X, dtype=float)
        if self.config.criterion == "mse":
            y = np.asarray(y, dtype=float)
            T = np.column_stack([y, y**2])
        else:
            self.classes_, idx = np.unique(np.asarray(y), return_inverse=True)
            T = np.eye(len(self.classes_))[idx]
        self._importance = np.zeros(X.shape[1])
        self.n_leaves_ = 0
        self.tree_ = self._grow(X, T, 0, len(X))
        total = self._importance.sum()
        self.feature_importances_ = self._importance / total if total > 0 else self._importance
        return self

    # ---- prediction ------------------------------------------------------------------------------------
    def _leaf_values(self, X: np.ndarray) -> np.ndarray:
        """Value vector of the leaf each row lands in. X: (n, d) -> (n, k)."""
        X = np.asarray(X, dtype=float)
        out = np.zeros((len(X), len(self.tree_["value"])))
        stack = [(self.tree_, np.arange(len(X)))]
        while stack:
            node, rows = stack.pop()
            if "feature" not in node or len(rows) == 0:
                out[rows] = node["value"]
                continue
            go_left = X[rows, node["feature"]] <= node["threshold"]
            stack.append((node["left"], rows[go_left]))
            stack.append((node["right"], rows[~go_left]))
        return out

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Class shares of the leaf each row lands in. X: (n, d) -> (n, n_classes). Classification only."""
        if self.config.criterion == "mse":
            raise ValueError("predict_proba is not defined for a regression tree")
        return self._leaf_values(X)

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Majority class (classification) or mean target (regression) of the leaf. X: (n, d) -> (n,)."""
        values = self._leaf_values(X)
        return values[:, 0] if self.config.criterion == "mse" else self.classes_[values.argmax(axis=1)]

    def depth(self) -> int:
        """Number of splits on the longest path from the root to a leaf."""
        def walk(node: dict) -> int:
            return 0 if "feature" not in node else 1 + max(walk(node["left"]), walk(node["right"]))
        return walk(self.tree_)

    def export_text(self, feature_names: list | None = None) -> str:
        """The tree as indented text, one line per node."""
        lines: list[str] = []

        def walk(node: dict, indent: str) -> None:
            if "feature" not in node:
                shown = float(node["value"][0]) if self.config.criterion == "mse" else self.classes_[node["value"].argmax()]
                lines.append(f"{indent}-> {shown} (n={node['n']})")
                return
            name = feature_names[node["feature"]] if feature_names else f"x[{node['feature']}]"
            lines.append(f"{indent}{name} <= {node['threshold']:.4g}")
            walk(node["left"], indent + "  ")
            lines.append(f"{indent}{name} > {node['threshold']:.4g}")
            walk(node["right"], indent + "  ")

        walk(self.tree_, "")
        return "\n".join(lines)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Fit DecisionTree on the XOR-pattern data from the README with max_depth set to 1, 2 and 4. For each, print the training accuracy, depth() and export_text(["a", "b"]). Explain why depth 1 is close to chance, and read feature_importances_ for the deepest tree.

Check on learning

  1. Why does a decision tree give the same splits whether a feature is measured in metres or in millimetres, when a KNN or a neural network would not?
    A way to think about it

    A split only asks which rows fall on each side of a cut. Check whether rescaling a feature changes the order of the rows.

  2. On the XOR pattern, no single split improves purity much, yet two levels solve the problem. What does that tell you about greedy growth and about stopping rules based on the gain of one split?
    A way to think about it

    Compute the class mix on each side of any first cut. Then consider what a rule that demands a minimum gain would do at the root.

  3. A tree with no depth limit reaches 100 percent training accuracy. Why is that not evidence of a good model?
    A way to think about it

    Think about what a leaf holding a single row has learned, and what happens when a new row lands there.

  4. Two features are almost identical copies of each other. How will the importance be shared between them, and what does that mean for reading the importances?
    A way to think about it

    At each node only one of them can be chosen, and after that split the other has little left to add. The choice between them can be close to arbitrary.

  5. Gini and entropy both measure impurity. In what situation could they prefer different splits?
    A way to think about it

    Compare how each behaves for a node at 90 to 10 and at 99 to 1. Entropy rises more steeply near purity.