Decision Trees: Entropy, Information Gain and Gini, With Python and C++

Grow a CART decision tree in Python, see Gini and entropy disagree, choose the depth honestly and run the trained tree in C++ at 16 ns per row.

Breast tumours plotted on two cell measurements over the rectangular benign and malignant regions carved out by a small decision tree.

scikit-learn’s DecisionTreeClassifier, run 20 times on the same 455 breast tumours with nothing changed but random_state, grew 20 different trees, and they classified anywhere from 103 to 109 of the same 114 test tumours correctly. Nothing was wrong with the library. Several features in the data split the tumours equally well, and when two splits tie, the tree has to pick one at random. That is the most useful thing to know about decision trees: each split is a greedy choice, and small changes upstream change everything below.

This tutorial builds a CART decision tree from scratch in NumPy: Gini impurity, entropy and information gain by hand, the split search, the stopping rules and the depth chosen by cross-validation. It then exports the trained tree as a text file and as generated C++ code and runs it in C++17 with identical predictions, and measures how fast five implementations predict. Every Python program was run for this article with Python 3.15.2, NumPy 2.5.5 and scikit-learn 1.9.1 on Ubuntu 24.04, and the output was identical on Python 3.13 and on Windows 11 with Python 3.14; the C++ was built with GCC 13.3, Clang 18.1 and MSVC with warnings as errors. Every output block on this page is captured from the companion repositories.

What Is a Decision Tree?

A decision tree is a supervised learning model that predicts by asking a sequence of yes-or-no questions about the features, such as “is worst perimeter at most 114.4?”, and following the answers down to a leaf that holds the prediction. Training grows the tree from the top: at each node it picks the question that best separates the classes (measured by a drop in Gini impurity or entropy) and repeats on each side until a stopping rule ends the branch.

The algorithm used here and in scikit-learn is CART (Classification and Regression Trees, Breiman, Friedman, Olshen and Stone, 1984): every split is binary and tests one numeric feature against a threshold. Trees need no feature scaling, handle interactions between features without extra work and can be read as rules, which makes them a common first model for tabular data and the building block of random forests and gradient boosting. In Python, the standard implementation is scikit-learn’s DecisionTreeClassifier, which this article rebuilds by hand and then compares against.

When to Use a Decision Tree (and When Not To)

SituationGood fit?Why
Tabular data with numeric and encoded featuresYesOne threshold per question; no scaling or distance needed
You need to explain every predictionYesA prediction is a short list of comparisons that a person can check
Features on very different scalesYesRescaling a feature moves its thresholds but never changes a split (measured below)
Interactions between featuresYesA question asked only on one branch is an interaction, found automatically
You need the best accuracy from tabular dataUse an ensembleRandom forests and gradient boosting combine many trees and are usually more accurate
The data changes a little between runsWith careOne tree can change completely when a few rows change (measured below)
Smooth or linear relationshipsRarelyA tree approximates a straight line with a staircase of steps
The model must run in C, C++ or on a microcontrollerYesA trained tree is a handful of comparisons; it can be compiled into plain code (shown below)

How a Decision Tree Is Grown

  1. Start with all training rows at the root.
  2. Measure the impurity of the node: how mixed its classes are, with Gini or entropy.
  3. Try every split. For each feature, sort the rows and try a threshold halfway between each pair of neighboring distinct values.
  4. Keep the best split, the one that lowers the weighted impurity of the two children the most.
  5. Recurse on the left rows and on the right rows.
  6. Stop when a node is pure, reaches the maximum depth or has too few rows; the node becomes a leaf that predicts its majority class.

In pseudocode:

grow(rows, depth):
    if rows are pure or depth == max_depth or len(rows) < min_samples_split:
        return leaf(majority class of rows)
    best = None
    for each feature f:
        for each threshold t halfway between neighboring values of f:
            gain = impurity(rows) - weighted impurity(rows with f <= t, rows with f > t)
            keep (f, t) if gain is the largest so far     # ties: lower feature, lower t
    return node(best, grow(left rows, depth + 1), grow(right rows, depth + 1))

predict(x): start at the root; go left if x[f] <= t, else right; return the leaf's class

The Math: Gini Impurity, Entropy and Information Gain

Gini impurity

For a node whose rows fall into K classes with proportions p1 to pK:

Gini impurity is the probability 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: 0.5 for two classes.

Entropy

Entropy measures, in bits, how uncertain the class of a random row from the node is. It is also 0 for a pure node, and 1 bit for an even two-class mix. Both measures rise and fall together, but not in proportion, which is why they can disagree about which split is best.

