Sub topic 2
Building a tree by recursive partitioning
This chapter assumes you know supervised learning basics (features, labels, training sets), can read short Python, and understand averages and simple proportions. It covers how a tree grows. The impurity formulas and the full split search come in later chapters.
The core idea
A decision tree is built by asking one question at a time. Each question splits the training data into two groups. The same procedure then runs again on each group, and again on the groups that result. This repeated splitting is called recursive partitioning.
The method is greedy. At each node it picks the split that looks best right now, using only the data in that node. It never goes back to change an earlier split, and it does not look ahead to see whether a weaker split now would allow a better one later.
The algorithm
For a node holding a set of training samples:
- Check whether to stop. If all samples share one label, or a stopping rule applies, make the node a leaf.
- Otherwise, try candidate splits on the features and score each one.
- Choose the split with the best score.
- Send the samples to a left child and a right child according to that split.
- Repeat steps 1 to 4 on each child.
A leaf stores a prediction. For classification, this is usually the most common label among the leaf's samples.
A worked example
Suppose we have six samples with one feature, x, and a label y:
| x | 1 | 2 | 3 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|
| y | A | A | B | B | B | B |
At the root, the best threshold is between 2 and 3, at 2.5. Samples with x <= 2.5 go left and contain only A. Samples with x > 2.5 go right and contain only B. Both children are pure, so both stop as leaves. The tree has one split and two leaves.
Now change the label at x = 8 to A. The right child, x > 2.5, holds 3, 7, 8, 9 with labels B, B, A, B. It is mixed, so the algorithm splits it again. The best new threshold is between 7 and 8 or between 8 and 9. Each choice leaves one side impure or isolates a single sample, so the tree needs a further split to separate the A at x = 8 completely. This shows how a tree can keep splitting to fit even a single odd sample.
A minimal implementation
The sketch below grows a tree for one numeric feature. It uses a simple misclassification count as the score, so it runs without extra libraries. Later chapters replace this score with Gini or entropy.
from collections import Counter
def majority(labels):
return Counter(labels).most_common(1)[0][0]
def errors(labels):
return len(labels) - Counter(labels).most_common(1)[0][1]
def build(xs, ys, depth=0, max_depth=3):
if len(set(ys)) == 1 or depth == max_depth:
return {"leaf": majority(ys)}
pairs = sorted(zip(xs, ys))
best = None
for i in range(1, len(pairs)):
if pairs[i - 1][0] == pairs[i][0]:
continue
t = (pairs[i - 1][0] + pairs[i][0]) / 2
left = [y for x, y in pairs if x <= t]
right = [y for x, y in pairs if x > t]
score = errors(left) + errors(right)
if best is None or score < best[1]:
best = (t, score)
if best is None:
return {"leaf": majority(ys)}
t = best[0]
li = [i for i, x in enumerate(xs) if x <= t]
ri = [i for i, x in enumerate(xs) if x > t]
return {
"threshold": t,
"left": build([xs[i] for i in li], [ys[i] for i in li], depth + 1, max_depth),
"right": build([xs[i] for i in ri], [ys[i] for i in ri], depth + 1, max_depth),
}
tree = build([1, 2, 3, 7, 8, 9], ["A", "A", "B", "B", "A", "B"])
print(tree)The function calls itself on each child with a smaller subset of the data. That self-call is the recursion.
Common errors
- Assuming the tree is globally optimal. Greedy choices can miss a better tree. Finding the best tree overall is much harder than finding the best single split.
- Forgetting a base case. Without a stopping rule, recursion continues until every leaf is pure. For noisy data, this memorizes the training set.
- Splitting on identical values. If all samples in a node have the same feature values but different labels, no split is possible. The node must become a leaf. The code above handles this with the
best is Nonecheck.
Exercise
In the first table, why does the algorithm stop splitting after one split? Why would it keep going if the label at x = 8 were A?
Show answer
After the split at 2.5, both children contain a single label, so each is pure and becomes a leaf. With x = 8 labeled A, the right child holds mixed labels (B, B, A, B), so the stopping check fails and the algorithm must search for another split.