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 classes, and independent sigmoids handle several labels at once. Every one of those models scores an object by a weighted sum of its features, .
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 .
A decision tree starts from the other end. Its building block is a yes-or-no question about one feature, . 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 when there are two of them and 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 for the boxes of the leaves and for the value stored in leaf . The tree is then a piecewise-constant function:
In regression 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, is a linear model over indicator features: the tree first builds the features from the data and then fits one weight per feature.
Take XOR, one of the course's running examples: class 1 at and , class 0 at and . No line separates the classes. A tree asks at the root and on each side, and its four leaves are pure. The effect of 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 , a tree with 16 leaves reaches test accuracy , the fully grown tree with 43 leaves , and logistic regression .
- 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 of a node , 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:
A split sends the objects with to the left child and the rest to the right child . Its gain is the drop of the impurity weighted by the children's sizes:
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 be the share of class in the node. Each loss gives a familiar criterion.
- Squared error, regression. The best constant is the mean , and the impurity is the variance of the targets in the node. The targets have variance . The split between 3 and 7 leaves two nodes of variance each, a gain of .
- Log-loss. Predict a distribution and pay . The average loss is the cross-entropy between the class shares and . By Gibbs' inequality from the topic Entropy, cross-entropy and KL in Generative Models, it is smallest at . The impurity is therefore the entropy , and the gain is the information gain of ID3 (Quinlan, 1986).
- Squared error on one-hot labels (the Brier score). The indicator has mean , its best constant, and variance . The sum over classes is the Gini index of CART (Breiman et al., 1984):
- 0–1 loss. The best constant is the majority class, and the impurity is the misclassification rate of the node.
Gini has a second reading. Label every object of the node at random, class with probability , regardless of its true class. An object of class gets a wrong label with probability , so the expected share of wrong labels is the Gini index. For class counts it equals .
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 and ;
- split B gives and .
Both make 4 mistakes, so for both the error rate falls from to . Yet B produces a pure node that needs no further splits. The smooth criteria see this: the weighted Gini index is for A and for B, the weighted entropy and bits.
The reason is the shape of the criteria. As a function of the class shares, 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 of class 1, the Gini index equals , 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 are estimates of the probability of class 1 in each box.
Greedy split search
Searching for the best tree is hopeless. Building the binary tree that identifies every training object with the fewest tests on average is NP-complete (Hyafil and Rivest, 1976). So every practical algorithm is greedy: choose the best split of the root, recurse into each child, and never revisit a decision.
The best split of one node, though, is found exactly. For a feature , sort the node's values. The candidate thresholds are the midpoints between consecutive distinct values. Sweep them in order, moving objects one at a time from the right child to the left. The class counts, or the sums and in regression, update in constant time, and so does the gain. One node costs for sorting plus for the sweep.
The nodes at one depth partition the training set. One level therefore costs , and a tree of depth costs
Greed has a price. On XOR every root split leaves one object of each class on each side, so the gain of every root split is zero, although two levels classify all four points. An algorithm that refuses splits without gain never starts; one that accepts them finds the tree.
On large data, libraries replace the exact search by a histogram. Each feature is binned once into at most a few hundred bins, of them, and only the bin edges are tried. Filling a node's histogram still touches each of its objects once, but there is no sorting, and the sweep costs instead of . The boosting libraries of the topic Gradient boosting are built on this.
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 first and then cuts it back. Cost-complexity pruning (Breiman et al., 1984) charges every leaf a price :
Here is a subtree, is its number of leaves, and 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 grows, the best subtrees form a nested sequence from down to the root alone.
Weakest-link pruning finds that sequence. Collapsing an internal node with subtree into a leaf raises the loss from to and removes leaves. It pays off once
The node with the smallest is collapsed first, then is recomputed, and so on. A node that would make 6 errors as a leaf and makes 2 with its 4 leaves has .
The value of is chosen by cross-validation on the training set, as in the topic Validation and overfitting. Note the shape of : 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.0088The fully grown tree has 16 leaves, depth 6, training accuracy 1.0 and test accuracy . Pruning with keeps 6 leaves and depth 4 and reaches .
Categories and missing values
Categorical features. A feature with unordered levels, such as a city, has no thresholds. The natural binary split sends a subset of the levels to the left. There are such splits, too many to try for large .
For two classes there is a shortcut. Order the levels by their share of class 1 and try only the 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, against , with weighted Gini .
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 of the test objects.
Depth controls the effect. Take 40 points of with uniform on and noise . 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 of the squared difference between the two trees, and no model can have a test error below the noise variance .
| 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 for nearest neighbours and of for ridge, and why averaging many trees should help.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.