Simple Algorithm
Machine Learning · Descent · 22 min

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 O(mlog⁡m)\order{m\log m} 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 x∈Rd\mathbf x\in\R^d is built from tests xj≤sx_j\le s. Each internal node compares one feature jj with one threshold ss and sends an example left or right, so the MM leaves partition the input space into boxes R1,…,RMR_1,\dots,R_M with sides parallel to the axes. The tree predicts a constant in each box:

f(x)=∑m=1Mcm 1{x∈Rm}f(\mathbf x)=\sum_{m=1}^{M}c_m\,\mathbf 1\{\mathbf x\in R_m\}
For classification, cmc_m is the majority class of the training examples in RmR_m, and their class proportions p^mk\hat p_{mk} serve as probability estimates; for regression, cmc_m is their mean.

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 II:

text
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 p^k\hat p_k be the fraction of class kk among the ntn_t training examples at node tt, for KK classes. Three impurity measures are standard:

MeasureFormulaTwo classes (p^\hat p = fraction of class 1)Maximum (two classes)
Misclassification error1−max⁡kp^k1-\max_k\hat p_kmin⁡(p^, 1−p^)\min(\hat p,\,1-\hat p)1/21/2
Gini impurity∑kp^k(1−p^k)=1−∑kp^k2\sum_k\hat p_k(1-\hat p_k)=1-\sum_k\hat p_k^22p^(1−p^)2\hat p(1-\hat p)1/21/2
Entropy−∑kp^klog⁡2p^k-\sum_k\hat p_k\log_2\hat p_k−p^log⁡2p^−(1−p^)log⁡2(1−p^)-\hat p\log_2\hat p-(1-\hat p)\log_2(1-\hat p)11 bit
All three vanish at a pure node and peak at the uniform distribution; with KK classes the maxima are 1−1/K1-1/K, 1−1/K1-1/K and log⁡2K\log_2K.

A split of node tt into children tL,tRt_L,t_R that receive fractions wL=ntL/ntw_L=n_{t_L}/n_t and wR=ntR/ntw_R=n_{t_R}/n_t of its examples has impurity decrease

ΔI=I(t)−wL I(tL)−wR I(tR)\Delta I = I(t) - w_L\,I(t_L) - w_R\,I(t_R)
With entropy, ΔI\Delta I is the information gain: the empirical mutual information between the split indicator and the class, among the examples at tt.

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 kk with probability p^k\hat p_k. And it is a variance: code the label as a one-hot vector ey∈{0,1}K\mathbf e_y\in\{0,1\}^K; coordinate kk has variance p^k(1−p^k)\hat p_k(1-\hat p_k), 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.

SplitChildren (class 1, class 2)Decrease in misclassificationDecrease in GiniDecrease in entropy
s1s_1(40, 10) and (20, 30)0.1000.0800.125 bits
s2s_2(30, 0) and (30, 40)0.1000.1370.281 bits
A node with 60 examples of class 1 and 40 of class 2 (misclassification 0.40, Gini 0.48, entropy 0.971 bits). Misclassification error cannot tell the two splits apart; Gini and entropy both prefer s2s_2, which isolates a pure group of 30 that needs no further splitting.

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 (0.5,0.3,0.2)(0.5, 0.3, 0.2) over three classes. Work out its Gini impurity and entropy before revealing.

Gini: 1−(0.52+0.32+0.22)=1−(0.25+0.09+0.04)=0.621-(0.5^2+0.3^2+0.2^2)=1-(0.25+0.09+0.04)=0.62, against a maximum of 1−1/3≈0.671-1/3\approx0.67 for three classes. Entropy: −(0.5log⁡20.5+0.3log⁡20.3+0.2log⁡20.2)≈1.49-(0.5\log_20.5+0.3\log_20.3+0.2\log_20.2)\approx1.49 bits, against a maximum of log⁡23≈1.58\log_23\approx1.58. Both say the node is far from pure.

Finding the best split fast

For one feature at a node with mm examples, only thresholds between consecutive distinct values matter (midpoints are the usual choice), so there are at most m−1m-1 candidates. Scoring each from scratch costs O(m)\order{m}, or O(m2)\order{m^2} per feature. One sort and one scan do much better:

DerivationScanning a feature in one pass
  1. NkL(i+1)=NkL(i)+1{y(i+1)=k},NkR(i)=Nk−NkL(i)N_k^L(i+1)=N_k^L(i)+\mathbf 1\{y_{(i+1)}=k\},\qquad N_k^R(i)=N_k-N_k^L(i)

    Sort the node's examples by feature jj, so x(1)≤⋯≤x(m)x_{(1)}\le\dots\le x_{(m)}. A threshold between positions ii and i+1i+1 (allowed when x(i)<x(i+1)x_{(i)}<x_{(i+1)}) puts the first ii examples on the left. Keep the left child's class counts NkLN_k^L; moving one example across changes one count.

  2. m[imGL+m−imGR]=m−∑k(NkL)2i−∑k(NkR)2m−im\Big[\tfrac im G_L+\tfrac{m-i}m G_R\Big]=m-\sum_{k}\frac{(N_k^L)^2}{i}-\sum_k\frac{(N_k^R)^2}{m-i}

    The weighted Gini impurity is a function of the counts alone. Multiplying by mm and expanding, minimizing it is the same as maximizing a sum that updates in O(K)\order{K} per position:

  3. SSEL+SSER=∑iyi2−(SL2i+SR2m−i)\mathrm{SSE}_L+\mathrm{SSE}_R=\sum_{i}y_i^2-\Big(\frac{S_L^2}{i}+\frac{S_R^2}{m-i}\Big)

    For regression with squared error, a group of ngn_g targets with sum SgS_g and sum of squares QgQ_g has residual sum of squares Qg−Sg2/ngQ_g-S_g^2/n_g. The QQ's add up to the same total for every split, so the best threshold maximizes a function of two running sums:

  4. O(dnlog⁡n)⏟presort once+O(dn)⏟per level\underbrace{\order{dn\log n}}_{\text{presort once}}+\underbrace{\order{dn}}_{\text{per level}}

    Cost: one sort and an O(m)\order{m} scan per feature, so O(dmlog⁡m)\order{dm\log m} per node. The nodes of one level partition the nn training examples, so a level costs O(dnlog⁡n)\order{dn\log n} and a tree of depth DD costs O(Ddnlog⁡n)\order{Ddn\log n}. Sorting every feature once at the root and passing the order down to the children cuts the per-level cost to O(dn)\order{dn}. Gradient-boosting libraries go further and bin each feature into a few hundred buckets (XGBoost, LightGBM & CatBoost).

Check your understanding

You replace a positive feature by its logarithm and regrow the tree with the same settings. What changes?

  1. The splits change, because the logarithm compresses large values
  2. The partition of the training data is identical; only the threshold values are expressed on the new scale
  3. The tree becomes shallower, because the feature now has a smaller range
  4. 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 ∑i∈Rm(yi−c)2\sum_{i\in R_m}(y_i-c)^2 is the mean yˉm\bar y_m, the node impurity is the variance of its targets, and a split is chosen to minimize SSEL+SSER\mathrm{SSE}_L+\mathrm{SSE}_R. 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:

SSEparent−SSEL−SSER=nLnRn (yˉL−yˉR)2\mathrm{SSE}_{\text{parent}}-\mathrm{SSE}_L-\mathrm{SSE}_R=\frac{n_Ln_R}{n}\,\big(\bar y_L-\bar y_R\big)^2
The between-group sum of squares. A split scores well when the two children's means differ a lot and neither child is tiny: separation is traded against balance.
Predict before you look

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

4⋅610(3−8)2=2.4×25=60\frac{4\cdot6}{10}(3-8)^2=2.4\times25=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 yy values: a tree cannot extrapolate a trend beyond the data, and it approximates a smooth function by a staircase.

Categorical features. A feature with LL unordered levels allows 2L−1−12^{L-1}-1 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 L−1L-1 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: 249−1≈5.6×10142^{49}-1\approx5.6\times10^{14} splits. With the shortcut: 4949. 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 T0T_0 and then prune it back. For a subtree T⪯T0T\preceq T_0, obtained by collapsing some internal nodes into leaves, with ∣T∣|T| leaves and training error R(T)R(T) (the misclassification rate, or the SSE divided by nn in regression), define

Rα(T)=R(T)+α ∣T∣R_\alpha(T)=R(T)+\alpha\,|T|
The cost-complexity criterion. α≥0\alpha\ge0 is the price of a leaf: α=0\alpha=0 keeps the full tree, and a large enough α\alpha leaves only the root.

Breiman et al. (1984) proved that for each α\alpha there is a unique smallest subtree TαT_\alpha minimizing RαR_\alpha, and that as α\alpha grows these subtrees are nested, T0⪰Tα1⪰Tα2⪰⋯⪰{root}T_0\succeq T_{\alpha_1}\succeq T_{\alpha_2}\succeq\dots\succeq\{\text{root}\}, with finitely many distinct ones. Weakest-link pruning computes the whole sequence. For each internal node tt of the current tree, with branch TtT_t below it, compute the increase in training error per leaf removed if tt is collapsed:

g(t)=R(t)−R(Tt)∣Tt∣−1g(t)=\frac{R(t)-R(T_t)}{|T_t|-1}
Collapse the node (or nodes) with the smallest gg, record that value as the next breakpoint αk\alpha_k, and repeat until only the root remains.
Predict before you look

Collapsed into a leaf, node tt would misclassify 10% of the training set. Its branch has 4 leaves, which together misclassify 4%. Above what value of α\alpha does collapsing tt lower RαR_\alpha?

Show the answer

0.02

g(t)=(0.10−0.04)/(4−1)=0.02g(t)=(0.10-0.04)/(4-1)=0.02. Collapsing removes 3 leaves, saving 3α3\alpha, and adds 0.06 of training error, so it pays once 3α>0.063\alpha>0.06.

Choose α\alpha, and with it the tree size, by cross-validation: for each of KK 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 α\alpha with the lowest average error or, with the one-standard-error rule, the largest α\alpha whose error is within one standard error of that minimum, which gives a smaller tree that is statistically as good.

python
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 R(T)R(T) by the leaves' weighted impurity rather than the misclassification rate, but the pruning algorithm is the same.

Strengths, weaknesses and what comes next

PropertyConsequence
A short path of tests per predictiona small tree reads as rules that people can audit; a large one cannot be read
Splits use only the order of each featureno scaling needed; robust to outlying feature values; numeric and categorical inputs mix freely
Splits inside a branch condition on the splits aboveinteractions between features are captured without being specified
Axis-aligned, piecewise-constant fitstaircases for oblique boundaries; no extrapolation beyond the training targets; a discontinuous regression function
Greedy, data-dependent choiceshigh 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 1−max⁡kp^k1-\max_k\hat p_k, Gini 1−∑kp^k21-\sum_k\hat p_k^2, entropy −∑kp^klog⁡2p^k-\sum_k\hat p_k\log_2\hat p_k. 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 O(mlog⁡m)\order{m\log m}; a level of the tree costs O(dnlog⁡n)\order{dn\log n}.
  • Regression trees predict leaf means, choose splits by the between-group sum of squares nLnRn(yˉL−yˉR)2\frac{n_Ln_R}n(\bar y_L-\bar y_R)^2, and cannot extrapolate. Order-preserving feature transforms leave the training partition unchanged.
  • Cost-complexity pruning of R(T)+α∣T∣R(T)+\alpha|T| yields a nested sequence of subtrees, computed by weakest-link pruning; choose α\alpha 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.

Question 1

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?

  1. 0.18
  2. 0.32
  3. 0.50
  4. 0.64
Show the answer

A. 0.18

The parent has G=0.5G=0.5. Each child has G=2(0.8)(0.2)=0.32G=2(0.8)(0.2)=0.32, so the weighted average is 0.32 and the decrease is 0.5−0.32=0.180.5-0.32=0.18.

Question 2

Why do tree learners grow trees with Gini impurity or entropy rather than the misclassification rate?

  1. The misclassification rate is more expensive to compute
  2. The misclassification rate can increase after a split
  3. 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
  4. 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.

Question 3

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?

  1. A price above 900,000, following the trend of larger houses
  2. At most 900,000, because every prediction is an average of training prices
  3. Any value, because trees are very flexible
  4. 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.

Question 4

In cost-complexity pruning, what happens to the optimal subtree TαT_\alpha as α\alpha increases?

  1. It changes continuously, giving a different tree for every value of α\alpha
  2. It jumps between unrelated trees
  3. It always equals the tree grown to a fixed maximum depth
  4. 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 R(T)+α∣T∣R(T)+\alpha|T| are nested and piecewise constant in α\alpha. Weakest-link pruning computes the breakpoints αk\alpha_k by repeatedly collapsing the node with the smallest g(t)=(R(t)−R(Tt))/(∣Tt∣−1)g(t)=(R(t)-R(T_t))/(|T_t|-1).

Question 5

Before fitting a decision tree, you standardize every feature (subtract its mean, divide by its standard deviation). What changes?

  1. The tree becomes more accurate, because the features become comparable
  2. The Gini impurities change, because the features have been rescaled
  3. The learned partition of the training data stays the same; only the threshold values are re-expressed
  4. 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

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).