Sub topic 2
Building a tree by recursive partitioning
This chapter assumes you know what features, labels and a training set are, and that you can read basic Python. It also assumes you have seen the parts of a tree: root, internal nodes, branches and leaves. Here we cover the procedure that grows a tree from data. The details of how to score a split (Gini, entropy, information gain) and how to search thresholds efficiently get their own chapters. This one is about the overall loop.
The core idea
A decision tree is built by asking one question about the data, splitting the samples into two groups by the answer, and then repeating the same process on each group. Each group is a smaller copy of the original problem. This is why the method is called recursive partitioning. It is recursive because the procedure calls itself on the pieces. It is partitioning because each split cuts the feature space into non-overlapping regions.
When the process stops, each region becomes a leaf. A leaf stores one prediction, which for classification is usually the most common class among the training samples that landed there.
The algorithm
For a node that holds a set of training samples, the procedure is:
- Check the stopping conditions. If any holds, make this node a leaf and return.
- Search every feature and every candidate threshold for the split that makes the two child groups as pure as possible.
- If the best split does not improve on the current node, make a leaf and return.
- Otherwise, store the chosen feature and threshold in the node, send each sample to the left child (feature value
<=threshold) or the right child (value>threshold), and run the same procedure on each child.
The stopping conditions in this chapter's code are simple: all samples share one label, the depth limit is reached, or there are too few samples to split. The next chapters on stopping criteria and pruning look at these rules in more detail.
Why the choice is greedy
At each node the algorithm picks the split that looks best right now. It does not look ahead to ask whether a mediocre split here would allow excellent splits below. This is a greedy strategy.
Greedy is used because the alternative is too expensive. Finding the smallest tree that classifies the training data perfectly is NP-complete, so no efficient exact method is known. Greedy construction runs fast and usually gives good trees, but it carries two consequences:
- The tree is not guaranteed to be the best possible tree. Two different data samples can give quite different trees.
- A split is never revisited. If an early split is poor, every node below it inherits the problem.
A working implementation
The code below builds a small tree from scratch. It uses Gini impurity as its purity score, which the next chapter explains. For now, read gini as "0 means all labels in the group are the same, larger means more mixed". A split's score is the average impurity of its two children, weighted by how many samples each child holds. Lower is better.
def gini(labels):
n = len(labels)
counts = {}
for y in labels:
counts[y] = counts.get(y, 0) + 1
return 1.0 - sum((c / n) ** 2 for c in counts.values())
def majority(labels):
# sorted() makes ties resolve the same way on every run
return max(sorted(set(labels)), key=labels.count)
def best_split(X, y):
"""Return (score, feature, threshold) for the best split, or None."""
n = len(y)
best = None
for j in range(len(X[0])):
values = sorted(set(row[j] for row in X))
for a, b in zip(values, values[1:]):
t = (a + b) / 2
left = [y[i] for i, row in enumerate(X) if row[j] <= t]
right = [y[i] for i, row in enumerate(X) if row[j] > t]
score = (len(left) * gini(left) + len(right) * gini(right)) / n
if best is None or score < best[0]:
best = (score, j, t)
return best
def build(X, y, depth=0, max_depth=3, min_samples_split=2):
leaf = {"leaf": True, "prediction": majority(y), "n": len(y)}
if len(set(y)) == 1 or depth >= max_depth or len(y) < min_samples_split:
return leaf
split = best_split(X, y)
if split is None: # every feature is constant, so nothing to split on
return leaf
score, j, t = split
if score >= gini(y): # no improvement over this node
return leaf
left_idx = [i for i, row in enumerate(X) if row[j] <= t]
right_idx = [i for i, row in enumerate(X) if row[j] > t]
return {
"leaf": False,
"feature": j,
"threshold": t,
"left": build([X[i] for i in left_idx], [y[i] for i in left_idx],
depth + 1, max_depth, min_samples_split),
"right": build([X[i] for i in right_idx], [y[i] for i in right_idx],
depth + 1, max_depth, min_samples_split),
}
def predict(node, row):
while not node["leaf"]:
side = "left" if row[node["feature"]] <= node["threshold"] else "right"
node = node[side]
return node["prediction"]
def show(node, indent=0):
pad = " " * indent
if node["leaf"]:
print(f"{pad}predict {node['prediction']} (n={node['n']})")
return
print(f"{pad}if x[{node['feature']}] <= {node['threshold']}:")
show(node["left"], indent + 1)
print(f"{pad}else:")
show(node["right"], indent + 1)
X = [[1], [2], [3], [6], [7], [8], [11], [12], [13]]
y = ["A", "A", "A", "B", "B", "B", "C", "C", "C"]
tree = build(X, y)
show(tree)
print(predict(tree, [7]), predict(tree, [12]), predict(tree, [0]))Running it prints:
if x[0] <= 4.5:
predict A (n=3)
else:
if x[0] <= 9.5:
predict B (n=3)
else:
predict C (n=3)
B C AFollowing the run
At the root there are nine samples and three classes. Every candidate threshold is scored. The splits at 4.5 and 9.5 tie at about 0.333, because each isolates one pure class of three and leaves two mixed classes of six. The code uses a strict < comparison, so the first one found (4.5) is kept. The left child contains only class A, so it stops at once. The right child contains B and C. It is searched again and split at 9.5, which separates the classes perfectly, so both grandchildren are pure leaves.
Prediction follows the same path. A sample with x = 7 fails x <= 4.5, passes x <= 9.5, and lands in the B leaf.
Edge cases the recursion must handle
- Candidate thresholds sit between distinct values. The code uses midpoints of neighbouring unique values. Because of this, both children are never empty. A threshold equal to a sample's value would risk putting everything on one side.
- Identical features, different labels. If two samples have the same feature values but different labels, no split can separate them. A node holding only such samples is impure, yet
best_splitreturnsNoneand the node becomes a leaf with a majority vote. Real data with noise produces this case often. - No single split helps. Consider an XOR pattern with points (0,0)→0, (0,1)→1, (1,0)→1, (1,1)→0. Any one split leaves both children as mixed as the parent, so the code's "no improvement" check makes a leaf. A tree that accepted zero-gain splits could still solve this problem with two levels. Libraries differ here. Scikit-learn's default
min_impurity_decreaseof 0.0 does not reject a zero-gain split, so it can fit XOR, while the toy code above cannot. This is a real trade-off. Accepting zero-gain splits finds interactions between features, and it also grows more splits that may only fit noise. - Class ties at a leaf. When two classes have equal counts, a rule must pick one. The code takes the first in sorted order.
- Recursion depth. The depth limit also keeps the recursion shallow. An unlimited tree on
nsamples can reach depth close tonin the worst case, and a naive recursive implementation can hit Python's recursion limit on large, noisy data. Production libraries build trees iteratively. - Cost. Each node scans all features and all thresholds, and this toy version rescans all samples for every threshold. That makes it slow, roughly quadratic in the samples per feature at each node. Sorting once per feature and updating counts as the threshold moves reduces this considerably. That optimization is covered in the chapter on finding the best split.
What the recursion guarantees
Each split sends every sample to exactly one child, so the leaves form a partition of the training data. Every possible input also reaches exactly one leaf, so prediction always returns an answer. If you let the recursion run until every node is pure, the tree classifies the training data perfectly unless identical feature rows carry different labels. That perfect training score is not good news. It is the starting point for the overfitting chapter that follows.
Summary of the working model
| Step | What happens | Where it can go wrong |
|---|---|---|
| Check stop rules | Pure node, depth limit, or too few samples ends the recursion | Rules that are too loose grow huge trees |
| Search splits | Score every feature and midpoint threshold | Cost grows with features and samples |
| Test improvement | Weighted child impurity must beat the parent | Useful interactions (XOR) may be missed |
| Divide and recurse | Samples go left or right, and children are built the same way | Early poor splits cannot be undone |
| Make leaf | Store the majority class and sample count | Ties and noisy labels make the leaf prediction uncertain |
Exercise
Using the build function above, you train on the data X = [[1], [2], [3], [4]] with y = ["A", "A", "B", "B"] and max_depth=0. What does the function return, and why? Then say what the tree looks like with max_depth=1.
Show answer
With max_depth=0, the check depth >= max_depth is true at the root (0 >= 0), so the function returns a single leaf before any split search. The leaf predicts the majority class. The classes tie at two each, so majority picks the first in sorted order, "A", with n=4. With max_depth=1, the root is allowed to split. The best threshold is 2.5, which gives two pure children of two samples each (weighted score 0.0, below the parent's 0.5). Both children are built at depth 1, where depth >= max_depth is true, so they become leaves. The result is a root testing x[0] <= 2.5, a left leaf predicting "A" with n=2, and a right leaf predicting "B" with n=2.