Sub topic 5
Finding the best split
This chapter assumes you know Gini impurity, entropy, and weighted impurity decrease from the earlier chapters, and that you can read basic Python.
What the search does
At every node, the tree builder needs one question to ask. A split is a feature plus a rule, such as petal_length <= 2.45. The builder scores every candidate split and keeps the one whose child nodes are purest.
The score is the weighted average impurity of the two children:
weighted impurity = (nleft × impurityleft + nright × impurityright) / n
The best split is the one with the lowest weighted impurity. Equivalently, it is the one with the largest drop from the parent's impurity. The search is greedy. It picks the best split for this node only and never looks ahead.
Numeric features
For a numeric feature with k distinct values, only k − 1 splits are meaningfully different. Any threshold between two neighbouring sorted values sends the same samples left and right. By convention the builder uses the midpoint.
def gini(labels):
n = len(labels)
if n == 0:
return 0.0
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 best_threshold(xs, ys):
pairs = sorted(zip(xs, ys))
best = (None, float("inf"))
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 = (len(left) * gini(left) + len(right) * gini(right)) / len(pairs)
if score < best[1]:
best = (t, score)
return best
print(best_threshold([2.0, 3.0, 10.0, 11.0], [0, 0, 1, 1])) # (6.5, 0.0)The continue line skips equal neighbours. Without it, you would score a threshold that cannot separate two identical values. The x <= t convention matches scikit-learn, which sends equal-or-lower values left.
This version rebuilds the left and right lists for every threshold, so it costs O(n²) per feature. Real implementations sort once and then move one sample at a time from the right class counts to the left class counts. Each threshold is then scored in constant time, and the cost is dominated by the O(n log n) sort.
Categorical features
A categorical feature has no natural order, so thresholds do not apply. There are two common approaches.
- Subset splits. Group the categories into two sets, as CART does in its original form. With k categories there are 2^(k−1) − 1 possible groupings, which grows fast.
- Binary encoding. One-hot encode the feature and let each indicator column be a numeric feature. Scikit-learn's
DecisionTreeClassifierexpects numeric input, so this is the usual route there.
Do not label-encode a nominal feature as 0, 1, 2 and feed it in directly. The tree will treat the codes as ordered and only test code <= t, which can hide good groupings.
Choosing across features
The builder repeats the threshold scan for every feature and keeps the overall winner. The max_features hyperparameter limits how many randomly chosen features are examined at each node. A single tree usually leaves it unset. Random forests rely on it, which a later chapter covers.
Common errors
- Scoring children by unweighted average impurity. A tiny pure child can then beat a balanced split.
- Forgetting to skip duplicate values, which produces empty children.
- Expecting the globally best tree. The greedy choice can miss a split that looks weak alone but enables strong splits below it.
- Trusting a threshold's exact value. Small changes in the data can move it, and the whole subtree below changes with it.
Exercise
A node holds labels [0, 0, 1, 1, 1] sorted by one feature with values [1, 2, 3, 4, 5]. Which threshold does the search pick, and what is its weighted Gini?
Show answer
The threshold is 2.5. The left child is [0, 0] with Gini 0, and the right child is [1, 1, 1] with Gini 0, so the weighted Gini is 0.0. Every other midpoint leaves a mixed child with a higher score.