Sub topic 5
Finding the best split
This chapter assumes you know what Gini impurity is, how weighted impurity decrease scores a split, and how recursive partitioning builds a tree. It covers how a tree turns those scores into one concrete question at each node.
The search problem
At every node the tree must choose a feature and a rule for that feature. The choice is greedy: it picks the split with the lowest weighted child impurity right now, with no look-ahead.
The rule has the form feature <= threshold for a numeric feature. The search is exhaustive over a finite set of candidates, so no gradient descent or randomness is involved.
Candidate thresholds for numeric features
Only the order of the values matters, not their magnitudes. If a feature takes n distinct values in the node, the samples can be separated into a left and a right group in only n - 1 different ways. Any threshold between two neighbouring sorted values produces the same partition.
The usual convention is the midpoint of two neighbouring distinct values. Two details matter:
- Identical values are never separated. If
x[i-1] == x[i], no threshold can put them on different sides, so that position is skipped. - Midpoints help at prediction time. A new sample that falls between two training values lands in the middle of the gap instead of on its edge.
A reference implementation
The function below scores each midpoint on one feature. It is a direct and slow version, because it rebuilds both child lists for every threshold. That keeps the logic easy to read.
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 threshold 6.5 sits halfway between 3.0 and 10.0. It produces two pure children, so the weighted impurity is 0.0.
Searching across features
To pick the split for a node, run the threshold search on every feature and keep the winner. This function reuses gini and best_threshold from above.
def best_split(rows, ys):
best = (None, None, float("inf")) # (feature index, threshold, score)
for j in range(len(rows[0])):
xs = [r[j] for r in rows]
t, score = best_threshold(xs, ys)
if t is not None and score < best[2]:
best = (j, t, score)
return best
rows = [[2.0, 5.0], [3.0, 1.0], [10.0, 4.0], [11.0, 2.0]]
ys = [0, 0, 1, 1]
print(best_split(rows, ys)) # (0, 6.5, 0.0)Feature 1 in this example has a best score of 1/3, so feature 0 wins. The comparison uses a strict <, so on a tie the earlier feature and threshold are kept. scikit-learn also resolves ties by search order, but it shuffles the feature order using random_state. Two equally good splits can therefore produce different trees under different seeds.
Cost and how real libraries speed it up
The reference code costs about O(n²) per feature, because each of up to n - 1 thresholds rebuilds both child lists. Production implementations avoid this:
- Sort the node's samples by the feature once, in O(n log n).
- Sweep from left to right, moving one sample at a time from the right child to the left child.
- Keep running class counts for each side, so each child's Gini updates in O(number of classes).
With that sweep, a node costs roughly O(p · n log n) for p features. Sorting dominates. Across the whole tree this gives the commonly quoted training cost of about O(p · n log² n) for a balanced tree. Gradient boosting libraries often go further and bin each feature into at most a few hundred buckets, so only the bucket edges are candidates.
Categorical features
A categorical feature has no order, so thresholds do not apply. A split instead sends a subset of categories left and the rest right. With k categories there are 2^(k−1) − 1 possible non-trivial partitions, which grows too fast to enumerate for large k.
There are two common approaches:
- One-hot encoding. Each category becomes a 0/1 column, and the split
is_red <= 0.5isolates one category at a time. This is the usual route with scikit-learn trees. Its weakness is that a high-cardinality feature needs many splits to group categories. - Ordering trick. For binary classification or regression, sort the categories by their mean target value and treat them as ordered. The best subset split is then always one of the
k − 1cut points along that order, which is a result due to Breiman and colleagues. Some libraries use this.
Do not label-encode a nominal category as 0, 1, 2 and feed it to a tree as if it were numeric. The tree will look only for threshold splits along an arbitrary order, and it can miss groupings that do not happen to be contiguous.
Constraints that change the search
Several hyperparameters act while the candidates are being scored, not after. They change which split wins.
min_samples_leafrejects any candidate that leaves fewer than that many samples on either side. A perfect-looking split that isolates one sample is discarded, and the next-best candidate is used.min_impurity_decreaserejects a best split whose weighted impurity decrease is too small. The node then becomes a leaf.max_featureslimits the search to a random subset of features at each node. This is faster, and it is the mechanism random forests rely on to make their trees different from each other.splitter="random"in scikit-learn draws one random threshold per feature instead of scanning all of them. It is much faster and adds variance.
Bias toward features with many split points
Impurity-based search favours features with many distinct values. A continuous feature offers hundreds of thresholds, and a binary feature offers one. By chance alone, one of the many thresholds will often score better than the single option on a more meaningful feature. An ID column or a timestamp can look attractive for this reason. It will then show high impurity-based importance without carrying any generalizable signal.
Practical consequences:
- Drop identifiers before training.
- Be cautious about impurity-based feature importance for noisy continuous features. A later chapter covers this caveat and the alternatives.
- Use
min_samples_leafas a guard, because it blocks the tiny-leaf splits where chance fits are most likely.
Edge cases to check
| Situation | What happens |
|---|---|
| All values of a feature equal in the node | No candidates, so the feature is skipped. |
| Node already pure | Impurity is 0, so no split can improve it and the node becomes a leaf. |
| Two splits tie | The first found wins. The order depends on feature order and shuffling. |
| Missing values | Behaviour depends on the library. Older scikit-learn versions reject them, and newer versions of some trees can route them to one side. Check your version's documentation. |
| Feature values differ only by tiny float error | Midpoints can round to one of the neighbours, so the library applies a minimum feature-difference check. |
Exercise
A node holds four samples with feature values [1, 2, 3, 4] and labels [0, 1, 0, 1]. List the candidate thresholds, compute the weighted Gini for each, and say which one your search returns if ties go to the first candidate.
Show answer
The candidates are 1.5, 2.5, and 3.5. At 1.5 the left child is [0] with Gini 0 and the right child is [1, 0, 1] with Gini 1 − (1/9 + 4/9) = 4/9, so the weighted score is (1 × 0 + 3 × 4/9) / 4 = 1/3. At 2.5 both children are [0, 1] with Gini 0.5, so the weighted score is 0.5. At 3.5 the left child is [0, 1, 0] with Gini 4/9 and the right child is [1] with Gini 0, so the weighted score is 1/3. The scores at 1.5 and 3.5 tie at 1/3, so the search returns 1.5.
Exercise
A node has 1,000 samples and 10 numeric features, and every feature value is distinct. What is the maximum number of candidate splits scored at this node, and how does setting max_features=3 change it?
Show answer
Each feature has at most 999 candidate thresholds, so the maximum is 10 × 999 = 9,990 candidates. With max_features=3, only 3 randomly chosen features are searched, so at most 3 × 999 = 2,997 candidates are scored. The reduced search is faster. The best split found may be worse than the best over all features, which is the diversity that random forests exploit.