Information gain (impurity decrease)

A split sends nL of the node’s n rows left and nR right. Its quality is how much it lowers the impurity I, weighting each child by its share of the rows:

With entropy as I, this is called information gain; with Gini, it is the Gini decrease. The tree takes the split with the largest decrease. Weighting by the children’s sizes matters: a split that isolates one row in a perfectly pure child barely changes the weighted impurity, unless that row was the main source of the mixing.

A Worked Example by Hand

Eight customers, sorted by how many months they have been customers, and whether they cancelled (1) or stayed (0); a small, made-up example chosen so that the two measures disagree:

Months12345678
Cancelled00001001

The root. Two of eight cancelled, so p = (0.75, 0.25). Gini is 1 − 0.75² − 0.25² = 0.375; entropy is −0.75 log₂ 0.75 − 0.25 log₂ 0.25 = 0.811 bits.

Split at months ≤ 4.5. The left four are pure (impurity 0); the right four are two and two (Gini 0.5, entropy 1). The weighted child impurity is 4/8 × 0.5 = 0.25 for Gini and 4/8 × 1 = 0.5 for entropy, so the decrease is 0.375 − 0.25 = 0.125 (Gini) and 0.811 − 0.5 = 0.311 (entropy).

Split at months ≤ 7.5. The left seven hold one cancellation (Gini 1 − (6/7)² − (1/7)² = 0.245; entropy 0.592); the right one is pure. The decrease is 0.375 − 7/8 × 0.245 = 0.161 (Gini) and 0.811 − 7/8 × 0.592 = 0.294 (entropy).

Gini prefers 7.5; entropy prefers 4.5. The program below checks all seven candidate splits and fits a one-split tree with each measure:

"""The article's worked example: eight customers, one feature, two impurity measures.

Gini and entropy rank the seven possible splits differently, so trees grown
with each one start with a different question.
"""

import numpy as np

from tree import Criterion, DecisionTreeClassifier, impurity

months = np.arange(1.0, 9.0)  # months as a customer
left_service = np.array([0, 0, 0, 0, 1, 0, 0, 1])  # 1 = cancelled

parent = np.bincount(left_service, minlength=2).astype(float)
print(f"all 8 customers: {int(parent[1])} cancelled")
print(
    f"gini {impurity(parent, 'gini'):.4f}, entropy {impurity(parent, 'entropy'):.4f} bits"
)

print("\nsplit         left    right   gini gain  entropy gain")
for i in range(1, 8):
    threshold = (months[i - 1] + months[i]) / 2
    a = np.bincount(left_service[:i], minlength=2).astype(float)
    b = np.bincount(left_service[i:], minlength=2).astype(float)
    gains = []
    for criterion in ("gini", "entropy"):
        child = (i * impurity(a, criterion) + (8 - i) * impurity(b, criterion)) / 8
        gains.append(float(impurity(parent, criterion) - child))
    print(
        f"months <= {threshold:.1f}  {int(a[1])} of {i}  {int(b[1])} of {8 - i}"
        f"  {gains[0]:9.4f}  {gains[1]:12.4f}"
    )

X = months.reshape(-1, 1)
criteria: tuple[Criterion, ...] = ("gini", "entropy")
print()
for criterion in criteria:
    root = DecisionTreeClassifier(criterion, max_depth=1).fit(X, left_service)
    print(f"{criterion:7} tree's first split: months <= {root.threshold_[0]:.1f}")

Output:

all 8 customers: 2 cancelled
gini 0.3750, entropy 0.8113 bits

split         left    right   gini gain  entropy gain
months <= 1.5  0 of 1  2 of 7     0.0179        0.0560
months <= 2.5  0 of 2  2 of 6     0.0417        0.1226
months <= 3.5  0 of 3  2 of 5     0.0750        0.2044
months <= 4.5  0 of 4  2 of 4     0.1250        0.3113
months <= 5.5  1 of 5  1 of 3     0.0083        0.0157
months <= 6.5  1 of 6  1 of 2     0.0417        0.0738
months <= 7.5  1 of 7  1 of 1     0.1607        0.2936

gini    tree's first split: months <= 7.5
entropy tree's first split: months <= 4.5
<= 1.5 <= 2.5 <= 3.5 <= 4.5 <= 5.5 <= 6.5 <= 7.5 candidate split on months as a customer 0% 10% 20% 30% 40% 50% 60% share of the impurity removed gini picks months <= 7.5 entropy picks months <= 4.5 Two impurity measures, two different first questions Gini entropy
Figure 1: The eight-customer example. Each bar is the share of the node’s impurity that a split removes. Gini prefers cutting off the last customer (months <= 7.5); entropy prefers the clean group of four (months <= 4.5).

