Skip to content
BIASED

Decision trees

Models made of yes-or-no questions about one feature — a piecewise-constant function on boxes, impurity as the loss of the best constant (variance, entropy, Gini), greedy split search and its cost, stopping and pruning, categories and missing values, and why a single tree is unstable.

Questions instead of weights

The topic Multiclass and multilabel classification closed the linear part of the course. One-vs-rest, one-vs-one and softmax regression handle KK classes, and independent sigmoids handle several labels at once. Every one of those models scores an object by a weighted sum of its features, ⟨wk,x⟩+bk\langle w_k, x \rangle + b_k.

A weighted sum has two habits that tabular data dislike. First, it needs numbers on comparable scales, so categories have to be encoded and features scaled, as in the topic Data, features and leakage. Second, it treats each feature on its own. In the credit task, the rule "a higher income lowers the risk of default, unless the debt is also high" says that the effect of income depends on the debt. Such a rule is an interaction. A linear model gets it only through a hand-made feature like income × debt, or through a kernel from the topic Kernels, which has to be chosen and whose Gram matrix grows as n2n^2.

A decision tree starts from the other end. Its building block is a yes-or-no question about one feature, xj≤tx_j \le t. An object starts at the root, answers the question, goes left or right, and repeats until it reaches a leaf, which returns a stored answer.

Interactions come for free: the next question is asked on one side of the previous answer only. "Is the income at most 40? If not, is the debt at most 25?" asks about debt for high earners alone, so debt matters for them and not for the others.

Classes are {0,1}\{0, 1\} when there are two of them and 1,…,K1, \dots, K in general. A leaf can store any number of classes, so a tree needs no one-vs-rest wrapper.

Boxes and constants

Each leaf collects the inputs that give one fixed list of answers. Every answer cuts the space along a hyperplane parallel to an axis, so a leaf is a box with axis-parallel sides. Write A1,…,AJA_1, \dots, A_J for the boxes of the JJ leaves and cmc_m for the value stored in leaf mm. The tree is then a piecewise-constant function:

f(x)=∑m=1Jcm [x∈Am].f(x) = \sum_{m=1}^{J} c_m \, [x \in A_m] .

In regression cmc_m is the mean target of the training objects in the leaf. In classification it is the majority class or the vector of class shares. Read differently, ff is a linear model over JJ indicator features: the tree first builds the features [x∈Am][x \in A_m] from the data and then fits one weight per feature.

Take XOR, one of the course's running examples: class 1 at (0,1)(0, 1) and (1,0)(1, 0), class 0 at (0,0)(0, 0) and (1,1)(1, 1). No line separates the classes. A tree asks x1≤0.5x_1 \le 0.5 at the root and x2≤0.5x_2 \le 0.5 on each side, and its four leaves are pure. The effect of x2x_2 flips between the two halves, which is exactly the interaction a weighted sum lacks.

The form of the questions has three consequences.

  • A tree only compares a feature with thresholds. An increasing transformation of a feature moves the thresholds but does not change which objects go where. The tree needs no scaling.
  • Every boundary is a staircase of axis-parallel steps, so a diagonal costs many leaves. With 2000 training points split into classes by the line x2=x1x_2 = x_1, a tree with 16 leaves reaches test accuracy 0.9620.962, the fully grown tree with 43 leaves 0.9820.982, and logistic regression 0.9980.998.
  • Past the last threshold the prediction stops changing: a tree cannot extrapolate a trend.

Impurity is the loss of the best constant

Which question should a node ask? A good split makes the children purer than the parent. Purity is measured by an impurity H(S)H(S) of a node SS, the set of training objects that reach it. It is zero for a pure node and grows as the node gets mixed. The cleanest definition is the loss of the best constant prediction in the node:

H(S)=min⁡c1∣S∣∑i∈SL(yi,c).H(S) = \min_{c} \frac{1}{|S|} \sum_{i \in S} L(y_i, c) .

A split (j,t)(j, t) sends the objects with xij≤tx_{ij} \le t to the left child SℓS_\ell and the rest to the right child SrS_r. Its gain is the drop of the impurity weighted by the children's sizes:

Δ(j,t)=H(S)−∣Sℓ∣∣S∣H(Sℓ)−∣Sr∣∣S∣H(Sr).\Delta(j, t) = H(S) - \frac{|S_\ell|}{|S|} H(S_\ell) - \frac{|S_r|}{|S|} H(S_r) .

