Sub topic 2
How a tree picks its splits
This chapter assumes you know what a decision tree looks like: a series of yes/no questions that ends in a leaf holding a prediction. It also assumes you know the vocabulary of classification and regression. Here you learn how the tree decides which question to ask at each node. That choice is the main source of the tree's variance, so the later chapters on bagging and random feature subsets build directly on it.
What a split is
A split at a node is a rule of the form feature j <= threshold t. Samples that satisfy the rule go to the left child. The rest go to the right child. For a numeric feature, the candidate thresholds are the midpoints between consecutive distinct values of that feature among the samples at the node.
The tree builder (scikit-learn uses an optimized version of CART) is greedy. At each node it tries every candidate split on every feature it is allowed to consider. It keeps the single split that reduces impurity the most, then repeats the process on each child. It never looks ahead and never goes back to revise an earlier split.
Impurity: scoring how mixed a node is
Impurity measures how mixed the targets are inside a node. It is zero when the node is pure, meaning every sample has the same label. It grows as the labels become more mixed.
| Criterion | Task | Formula for a node | Value when pure |
|---|---|---|---|
| Gini impurity | Classification | 1 - sum of p_k squared | 0 |
| Entropy | Classification | -sum of p_k log2(p_k) | 0 |
| Variance (MSE) | Regression | mean of (y - mean of y) squared | 0 |
Here p_k is the fraction of samples in the node that belong to class k.
- Gini impurity is the probability that two samples drawn at random from the node (with replacement) have different labels. For two classes it peaks at 0.5.
- Entropy measures the average surprise of a label drawn from the node. For two classes it peaks at 1 bit.
- Variance reduction is the regression analogue. A node is good when its targets are close to their mean. Using variance as the criterion is the same as minimizing squared error when each leaf predicts its mean.
In scikit-learn these are criterion="gini" (the default), "entropy" or "log_loss" for classifiers, and "squared_error" (the default) for regressors.
Scoring a split: weighted decrease in impurity
A split is scored by comparing the parent's impurity with the average impurity of the children. The children are weighted by how many samples each one receives:
gain = I(parent) - (nleft / n) * I(left) - (nright / n) * I(right)
The weighting matters. A split that peels off one pure sample from a node of 1,000 should not score as well as a split that cleanly separates two large groups.
A worked example
A node holds 10 samples: 6 of class 1 and 4 of class 0.
- Parent Gini: 1 - 0.6² - 0.4² = 1 - 0.36 - 0.16 = 0.48.
- A candidate split sends 5 samples left (4 of class 1, 1 of class 0) and 5 right (2 of class 1, 3 of class 0).
- Left Gini: 1 - 0.8² - 0.2² = 0.32. Right Gini: 1 - 0.4² - 0.6² = 0.48.
- Weighted child impurity: 0.5 × 0.32 + 0.5 × 0.48 = 0.40.
- Gain: 0.48 - 0.40 = 0.08.
The tree computes this number for every candidate and takes the largest. With entropy, the parent scores about 0.971 bits, and the same procedure applies with a different formula.
Implementing the split search
Searching naively would re-sort the data for every threshold. The standard approach sorts a feature once, then scans the sorted values from left to right. The code below keeps the logic simple and recomputes the impurity at each step, which costs O(n²) per feature. Real implementations update class counts incrementally to get O(n log n) from the sort plus O(n) for the scan.
The script finds the best threshold on one feature and compares it with a depth-1 scikit-learn tree.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
def gini(y):
if len(y) == 0:
return 0.0
p = np.bincount(y) / len(y)
return 1.0 - np.sum(p ** 2)
def best_split(x, y):
order = np.argsort(x)
x_s, y_s = x[order], y[order]
n = len(y_s)
parent = gini(y_s)
best_threshold, best_gain = None, 0.0
for i in range(1, n):
if x_s[i] == x_s[i - 1]:
continue # no threshold fits between equal values
threshold = (x_s[i] + x_s[i - 1]) / 2
left, right = y_s[:i], y_s[i:]
child = (len(left) * gini(left) + len(right) * gini(right)) / n
gain = parent - child
if gain > best_gain:
best_threshold, best_gain = threshold, gain
return best_threshold, best_gain
data = load_breast_cancer()
x = data.data[:, 0] # "mean radius"
y = data.target
threshold, gain = best_split(x, y)
print(f"Hand-written: threshold={threshold:.4f}, gain={gain:.4f}")
stump = DecisionTreeClassifier(max_depth=1, random_state=0)
stump.fit(x.reshape(-1, 1), y)
print(f"scikit-learn: threshold={stump.tree_.threshold[0]:.4f}")The two thresholds should agree up to rounding, because scikit-learn stores thresholds as 32-bit floats. If two thresholds tie exactly on gain, the two implementations may pick different ones.
Edge cases and gotchas
Ties and equal feature values
A threshold can only separate samples whose feature values differ. That is why the code skips positions where x_s[i] == x_s[i - 1]. A feature with a single distinct value at a node can never be split there.
Gini versus entropy
In practice the two criteria pick the same split most of the time. Entropy penalizes mixed nodes slightly more steeply, so it can favor more balanced splits in rare cases. Gini is cheaper because it needs no logarithm. Treat the choice as a minor hyperparameter, not a major modeling decision.
Categorical features
Classic CART can split a categorical feature by testing subsets of categories. Scikit-learn's forests do not do this. Categorical values must be encoded as numbers first, and one-hot encoding turns each category into a separate yes/no feature. Integer codes impose an artificial order that the tree can only partly undo.
Bias toward features with many thresholds
A feature with many distinct values offers many candidate thresholds. Among many candidates, one is likely to look good by chance. Impurity-based selection therefore tends to favor continuous or high-cardinality features over binary ones. This also affects impurity-based feature importance, which a later chapter covers.
Greedy does not mean optimal
The best first split is not always part of the best tree. The classic case is XOR: with two binary features, where the label is 1 when exactly one feature is 1, neither feature alone reduces impurity at the root. A greedy tree sees a gain of zero for every first split. The tree can still learn XOR if it is forced to split anyway, because the second level then finds a perfect split. In scikit-learn, nodes keep splitting while the criterion allows it, and a gain of exactly zero is not always a barrier.
Stopping rules
Splitting stops, and the node becomes a leaf, when one of these conditions holds:
- The node is pure.
max_depthis reached.- The node has fewer than
min_samples_splitsamples. - A split would leave a child with fewer than
min_samples_leafsamples. - The impurity decrease falls below
min_impurity_decrease.
With none of these set, scikit-learn grows each tree until every leaf is pure. That is why a single default tree has high variance. The next chapter explains why.
Connection to random forests
At each node a random forest does not search all features. It searches a random subset of size max_features. The scoring rule described in this chapter stays the same. Only the pool of candidate features shrinks. That change makes different trees choose different splits, which is the subject of the chapter on random feature subsets.
Exercises
Exercise
A node has 8 samples: 4 of class 0 and 4 of class 1. A split sends 3 samples left (all class 0) and 5 samples right (1 of class 0, 4 of class 1). Compute the Gini gain of this split.
Show answer
Parent Gini = 1 - 0.5² - 0.5² = 0.5. Left Gini = 0 because it is pure. Right Gini = 1 - 0.2² - 0.8² = 1 - 0.04 - 0.64 = 0.32. Weighted child impurity = (3/8) × 0 + (5/8) × 0.32 = 0.2. Gain = 0.5 - 0.2 = 0.3.
Exercise
Why does the weighted decrease use each child's share of the samples, instead of a plain average of the two children's impurities?
Show answer
A plain average would give a tiny child the same influence as a large one. A split that isolates one pure sample would look as good as a split that cleanly separates two large groups, even though it tells the tree very little about the data. Weighting by sample count makes the score reflect how much of the node's data actually became purer.
Exercise
In the hand-written best_split function, what would go wrong if the check for equal neighbouring values were removed?
Show answer
The function would compute a "threshold" equal to the repeated value and split the sorted array at a position between two samples that share that value. No real rule x <= t can separate them, so the score would describe a partition the tree could not actually produce when predicting on new data. The gain it reports could be higher than any achievable split.