Gini rewards the split that leaves one large, almost pure group (7 customers, 1 cancellation), because squaring the proportions makes a node with 6/7 of one class look nearly clean. Entropy penalizes that remaining uncertainty more and prefers the split with a perfectly clean group of four. On real data the two usually agree on most splits; on the breast cancer data below they produced trees that agree on 100 of 114 test predictions.

Decision Tree in Python From Scratch

The tree lives in tree.py and needs only NumPy. Impurity works on class counts, so the same function scores a single node or every candidate split at once:

def impurity(counts: FloatArray, criterion: Criterion) -> FloatArray:
    """Gini or entropy (in bits) of class counts; counts has classes on the last axis."""
    n = counts.sum(axis=-1, keepdims=True)
    p = np.divide(counts, n, out=np.zeros_like(counts), where=n > 0)
    if criterion == "gini":
        result: FloatArray = 1.0 - (p * p).sum(axis=-1)
        return result
    with np.errstate(divide="ignore", invalid="ignore"):
        terms = np.where(p > 0, p * np.log2(p), 0.0)
    entropy: FloatArray = -terms.sum(axis=-1)
    return entropy

The split search sorts the rows by each feature, builds the class counts on the left of every position with a cumulative sum and scores all positions in one vectorized step. Thresholds sit halfway between neighboring distinct values, computed as a / 2 + b / 2 exactly as scikit-learn does, and positions that would leave fewer than min_samples_leaf rows on a side are skipped:

def best_split(
    X: FloatArray, y: IntArray, n_classes: int, criterion: Criterion, min_leaf: int
) -> Split | None:
    """The split of these rows with the largest impurity decrease, or None."""
    n = len(y)
    parent = float(
        impurity(np.bincount(y, minlength=n_classes).astype(float), criterion)
    )
    best: Split | None = None
    for f in range(X.shape[1]):
        order = np.argsort(X[:, f], kind="stable")
        x = X[order, f]
        onehot = np.eye(n_classes)[y[order]]
        left = np.cumsum(onehot, axis=0)[:-1]  # class counts of rows 0..i
        right = left[-1] + onehot[-1] - left
        n_left = np.arange(1, n, dtype=float)
        valid = (x[1:] > x[:-1]) & (n_left >= min_leaf) & (n - n_left >= min_leaf)
        if not valid.any():
            continue
        child = (
            n_left * impurity(left, criterion)
            + (n - n_left) * impurity(right, criterion)
        ) / n
        gain = np.where(valid, parent - child, -np.inf)
        i = int(np.argmax(gain))  # the first maximum: the lowest threshold
        if best is None or gain[i] > best.gain:
            # halfway between the two values, computed as scikit-learn does
            threshold = x[i] / 2.0 + x[i + 1] / 2.0
            best = Split(float(gain[i]), f, float(threshold))
    return best

fit grows the tree recursively and stores it in parallel arrays (feature, threshold, left child, right child and class counts per node), the same layout scikit-learn uses:

        def grow(rows: IntArray, depth: int) -> int:
            node = len(feature)
            c = np.bincount(codes[rows], minlength=k).astype(float)
            feature.append(-1)
            threshold.append(0.0)
            left.append(-1)
            right.append(-1)
            counts.append(c)
            depth_of.append(depth)
            stop = (
                (self.max_depth is not None and depth >= self.max_depth)
                or len(rows) < self.min_samples_split
                or len(rows) < 2 * self.min_samples_leaf
                or (c > 0).sum() == 1  # pure
            )
            if stop:
                return node
            split = best_split(
                X_arr[rows], codes[rows], k, self.criterion, self.min_samples_leaf
            )
            if split is None:
                return node
            go_left = X_arr[rows, split.feature] <= split.threshold
            if go_left.all() or not go_left.any():  # cannot happen with exact midpoints
                return node
            feature[node], threshold[node] = split.feature, split.threshold
            left[node] = grow(rows[go_left], depth + 1)
            right[node] = grow(rows[~go_left], depth + 1)
            return node