The best constants are known from the topic Expectation and variance in Probability Theory: the mean under squared loss, the median under absolute loss, the mode under 0–1 loss. Let pkp_k be the share of class kk in the node. Each loss gives a familiar criterion.

  • Squared error, regression. The best constant is the mean yˉS\bar y_S, and the impurity is the variance of the targets in the node. The targets 1,2,3,7,8,91, 2, 3, 7, 8, 9 have variance 58/6≈9.6758/6 \approx 9.67. The split between 3 and 7 leaves two nodes of variance 2/32/3 each, a gain of 9.09.0.
  • Log-loss. Predict a distribution c=(c1,…,cK)c = (c_1, \dots, c_K) and pay −log⁡cyi-\log c_{y_i}. The average loss −∑kpklog⁡ck-\sum_k p_k \log c_k is the cross-entropy between the class shares and cc. By Gibbs' inequality from the topic Entropy, cross-entropy and KL in Generative Models, it is smallest at c=pc = p. The impurity is therefore the entropy −∑kpklog⁡pk-\sum_k p_k \log p_k, and the gain is the information gain of ID3 (Quinlan, 1986).
  • Squared error on one-hot labels (the Brier score). The indicator [yi=k][y_i = k] has mean pkp_k, its best constant, and variance pk(1−pk)p_k(1 - p_k). The sum over classes is the Gini index of CART (Breiman et al., 1984):
HGini(S)=∑k=1Kpk(1−pk)=1−∑k=1Kpk2.H_{\text{Gini}}(S) = \sum_{k=1}^{K} p_k (1 - p_k) = 1 - \sum_{k=1}^{K} p_k^2 .
  • 0–1 loss. The best constant is the majority class, and the impurity 1−max⁡kpk1 - \max_k p_k is the misclassification rate of the node.

Gini has a second reading. Label every object of the node at random, class kk with probability pkp_k, regardless of its true class. An object of class kk gets a wrong label with probability 1−pk1 - p_k, so the expected share of wrong labels is the Gini index. For class counts 6,3,16, 3, 1 it equals 0.540.54.

Why not the error rate

Why not split by the misclassification rate itself, the quantity we finally care about? Because it is too coarse. Take a node with 8 objects of each class and two candidate splits:

  • split A gives children with class counts (7,3)(7, 3) and (1,5)(1, 5);
  • split B gives (8,4)(8, 4) and (0,4)(0, 4).

Both make 4 mistakes, so for both the error rate falls from 0.50.5 to 0.250.25. Yet B produces a pure node that needs no further splits. The smooth criteria see this: the weighted Gini index is 0.3670.367 for A and 0.3330.333 for B, the weighted entropy 0.7950.795 and 0.6890.689 bits.

The reason is the shape of the criteria. As a function of the class shares, 1−max⁡kpk1 - \max_k p_k is piecewise linear. Many splits tie, and a split can have zero gain while it still sorts the classes. Gini and entropy are strictly concave, so their gain is strictly positive whenever the children's class shares differ from the parent's. In practice the two choose nearly the same trees.

For two classes with share pp of class 1, the Gini index equals 2p(1−p)2p(1 - p), twice the variance of the 0/1 label. So a Gini tree for two classes is the regression tree on the 0/1 labels: the gains differ by a factor of 2, the splits are the same. Its leaf values pp are estimates of the probability of class 1 in each box.

Stopping and pruning

Grown until every leaf is pure, a tree fits any training set without errors, with one leaf per object if need be. Then it generalizes badly. There are two remedies.

Stopping rules end the recursion early: a maximal depth, a minimal number of objects in a leaf or in a split, a maximal number of leaves, a minimal gain. They are cheap, and libraries offer them first. Their weakness is XOR in another guise: a split that looks useless can enable a useful one below it, and a gain threshold stops too early.

Pruning grows a large tree T0T_0 first and then cuts it back. Cost-complexity pruning (Breiman et al., 1984) charges every leaf a price α≥0\alpha \ge 0:

Cα(T)=R^(T)+α ∣T∣.C_\alpha(T) = \hat R(T) + \alpha \, |T| .

Here T⊆T0T \subseteq T_0 is a subtree, ∣T∣|T| is its number of leaves, and R^(T)\hat R(T) is its training loss: for example the number of training errors, or, in scikit-learn, the leaves' impurities weighted by their shares of the objects. As α\alpha grows, the best subtrees form a nested sequence from T0T_0 down to the root alone.

Weakest-link pruning finds that sequence. Collapsing an internal node ss with subtree TsT_s into a leaf raises the loss from R^(Ts)\hat R(T_s) to R^(s)\hat R(s) and removes ∣Ts∣−1|T_s| - 1 leaves. It pays off once

