Decision Trees
Recursive splits, impurity and pruning.
A decision tree cuts the input space into boxes with axis-aligned splits and predicts a constant in each box. This lesson derives the impurity measures that choose the cuts, the sort-and-scan search that finds the best cut in per feature, the regression version, and the cost-complexity pruning that stops a tree from memorizing its training set.
What you’ll learn
- Write a decision tree as a piecewise-constant model on a partition into boxes, and grow it by greedy recursive binary splitting.
- Compute the misclassification error, Gini impurity and entropy of a node and the impurity decrease of a split, and explain why strictly concave impurities are used for growing.
- Find a feature's best threshold with one sort and one scan, and derive the cost of growing a tree.
- Grow regression trees with squared-error splits, handle categorical features, and explain why trees are unaffected by order-preserving feature transforms.
- Prune by cost-complexity, choose the penalty by cross-validation, and explain why single trees are readable but unstable.
The model: boxes and constants
A binary decision tree on inputs is built from tests . Each internal node compares one feature with one threshold and sends an example left or right, so the leaves partition the input space into boxes with sides parallel to the axes. The tree predicts a constant in each box:
Choosing the best tree of a given size is empirical risk minimization over a huge combinatorial class, and problems of this kind are NP-hard (Hyafil & Rivest, 1976, proved the first such result; the Convergence lesson Optimal & Interpretable Trees takes this up). Every practical algorithm since CART (Breiman, Friedman, Olshen & Stone, 1984) and ID3 (Quinlan, 1986) therefore grows the tree greedily, top down, one split at a time, scoring each candidate by how much it lowers an impurity measure :
GROW(node with example set S, depth)
if S is pure, or |S| < n_min, or depth = D_max:
return LEAF(prediction from S) # majority class, or mean of y
for each feature j:
for each threshold s between consecutive distinct values of x_j in S:
S_L = {i in S : x_ij <= s}; S_R = S - S_L
score(j, s) = |S_L|/|S| * I(S_L) + |S_R|/|S| * I(S_R)
(j*, s*) = argmin over (j, s) of score(j, s) # largest impurity decrease
if I(S) - score(j*, s*) < min_decrease:
return LEAF(prediction from S)
return NODE(x_j* <= s*, GROW(S_L, depth + 1), GROW(S_R, depth + 1))Greedy recursive binary splitting. Each node's prediction depends only on the training examples that reach it, so every leaf is a local average.
Impurity: how mixed is a node?
Let be the fraction of class among the training examples at node , for classes. Three impurity measures are standard:
| Measure | Formula | Two classes ( = fraction of class 1) | Maximum (two classes) |
|---|---|---|---|
| Misclassification error | |||
| Gini impurity | |||
| Entropy | bit |
A split of node into children that receive fractions and of its examples has impurity decrease
The Gini impurity has three useful readings. It is the probability that two labels drawn at random, with replacement, from the node differ. It is the error rate of the randomized rule that predicts class with probability . And it is a variance: code the label as a one-hot vector ; coordinate has variance , so the Gini impurity is the total variance of the one-hot labels, and a Gini tree is exactly a least-squares regression tree fitted to them.
| Split | Children (class 1, class 2) | Decrease in misclassification | Decrease in Gini | Decrease in entropy |
|---|---|---|---|---|
| (40, 10) and (20, 30) | 0.100 | 0.080 | 0.125 bits | |
| (30, 0) and (30, 40) | 0.100 | 0.137 | 0.281 bits |
The reason is shape. Gini and entropy are strictly concave functions of the class proportions, and the parent's proportions are the weighted average of the children's, so by Jensen's inequality any split whose children differ in their proportions strictly lowers them. Misclassification error is concave but piecewise linear: its decrease is exactly zero whenever both children keep the parent's majority class, however much purer one of them becomes. The Convergence lesson CART in Depth proves both facts. In practice Gini and entropy usually choose the same or nearly the same splits, and misclassification error is kept for pruning and for reporting.
Think first A node has class proportions over three classes. Work out its Gini impurity and entropy before revealing.
Gini: , against a maximum of for three classes. Entropy: bits, against a maximum of . Both say the node is far from pure.
Finding the best split fast
For one feature at a node with examples, only thresholds between consecutive distinct values matter (midpoints are the usual choice), so there are at most candidates. Scoring each from scratch costs , or per feature. One sort and one scan do much better:
Sort the node's examples by feature , so . A threshold between positions and (allowed when ) puts the first examples on the left. Keep the left child's class counts ; moving one example across changes one count.
The weighted Gini impurity is a function of the counts alone. Multiplying by and expanding, minimizing it is the same as maximizing a sum that updates in per position:
For regression with squared error, a group of targets with sum and sum of squares has residual sum of squares . The 's add up to the same total for every split, so the best threshold maximizes a function of two running sums:
Cost: one sort and an scan per feature, so per node. The nodes of one level partition the training examples, so a level costs and a tree of depth costs . Sorting every feature once at the root and passing the order down to the children cuts the per-level cost to . Gradient-boosting libraries go further and bin each feature into a few hundred buckets (XGBoost, LightGBM & CatBoost).
You replace a positive feature by its logarithm and regrow the tree with the same settings. What changes?
- The splits change, because the logarithm compresses large values
- The partition of the training data is identical; only the threshold values are expressed on the new scale
- The tree becomes shallower, because the feature now has a smaller range
- Nothing at all, not even the numbers printed at the nodes
Show the answer
B. The partition of the training data is identical; only the threshold values are expressed on the new scale
A split depends only on how a threshold divides the sorted values, and a strictly increasing transform preserves the order. So every candidate split of the training data, its impurity decrease, and the chosen partition are the same. The thresholds are now written on the log scale; since the midpoint of two log values maps back to their geometric rather than arithmetic mean, a new point lying between two neighboring training values can occasionally fall on the other side. This is why trees need no feature scaling and shrug off outlying feature values (though not outlying targets, in regression).
Regression trees and categorical features
A regression tree uses the squared error. In a leaf, the constant minimizing is the mean , the node impurity is the variance of its targets, and a split is chosen to minimize . Other losses swap the mean for another constant: the median for absolute error, a quantile for the pinball loss of quantile regression. The decrease in SSE has a clean form:
A node with 10 training targets is split into children of 4 and 6 examples with means 3 and 8. By how much does the sum of squared errors fall?
Show the answer
60
. The formula needs only the sizes and means of the children, not the individual targets.
Every prediction of a regression tree is an average of training targets, so it can never leave the range of the training values: a tree cannot extrapolate a trend beyond the data, and it approximates a smooth function by a staircase.
Categorical features. A feature with unordered levels allows binary splits, one for each way of choosing which levels go left. For two classes there is a shortcut (Breiman et al., 1984): sort the levels by their fraction of class 1 and try only the splits along that order; one of them is optimal for Gini or entropy. For squared-error regression the same holds with levels sorted by their mean response, a result going back to Fisher (1958). With three or more classes no ordering is guaranteed to contain the optimum, so implementations use heuristics or one-hot encoding.
Missing values. CART sends an example whose split feature is missing down the side chosen by a surrogate split, a split on another feature that best mimics the primary one. C4.5 sends it down both branches with fractional weights, and gradient-boosting libraries learn a default direction for missing values at each split.
Think first A feature "state" has 50 levels. How many binary splits would an exhaustive search try, and how many with the ordering shortcut for a two-class problem?
Exhaustive: splits. With the shortcut: . The flip side is a bias: a feature with many levels offers many candidate splits, so even when it is pure noise it often finds one that looks good by chance. That inflates how often such features are chosen and their importance scores, a problem the Convergence lesson Feature Importance & Its Pitfalls examines.
Stopping, pruning and cost-complexity
When should growth stop? Simple rules, such as a maximum depth, a minimum number of examples per leaf or a minimum impurity decrease, are cheap but short-sighted: a split that looks useless can enable excellent splits below it. In the XOR pattern no single first split lowers the impurity at all, yet two levels classify perfectly. CART's answer is to grow a large tree and then prune it back. For a subtree , obtained by collapsing some internal nodes into leaves, with leaves and training error (the misclassification rate, or the SSE divided by in regression), define
Breiman et al. (1984) proved that for each there is a unique smallest subtree minimizing , and that as grows these subtrees are nested, , with finitely many distinct ones. Weakest-link pruning computes the whole sequence. For each internal node of the current tree, with branch below it, compute the increase in training error per leaf removed if is collapsed:
Collapsed into a leaf, node would misclassify 10% of the training set. Its branch has 4 leaves, which together misclassify 4%. Above what value of does collapsing lower ?
Show the answer
0.02
. Collapsing removes 3 leaves, saving , and adds 0.06 of training error, so it pays once .
Choose , and with it the tree size, by cross-validation: for each of folds, grow and prune a tree on the other folds and measure the error of each pruned subtree on the held-out fold. Pick the with the lowest average error or, with the one-standard-error rule, the largest whose error is within one standard error of that minimum, which gives a smaller tree that is statistically as good.
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
full = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
path = full.cost_complexity_pruning_path(X_train, y_train)
alphas = path.ccp_alphas[:-1] # breakpoints; the last one leaves only the root
cv = [cross_val_score(DecisionTreeClassifier(ccp_alpha=a, random_state=0),
X_train, y_train, cv=5).mean() for a in alphas]
best = alphas[int(np.argmax(cv))]
tree = DecisionTreeClassifier(ccp_alpha=best, random_state=0).fit(X_train, y_train)scikit-learn measures by the leaves' weighted impurity rather than the misclassification rate, but the pruning algorithm is the same.
Strengths, weaknesses and what comes next
| Property | Consequence |
|---|---|
| A short path of tests per prediction | a small tree reads as rules that people can audit; a large one cannot be read |
| Splits use only the order of each feature | no scaling needed; robust to outlying feature values; numeric and categorical inputs mix freely |
| Splits inside a branch condition on the splits above | interactions between features are captured without being specified |
| Axis-aligned, piecewise-constant fit | staircases for oblique boundaries; no extrapolation beyond the training targets; a discontinuous regression function |
| Greedy, data-dependent choices | high variance: a small change in the data can change the root split and everything below it |
Key takeaways
- A decision tree is a piecewise-constant model on axis-aligned boxes. Finding an optimal tree is NP-hard, so trees are grown greedily, one split at a time.
- Impurities: misclassification , Gini , entropy . Gini and entropy are strictly concave and reward useful splits that misclassification error scores as zero; Gini splitting is least squares on one-hot labels.
- Sorting once and scanning with running counts or sums finds a feature's best threshold in ; a level of the tree costs .
- Regression trees predict leaf means, choose splits by the between-group sum of squares , and cannot extrapolate. Order-preserving feature transforms leave the training partition unchanged.
- Cost-complexity pruning of yields a nested sequence of subtrees, computed by weakest-link pruning; choose by cross-validation. Single trees are readable but unstable, which ensembles exploit.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A node with 50 examples of each class is split into children with class counts (40, 10) and (10, 40). By how much does the Gini impurity fall?
- 0.18
- 0.32
- 0.50
- 0.64
Show the answer
A. 0.18
The parent has . Each child has , so the weighted average is 0.32 and the decrease is .
Why do tree learners grow trees with Gini impurity or entropy rather than the misclassification rate?
- The misclassification rate is more expensive to compute
- The misclassification rate can increase after a split
- Gini and entropy are strictly concave, so any split that changes the class proportions lowers them, while the misclassification rate often shows zero decrease for useful splits
- Gini and entropy always produce smaller trees
Show the answer
C. Gini and entropy are strictly concave, so any split that changes the class proportions lowers them, while the misclassification rate often shows zero decrease for useful splits
The misclassification rate is piecewise linear in the class proportions, so its decrease is zero whenever both children keep the parent's majority class, even if one child becomes pure. Strictly concave impurities reward such splits, which often make later splits easy.
A regression tree is trained on houses priced between 100,000 and 900,000. What can it predict for a house far larger than any in the training data?
- A price above 900,000, following the trend of larger houses
- At most 900,000, because every prediction is an average of training prices
- Any value, because trees are very flexible
- Nothing: the tree cannot handle inputs outside the training range
Show the answer
B. At most 900,000, because every prediction is an average of training prices
The house falls into some leaf, whose prediction is the mean of the training prices there, so it lies between 100,000 and 900,000. Trees are flat beyond the data: they cannot extrapolate a trend.
In cost-complexity pruning, what happens to the optimal subtree as increases?
- It changes continuously, giving a different tree for every value of
- It jumps between unrelated trees
- It always equals the tree grown to a fixed maximum depth
- It shrinks through a finite nested sequence, each tree a subtree of the one before
Show the answer
D. It shrinks through a finite nested sequence, each tree a subtree of the one before
Breiman et al. (1984) showed that the smallest minimizers of are nested and piecewise constant in . Weakest-link pruning computes the breakpoints by repeatedly collapsing the node with the smallest .
Before fitting a decision tree, you standardize every feature (subtract its mean, divide by its standard deviation). What changes?
- The tree becomes more accurate, because the features become comparable
- The Gini impurities change, because the features have been rescaled
- The learned partition of the training data stays the same; only the threshold values are re-expressed
- Features with large variance lose their advantage, so different features get chosen
Show the answer
C. The learned partition of the training data stays the same; only the threshold values are re-expressed
Standardization is strictly increasing in each feature, so it preserves every feature's order. Splits, impurities and the partition are unchanged; only the thresholds are written in standardized units. Scaling matters for distance- and gradient-based methods, not for trees.
Go deeper
- CART in Depth · Split criteria, cost-complexity pruning, categorical features and missing values.
- Optimal & Interpretable Trees · Why the best tree is NP-hard to find, and modern ways around it.
- Trees as Adaptive Partitions · Consistency, bias–variance and the instability of single trees.
Further reading
- L. Breiman, J. H. Friedman, R. A. Olshen & C. J. Stone, Classification and Regression Trees (Wadsworth, 1984).
- J. R. Quinlan, "Induction of decision trees," Machine Learning 1, 81–106 (1986).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), §9.2.
- W.-Y. Loh, "Fifty years of classification and regression trees," International Statistical Review 82(3), 329–348 (2014).