Prediction routes all rows at once, one level per loop iteration, until every row has reached a leaf:

    def apply(self, X: ArrayLike) -> IntArray:
        """The leaf each row lands in."""
        Q = np.asarray(X, dtype=np.float64)
        if Q.ndim != 2 or Q.shape[1] != self.n_features_in_:
            raise ValueError("X must be 2-D with as many columns as the training data")
        node = np.zeros(len(Q), dtype=np.int64)
        while True:
            inner = self.feature_[node] >= 0
            if not inner.any():
                return node
            rows = np.nonzero(inner)[0]
            n = node[rows]
            go_left = Q[rows, self.feature_[n]] <= self.threshold_[n]
            node[rows] = np.where(go_left, self.left_[n], self.right_[n])

The repository’s 19 tests check impurity values, the worked example, every chosen split against a brute-force search over all features and thresholds, both tie rules, thresholds and values exactly on a threshold, the depth and size limits, string labels, scaling, the exported files and the generated C++ code, a benchmark checksum shared with C++, and input validation. Against scikit-learn they check identical trees (same features, thresholds and node sizes) wherever no two splits tie, and the same depth-3 entropy tree on the breast cancer data for 10 random seeds. A separate script re-applies 17 plausible bugs to a copy of the code, from Gini without the “1 −” to < instead of <=; every one makes a test fail.

Decision Trees on a Real Dataset

The Breast Cancer Wisconsin (Diagnostic) data has 569 tumours described by 30 measurements of cell nuclei (UCI Machine Learning Repository), with the same split and labels as the logistic regression article in this series, so the two models can be compared directly.

PropertyValue
SourceWolberg, Mangasarian, Street and Street (1993), UCI Machine Learning Repository, doi:10.24432/C5DW2B; bundled with scikit-learn
LicenseCC BY 4.0
Rows and features569 tumours, 30 numeric features
Labels1 = malignant (212), 0 = benign (357)
Split80/20, stratified, random_state=42: 455 training rows, 114 test rows (42 malignant)
PreprocessingNone: trees do not need scaling
Model selection5-fold cross-validation repeated 10 times on the training rows

The experiment grows Gini and entropy trees with every depth limit from 1 to 8 and with none, scores each by repeated cross-validation and picks the smallest depth whose score is within one standard error of the best, so that a tree is not made larger for a difference the data cannot tell apart:

# Pick the smallest tree within one standard error of the best score.
print("\nsmallest depth within one standard error of the best CV score")
chosen: dict[str, int] = {}
for criterion, rows in table.items():
    best = max(rows, key=lambda r: r["cv"])
    pick = next(r for r in rows if r["cv"] >= best["cv"] - best["se"])
    chosen[criterion] = int(pick["depth"])
    print(
        f"{criterion:8} best {best['cv']:.3f} +/- {best['se']:.3f} at depth "
        f"{int(best['depth']) or 'none'}; chosen depth {int(pick['depth'])} ({pick['cv']:.3f})"
    )

Output:

training rows: 455, test rows: 114 (42 malignant)

cross-validated accuracy (5 folds x 10 repeats) and size of the tree on all training rows
depth  gini CV leaves  train   entropy CV leaves  train
    1    0.905      2  0.930        0.904      2  0.927
    2    0.918      4  0.954        0.907      4  0.927
    3    0.923      8  0.967        0.931      7  0.956
    4    0.923     13  0.982        0.930     12  0.978
    5    0.926     16  0.987        0.929     15  0.991
    6    0.925     19  0.993        0.930     16  0.996
    7    0.924     22  0.996        0.929     17  1.000
    8    0.924     24  1.000        0.929     17  1.000
 none    0.924     24  1.000        0.929     17  1.000

smallest depth within one standard error of the best CV score
gini     best 0.926 +/- 0.004 at depth 5; chosen depth 3 (0.923)
entropy  best 0.931 +/- 0.003 at depth 3; chosen depth 3 (0.931)

test rows: 114
baseline (always benign)      72/114 correct, 42 malignant missed, 0 false alarms
gini, no depth limit         106/114 correct, 5 malignant missed, 3 false alarms
gini, depth 3                103/114 correct, 9 malignant missed, 2 false alarms
entropy, depth 3             107/114 correct, 4 malignant missed, 3 false alarms
gini and entropy trees agree on 100 of 114 test rows

standardized features: same features at every node True, same test predictions True

