A Decision Tree from Scratch
Writing a tree yourself turns its hyperparameters from magic words into lines of code you recognise: max_depth is the recursion limit, min_samples_leaf is a check before splitting, and the famous greediness is a for loop that never looks back. This lesson builds CART (Classification And Regression Trees, Breiman and colleagues, 1984), the algorithm behind scikit-learn's trees, in about 50 lines of NumPy, and checks it against DecisionTreeClassifier split for split.
The algorithm
build(node data, depth):
if depth == max_depth, or the node is pure, or it is too small:
return a leaf with the class counts
for every feature j:
sort the node's examples by x_j
for every cut between two different consecutive values:
score = weighted Gini of the two sides
keep the best (feature, threshold); if it does not lower the impurity: return a leaf
split the data, and build(left, depth + 1), build(right, depth + 1)The search costs per node (a sort per feature), and each level of the tree touches every example once, so a tree of depth costs about .
Fast split search with cumulative counts
Re-counting both sides for every threshold would cost per threshold. The trick is to sort once and keep running class counts: after sorting by , the class counts of the left side for every cut position are a cumulative sum of one-hot labels, and the right side is the total minus the left. Gini for all cuts then comes from a few array operations. Ties need care: you may only cut between two different values, otherwise equal values would land on both sides.
For counts summing to , the Gini impurity is , and the score of a cut with examples on the left is
The code
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
def gini_from_counts(counts):
n = counts.sum(axis=-1, keepdims=True)
p = counts / np.maximum(n, 1)
return 1 - (p ** 2).sum(axis=-1)
def best_split(X, y, n_classes):
"""Scan every feature and every threshold; return (feature, threshold, weighted gini)."""
best = (None, None, np.inf)
n = len(y)
for j in range(X.shape[1]):
order = np.argsort(X[:, j], kind="stable")
xs, ys = X[order, j], y[order]
left = np.cumsum(np.eye(n_classes)[ys], axis=0)[:-1] # class counts left of each cut
right = left[-1] + np.eye(n_classes)[ys[-1]] - left # the rest
n_left = np.arange(1, n)
score = (n_left * gini_from_counts(left) + (n - n_left) * gini_from_counts(right)) / n
valid = xs[1:] > xs[:-1] # cut only between different values
if valid.any():
i = np.flatnonzero(valid)[np.argmin(score[valid])]
if score[i] < best[2]:
best = (j, (xs[i] + xs[i + 1]) / 2, score[i])
return best
def build(X, y, n_classes, depth, max_depth, min_samples_leaf=1):
counts = np.bincount(y, minlength=n_classes)
node = {"value": counts}
if depth == max_depth or counts.max() == len(y) or len(y) < 2 * min_samples_leaf:
return node
j, t, score = best_split(X, y, n_classes)
if j is None or score >= gini_from_counts(counts):
return node
mask = X[:, j] <= t
node.update(feature=j, threshold=t,
left=build(X[mask], y[mask], n_classes, depth + 1, max_depth),
right=build(X[~mask], y[~mask], n_classes, depth + 1, max_depth))
return node
def predict_one(node, x):
while "feature" in node:
node = node["left"] if x[node["feature"]] <= node["threshold"] else node["right"]
return node["value"].argmax()
X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
root = build(X_tr, y_tr, 2, 0, max_depth=3)
ours = np.array([predict_one(root, x) for x in X_te])
sk = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_tr, y_tr)
print("root split ours: feature", root["feature"], "threshold", round(root["threshold"], 4))
print("root split sklearn: feature", sk.tree_.feature[0], "threshold", round(sk.tree_.threshold[0], 4))
print("test accuracy ours", round(np.mean(ours == y_te), 3), " sklearn", round(sk.score(X_te, y_te), 3))
print("identical test predictions:", bool(np.all(ours == sk.predict(X_te))))root split ours: feature 22 threshold 106.1
root split sklearn: feature 22 threshold 106.1
test accuracy ours 0.916 sklearn 0.916
identical test predictions: True
Both trees split the root on feature 22 ("worst perimeter") at 106.1 and make identical predictions on all 143 test tumours. Reading the code against the hyperparameters of DecisionTreeClassifier:
| Hyperparameter | Where it lives in the code |
|---|---|
max_depth |
depth == max_depth stops the recursion |
min_samples_leaf |
the size check (scikit-learn also refuses cuts that leave fewer on either side) |
criterion |
gini_from_counts; swap in entropy for "entropy" |
max_features |
would sample a subset of range(X.shape[1]) in best_split: the key ingredient of random forests |
splitter="random" |
would draw a random threshold per feature instead of scanning (Extra Trees) |
Two details matter for matching scikit-learn exactly. Thresholds are midpoints between consecutive distinct values, and when two features give exactly the same score scikit-learn breaks the tie by visiting features in a random order (fixed by random_state); on real-valued data exact ties are rare, so the trees agree.
Why greedy?
Finding the smallest tree that fits the data is NP-hard, so CART takes the best split at each node and never revisits it. Greedy splitting can miss structure that only shows up two levels down: the classic case is XOR, where no single split on or reduces impurity, although two levels separate the classes perfectly. In practice the ensembles in the next lessons make up for most of this short-sightedness.
Strengths and limits of the from-scratch version
This tree is correct but slow: Python recursion and a sort per feature per node. scikit-learn's version is written in Cython, sorts once, and handles sample weights, missing values (since version 1.3) and regression. Use the code to understand trees, and the library to train them.
Practice
- Add
min_samples_leafproperly: a cut is valid only if both sides keep at leastmin_samples_leafexamples. Which line changes?
Answer
Combine the valid mask with the size condition: valid = (xs[1:] > xs[:-1]) & (n_left >= min_samples_leaf) & (n - n_left >= min_samples_leaf), and pass min_samples_leaf down to best_split and to the recursive build calls.
- Four points: , , , . What impurity decrease does each single split give, and what does CART do?
Answer
Every split on or leaves one A and one B on each side, so both children have Gini 0.5, the same as the root: a decrease of 0. The code's check score >= gini_from_counts(counts) then makes the root a leaf, although a depth-2 tree would classify all four points. This is greediness failing on XOR (scikit-learn would still split, since it only requires a decrease of at least 0).
Test yourself
Why does the split search only cut between two different consecutive values?
- To save memory
- Equal values must go to the same side, since the test is
- Because Gini is undefined otherwise
- To make the tree balanced
What makes CART greedy?
- It uses all features
- It picks the best split at each node and never revisits earlier splits
- It grows trees to full depth
- It uses the Gini criterion
Which change to best_split turns this tree into the kind used by random forests?
- Use entropy instead of Gini
- Search only a random subset of the features at each node
- Use midpoints as thresholds
- Stop at depth 3