α≥g(s)=R^(s)−R^(Ts)∣Ts∣−1.\alpha \ge g(s) = \frac{\hat R(s) - \hat R(T_s)}{|T_s| - 1} .

The node with the smallest gg is collapsed first, then gg is recomputed, and so on. A node that would make 6 errors as a leaf and makes 2 with its 4 leaves has g=4/3≈1.33g = 4/3 \approx 1.33.

The value of α\alpha is chosen by cross-validation on the training set, as in the topic Validation and overfitting. Note the shape of CαC_\alpha: training loss plus a penalty on complexity, the number of leaves here instead of a norm of the weights in the topic Regularization. On the breast cancer data (398 training and 171 test objects, 30 features):

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.tree import DecisionTreeClassifier
 
X, y = load_breast_cancer(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
full = DecisionTreeClassifier(random_state=0).fit(Xtr, ytr)
alphas = full.cost_complexity_pruning_path(Xtr, ytr).ccp_alphas
grid = GridSearchCV(DecisionTreeClassifier(random_state=0), {"ccp_alpha": alphas}, cv=5)
pruned = grid.fit(Xtr, ytr).best_estimator_
for tree in (full, pruned):
    print(tree.get_n_leaves(), tree.get_depth(), round(tree.score(Xte, yte), 3))
print(round(grid.best_params_["ccp_alpha"], 4))
16 6 0.906
6 4 0.918
0.0088

The fully grown tree has 16 leaves, depth 6, training accuracy 1.0 and test accuracy 0.9060.906. Pruning with α=0.0088\alpha = 0.0088 keeps 6 leaves and depth 4 and reaches 0.9180.918.

Categories and missing values

Categorical features. A feature with qq unordered levels, such as a city, has no thresholds. The natural binary split sends a subset of the levels to the left. There are 2q−1−12^{q-1} - 1 such splits, too many to try for large qq.

For two classes there is a shortcut. Order the levels by their share of class 1 and try only the q−1q - 1 splits that respect this order. The best of them is the best of all subsets for Gini and for entropy (Breiman et al., 1984). In regression with squared error the same holds with the levels ordered by their mean target (Fisher, 1958). Example: four levels A, B, C, D with 10 objects each and 2, 8, 3, 7 objects of class 1. The order is A, C, D, B, and among its three splits is the best of all seven, {A,C}\{A, C\} against {B,D}\{B, D\}, with weighted Gini 0.3750.375.

Two cautions. With more than two classes there is no such shortcut. And a feature with many levels offers many ways to split, so it can fit noise; pruning and validation control that. Ordering by the training targets is not leakage in the sense of the topic Data, features and leakage: it is part of the split search, like the choice of a threshold.

Missing values. A tree can keep the rows with gaps in several ways:

  • treat "missing" as a level of its own for a categorical feature;
  • surrogate splits (CART): rank the splits on other features by how well they reproduce the chosen split, and send an object with a missing value down the best surrogate it has;
  • a learned direction: compute the gain of each threshold twice, with all missing values sent left and with all sent right, and keep the better one. XGBoost does this, and so does scikit-learn;
  • C4.5 sends the object down both branches with weights proportional to the branch sizes and averages the predictions.

Library support varies. scikit-learn's DecisionTreeClassifier handles NaN but accepts only numbers, so categories must be encoded first. HistGradientBoostingClassifier, LightGBM and CatBoost split on categories directly.

Unstable trees, and what next

The greedy construction makes a tree an unstable model. A small change in the data can change the root split, and every split below inherits the change. Trees grown on two random halves of the breast cancer training set split the root on different features, worst perimeter and mean concave points, and disagree on 10.5%10.5\% of the test objects.

Depth controls the effect. Take 40 points of y=sin⁡2πx+εy = \sin 2\pi x + \varepsilon with xx uniform on [0,1][0, 1] and noise ε∼N(0,0.32)\varepsilon \sim \mathcal N(0, 0.3^2). Grow one tree on each of two independent samples and repeat 500 times. The table gives the average squared errors. The gap is the mean over xx of the squared difference between the two trees, and no model can have a test error below the noise variance 0.090.09.

depth leaves train error test error gap
1 2 0.162 0.204 0.091
3 8 0.060 0.149 0.113
unlimited 40 0 0.186 0.192

"Flexible models overfit" is true but vague. The next topic, Bias–variance decomposition, splits the expected test error of any learning method into three parts: noise, squared bias and variance. That split explains this table, the choice of depth for trees, of kk for nearest neighbours and of λ\lambda for ridge, and why averaging many trees should help.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.