the entropy tree of depth 3 (class counts: benign, malignant)
|--- worst perimeter <= 114.4
|   |--- worst concave points <= 0.111
|   |   |--- area error <= 45.17
|   |   |   |--- class 0 (237, 1)
|   |   |--- area error >  45.17
|   |   |   |--- class 0 (4, 3)
|   |--- worst concave points >  0.111
|   |   |--- worst texture <= 25.73
|   |   |   |--- class 0 (26, 2)
|   |   |--- worst texture >  25.73
|   |   |   |--- class 1 (13, 22)
|--- worst perimeter >  114.4
|   |--- mean concave points <= 0.05008
|   |   |--- worst texture <= 28.97
|   |   |   |--- class 0 (5, 1)
|   |   |--- worst texture >  28.97
|   |   |   |--- class 1 (0, 6)
|   |--- mean concave points >  0.05008
|   |   |--- class 1 (0, 135)
yes no yes no yes no yes no yes no yes no benign 237 / 1 benign 4 / 3 area error <= 45.17 benign 26 / 2 malignant 13 / 22 worst texture <= 25.73 worst concave points <= 0.111 benign 5 / 1 malignant 0 / 6 worst texture <= 28.97 malignant 0 / 135 mean concave points <= 0.05008 worst perimeter <= 114.4 The chosen tree: entropy, depth 3, 7 leaves
Figure 2: The tree chosen by cross-validation, trained on the 455 training tumours. Each leaf shows its prediction and the training tumours that reach it, benign / malignant. It classifies 107 of the 114 test tumours correctly.
1 2 3 4 5 6 7 8 none maximum depth 0.88 0.90 0.92 0.94 0.96 0.98 1.00 accuracy chosen: depth 3 Deeper trees fit the training rows, not new tumours gini, training rows gini, cross-validation entropy, training rows entropy, cross-validation
Figure 3: Accuracy on the training rows (dashed) and in 5-fold cross-validation repeated 10 times (solid) for every depth limit. Training accuracy climbs to 100%; cross-validated accuracy stays between 0.90 and 0.93 from depth 2 on.

Reading the results:

  • A fully grown tree memorizes the training rows. Without a depth limit, both trees classify 100% of the training rows correctly, but cross-validation puts them at 0.924 (Gini) and 0.929 (entropy). Training accuracy keeps rising with depth; cross-validated accuracy stops improving at depth 3.
  • Depth 3 is enough. The entropy tree of depth 3 scored the best cross-validated accuracy, 0.931, with 7 leaves instead of 17. It classified 107 of the 114 test tumours correctly and missed 4 of the 42 malignant ones. It is chosen over the Gini tree because its cross-validated score is higher.
  • Gini and entropy made different trees. At depth 3 the Gini tree reached 0.923 in cross-validation and 103 of 114 on the test rows, missing 9 malignant tumours; the two depth-3 trees agree on 100 of the 114 test predictions. Neither measure is better in general; here the choice was made by cross-validation, as it should be.
  • Scaling changes nothing. Standardizing all 30 features gave the same feature at every node and the same test predictions; only the thresholds moved. Compare k-nearest neighbors, where one unscaled feature dominated every distance.
  • A single tree is not the most accurate model here. On the same 114 test tumours, logistic regression classified 110 correctly. Trees trade some accuracy for rules a person can read, and ensembles of trees win the accuracy back (see the stability section).

The printed tree has one split that changes nothing: below “worst concave points ≤ 0.111”, the question “area error ≤ 45.17” separates 237 benign and 1 malignant tumour from 4 benign and 3 malignant, and both sides predict benign. Growing a tree lowers impurity, not the error rate, so it keeps such splits. They do change the leaf probabilities, which matters if you use predict_proba.

Why a Single Tree Is Unstable

The stability experiment measures how much one tree depends on details of its training data:

scikit-learn, default settings, random_state = 0 to 19:
  20 different trees; test rows correct: 103 to 109 of 114

this article's tree (gini, no depth limit) on 200 bootstrap samples:
  feature tested at the root:
    worst perimeter        100
    worst concave points    36
    worst radius            28
    mean concave points     27
    worst area               9
  test rows correct per tree: mean 104.5, min 96, max 110 of 114
  majority vote of the 200 trees: 109 of 114
0 20 40 60 80 100 trees, out of 200, with this feature at the root worst perimeter worst concave points worst radius mean concave points worst area 100 36 28 27 9 Resample the rows and the first question changes
Figure 4: The feature tested at the root of 200 trees, each grown on a bootstrap sample of the 455 training tumours. Five different features win the root; on the test rows the single trees range from 96 to 110 correct of 114, and their majority vote gets 109.

The same data, 20 different trees. scikit-learn’s documentation explains why: the features are randomly permuted at each split, and when several splits improve the criterion by exactly the same amount, one of them has to be selected at random, so random_state has to be fixed for deterministic fitting. In this data, radius, perimeter and area measure the same size three ways and often produce identical splits of the training rows; they disagree only on new rows. The from-scratch tree avoids the randomness by always taking the lower feature index, but that is a convention, not a better answer.

Different rows, different roots. On 200 bootstrap samples (455 rows drawn with replacement), five different features won the root, and the single trees ranged from 96 to 110 correct of 114. Their majority vote got 109. Averaging many trees grown on resampled data is called bagging, and adding a random choice of features at each split turns it into a random forest: the instability of single trees is exactly what those ensembles exploit.

Running the Trained Tree in C++

A trained tree is a few numbers per node, so it is easy to run anywhere. The export step writes it two ways. The first is a table with one line per node, which a program loads at run time:

# decision tree: 13 nodes, 30 features
# node feature threshold left right class
0 22 114.44999999999999 1 8 0
1 27 0.11099999999999999 2 5 0
2 13 45.17 3 4 0
3 -1 0.0 -1 -1 0
4 -1 0.0 -1 -1 0
5 21 25.735 6 7 0
6 -1 0.0 -1 -1 0
7 -1 0.0 -1 -1 1
8 7 0.050085 9 12 1
9 21 28.97 10 11 1
10 -1 0.0 -1 -1 0
11 -1 0.0 -1 -1 1
12 -1 0.0 -1 -1 1

The second is C++ source with the tree as nested if statements, which compiles into the program with no file to load and nothing to parse:

// Generated by export.py from the trained decision tree. Do not edit.
#pragma once

namespace generated {

// The predicted class for one row of 30 features.
inline int breast_cancer_tree(const double* x)
{
    if (x[22] <= 114.44999999999999) {  // worst perimeter
        if (x[27] <= 0.11099999999999999) {  // worst concave points
            if (x[13] <= 45.17) {  // area error
                return 0;
            }
            return 0;
        }
        if (x[21] <= 25.735) {  // worst texture
            return 0;
        }
        return 1;
    }
    if (x[7] <= 0.050085) {  // mean concave points
        if (x[21] <= 28.97) {  // worst texture
            return 0;
        }
        return 1;
    }
    return 1;
}

}  // namespace generated

Thresholds are written with Python’s repr, the shortest text that converts back to exactly the same double, and the C++ loader reads them with std::from_chars, which converts correctly rounded. The comparisons therefore give the same answers as in Python, bit for bit; a test feeds both versions values exactly on each threshold and on the next double above it. The generated code also shows the split that changes nothing: under area error, both branches return 0.

The loader checks the file (fields, node order, feature indexes, finite thresholds, children after their parent so the tree cannot loop) and then walks it:

    // The leaf a row lands in.
    std::size_t leaf(const double* x) const
    {
        std::size_t i = 0;
        while (nodes_[i].feature >= 0) {
            const Node& n = nodes_[i];
            i = static_cast<std::size_t>(x[n.feature] <= n.threshold ? n.left : n.right);
        }
        return i;
    }

    int predict(const double* x) const { return nodes_[leaf(x)].label; }

Python and C++ are checked against each other. A plain-Python program with no NumPy reads the same two files as the C++ program, and both repositories compare their output with the same expected file:

tree: 13 nodes, 7 leaves; test rows: 114
correct: 107 of 114
benign:     69 right,  3 called malignant
malignant:  38 right,  4 missed
predictions (1 = malignant):
  010100100010100000100011100111101100001000100101001100010
  001001000110001100001011100001110100010000000010010100001
test row 0 (class 0) follows nodes 0 1 2 3:
  worst_perimeter = 83.74 <= 114.45
  worst_concave_points = 0.08958 <= 0.111
  area_error = 10.5 <= 45.17
  leaf 3: class 0

The C++ tests also check the generated function against the loaded tree on 20,000 rows built from test values and thresholds, the error message for each kind of malformed file, Windows line endings and the benchmark rows. They pass under AddressSanitizer, UndefinedBehaviorSanitizer and Valgrind, and a script that puts 13 deliberate mistakes into a copy of the sources, including one threshold rounded to six digits, confirms that each one is caught. For running other kinds of trained models from C++, see machine learning with C++.

Performance: Predicting With the Tree

The benchmark classifies 1,000,008 rows drawn from the 114 test tumours in a pseudo-random order that both languages generate from the same splitmix64 stream, so every version must produce the same checksum (732426313) before any time is compared. Everything runs on one thread.

The Python side times the plain-Python walk over the node table, this article’s NumPy tree and scikit-learn:

1,000,008 rows, tree depth 3, 7 leaves
checksums: [732426313] (all equal: True)

nanoseconds per row (median of repeated runs), x86_64
pure Python, exported node table         793.8
NumPy, this article's tree               216.9
scikit-learn predict                     133.5

The C++ program, built with GCC 13.3 in Release mode (-O3, CMake’s default), on the same machine:

1000008 rows, tree depth 3, 7 leaves
checksums: loaded 732426313, generated 732426313
nanoseconds per row (median of 7 runs):
  loaded node table         28.17
  generated nested ifs      15.51
1 0 1 1 0 2 1 0 3 nanoseconds per row (log scale, one thread) pure Python, node table NumPy, from scratch scikit-learn predict C++, loaded node table C++, generated ifs 794 ns 217 ns 134 ns 28 ns 16 ns The same tree, the same 1,000,008 predictions
Figure 5: Median time per row to classify 1,000,008 rows drawn from the test tumours with the depth-3 tree, on one thread of one Linux virtual machine. All five give the same predictions.

What the numbers show:

  • A depth-3 tree costs 16 to 28 nanoseconds per row in C++, about 5 to 8 times less than scikit-learn’s predict and about 30 to 50 times less than walking the tree in plain Python. For one prediction at a time, as in a request handler, the difference is larger still, because each call into NumPy or scikit-learn has a fixed overhead that a batch of a million rows hides.
  • The generated code beat the loaded table by about 1.8 times. The comparisons and thresholds are constants in the instruction stream instead of data the processor has to fetch from the node array.
  • The row order matters. In an earlier version of the benchmark the 114 rows simply repeated in order, and the generated function measured about 11 nanoseconds per row instead of 15 to 19 on shuffled rows of the same data: the processor’s branch predictor learned the repeating pattern. Benchmarks of branchy code need data in a realistic order.

These are medians of repeated runs on one Linux virtual machine (Intel Xeon at 2.10 GHz, 2 vCPUs), and they moved between runs: across four runs of the Python benchmark and five of the C++ one, plain Python ranged from 627 to 794 nanoseconds per row, NumPy from 163 to 217, scikit-learn from 112 to 134, the loaded C++ table from 27 to 33 and the generated C++ from 15 to 19. The order of the five never changed. On the Windows 11 desktop used for the Windows checks (Intel Core i7-8700K at 3.70 GHz), the same programs gave plain Python 604, NumPy 160, scikit-learn 95, the loaded C++ table built with MSVC 20 and the generated C++ 13 nanoseconds per row: the same order, with the same checksum. The benchmark measures batch prediction with one small tree on in-memory data; it does not measure deep trees, ensembles, single-row calls or training time.

Complexity

StepCostNotes
Find the best split at a node with n rows and m featuresO(m n log n)Sorting dominates; the scan over thresholds is O(m n)
Grow a balanced treeAbout O(m n log² n)Each level re-sorts its rows; scikit-learn’s implementation avoids some of this work
Predict one rowO(depth)3 comparisons for the depth-3 tree here
MemoryO(number of nodes)13 nodes here; at most 2 n − 1 for a fully grown tree

Prediction cost depends only on the depth, not on the size of the training set, which is the opposite of k-nearest neighbors. The tree itself is a binary tree stored in arrays, the same structure as the binary trees used throughout computer science.

Common Mistakes With Decision Trees

1. Leaving the depth unlimited. scikit-learn’s defaults grow the tree until every leaf is pure. Here that meant 100% training accuracy, 24 leaves and a lower cross-validated score than a 7-leaf tree. Limit max_depth or min_samples_leaf, chosen by cross-validation.

2. Not fixing random_state. Even with every feature considered at every split, scikit-learn breaks ties at random; 20 seeds gave 20 different trees and test scores from 103 to 109 of 114. Fix the seed for reproducible results, and do not read much into one seed’s tree.

3. Reading the tree as the truth about the data. Which correlated feature appears at a node is often a tie broken by chance or by a few rows: five different features won the root over 200 resamples. Use the tree to explain its own predictions, not to rank features.

4. Treating Gini and entropy as interchangeable. They usually agree, but they built different depth-3 trees here, with 9 and 4 malignant tumours missed on the test rows. Try both in cross-validation.

5. Mixing up < and <= when porting a tree. scikit-learn and this article send x <= threshold left. A port that uses <, or that prints thresholds with fewer digits, sends rows that sit exactly on a threshold the wrong way; both mistakes are among the deliberate bugs the tests catch.

ModelDecision boundaryNeeds scalingKey difference from a single tree
Decision treeAxis-aligned rectanglesNoReadable rules; unstable; overfits without limits
Random forestAverage of many treesNoBagging plus random features per split; more accurate and stable, less readable
Gradient boostingSum of many small treesNoTrees fitted one after another to the remaining errors; often the most accurate on tabular data
Logistic regressionA single hyperplaneHelpsSmooth probabilities; weights as odds ratios; no interactions unless added
K-nearest neighborsAny shape, from the dataYesNo training; prediction cost grows with the data

Key Takeaways

  • A decision tree asks one threshold question per node and is grown greedily, taking at each node the split with the largest impurity decrease.
  • Gini and entropy can pick different splits: in the eight-customer example Gini cut off one customer and entropy made a pure group of four.
  • Limit the depth. A fully grown tree scored 100% on its training rows; a depth-3 tree with 7 leaves scored higher in cross-validation and 107 of 114 on the test rows.
  • One tree is unstable. scikit-learn grew 20 different trees from the same data with 20 seeds, and bootstrap samples changed even the root question; averaging trees (bagging, random forests) turns that into accuracy.
  • Trees need no scaling: standardizing every feature left every split and prediction unchanged.
  • A trained tree is easy to deploy: exported as a table or as generated C++, it made the same predictions as Python in 16 to 28 nanoseconds per row.

Conclusion

Decision trees are built from one idea, a greedy search for the question that best separates the classes, and everything else follows from it: the readable rules, the freedom from scaling, the tendency to memorize and the instability when several questions are equally good. On the breast cancer data a depth-3 tree with seven leaves did as well as any larger tree and fits in about twenty lines of generated C++.

The instability is also the way forward. Growing many trees on resampled data and letting them vote, as the 200 bootstrap trees did here, is the idea behind random forests and, with trees fitted to each other’s errors, gradient boosting. More tutorials in this series are collected in the artificial intelligence section.

Source Code and Tests

Python decision tree build status
C++ decision tree build status

The Python programs are in the machine-learning/decision-tree directory of the MYCPLUS Python examples repository, and the C++ version is in the same directory of the C++ examples repository.

Build and test the Python version:

python -m pip install -r requirements-dev.txt
python -m unittest discover -s tests -v
sh run_all.sh

Build and test the C++ version:

cmake -S . -B build
cmake --build build --config Release
ctest --test-dir build -C Release --output-on-failure

What the builds check. The Python build runs on Linux and Windows with Python 3.13, 3.14 and 3.15 and the pinned NumPy and scikit-learn versions: ruff and mypy --strict, the 19 unit tests, exact output of the worked example, the breast cancer experiment and the shared prediction report, the stability experiment and, on Linux, the 17 deliberate bugs. The C++ build runs GCC and Clang with C++17 and C++20 and -Wall -Wextra -pedantic -Werror, the same tests under AddressSanitizer and UndefinedBehaviorSanitizer, MSVC with /W4 /WX /permissive- on Windows, and on Linux the 13 deliberate mistakes. CTest checks that the C++ report matches the Python one byte for byte and that the benchmark’s checksum matches Python’s. The timings themselves are not checked in CI.

What I Verified

CheckUbuntu 24.04Windows 11
Python environmentPython 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1; every Python output on this page captured from these runsWindows 11 (build 26300), Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1
Same programs on Python 3.13.18Identical output for the worked example, the breast cancer experiment, the shared report and the stability experimentNot applicable
19 Python unit tests, ruff, mypy --strictPass, no issuesPass, no issues
Exact output of the worked example, breast cancer experiment and shared reportMatches this pageMatches this page
17 deliberate Python bugsAll 17 caughtAll 17 caught
C++ build and CTestGCC 13.3 and Clang 18.1, C++17 and C++20, warnings as errors: passMSVC (cl.exe 14.44.35229), /W4 /WX /permissive-: build and CTest pass
C++ report identical to Python’sByte for byteByte for byte (CTest)
AddressSanitizer, UBSan, ValgrindClean (GCC)Not applicable
13 deliberate C++ mistakesAll 13 caughtNot applicable
BenchmarkSame checksum in all five implementations; timings as shownSame checksum; Intel Core i7-8700K: plain Python 604 ns, NumPy 160, scikit-learn 95, MSVC C++ loaded 20, generated 13

Not covered: macOS, ARM processors, other library versions, regression trees, categorical splits, missing values and pruning by cost-complexity (ccp_alpha).

Scroll to Top