Traditional models · lesson 4 of 16
Parts in this lesson
A1 - np.sum(p ** 2)Gini impurity
BDecisionTreeClassifier(max_depth=2)a tree, and how deep it may grow
Cexport_text(tree, feature_names=[...])the tree as rules
DDecisionTreeRegressor(max_depth=2)a tree that predicts numbers

Decision trees

Last updated

A decision tree plays twenty questions with the data: is the bill longer than 42 mm? Is it deeper than 16? Each answer narrows the choices until one species is left. Trees need no scaling, handle any mix of features, and print as rules a person can check. They also overfit as soon as you let them, which is why lessons 4.5 and 4.6 grow whole forests of them.

By the end of this lesson you can

  • Measure how mixed a group is with Gini impurity and entropy
  • Choose a split by information gain, and grow a tree one question at a time
  • Fit DecisionTreeClassifier and DecisionTreeRegressor, and read their rules
  • Control overfitting with the tree's depth

Twenty questions

In the game of twenty questions, a good first question splits the possibilities roughly in half ("Is it alive?"), and each answer leads to the next question. A decision tree classifies the same way. Each node asks one yes-or-no question about one feature, "is the bill length at most 42.35 mm?", and sends the penguin left or right. At the bottom, each leaf gives an answer.

Grow one on the penguins' bill length and depth, a level at a time:

Tree grower342 penguins, Gini impurity
35404550551416182022bill length (mm)bill depth (mm)yesnolength ≤ 42.35?AdeGen

1 question, 2 rectangles, and 259 of 342 penguins (75.7%) labelled right. Every cut is straight and across one axis: a tree can only ask “is this feature at most this number?”.

At depth 0 there are no questions: every penguin is called Adelie, the commonest, and 151 of 342 are right. One question, on bill length, separates most Adelies from the rest. A second level, on bill depth, splits the long-billed penguins into Gentoos (shallow bills) and Chinstraps (deep). Every boundary is a straight cut across one axis, so the regions are always rectangles.

How mixed is a group? Gini and entropy

A good question leaves groups that are each mostly one species. To compare questions, measure how mixed a group is. With pc the share of the group in class c:

G=1−∑cpc2H=−∑cpclog2⁡pc

Gini impurity G is the chance that two penguins drawn at random from the group (with replacement) are of different species. Entropy H is lesson 1.11's average surprise, in bits. Both are 0 for a pure group and largest for an even mix:

trees.ipynb

50 of one kind: 0 and 0. Half and half of two: Gini 0.5, entropy 1 bit. An even three-way mix: Gini 0.666, entropy 1.584 bits, the most they can be with three classes. The two measures nearly always choose the same split; scikit-learn uses Gini by default because it skips the logarithm.

Choosing a split: information gain

A split is good if the groups it makes are, on average, much purer than the group it started with. The information gain of a split is the impurity before minus the impurity after, each side weighted by its share of the penguins:

gain=G(parent)−nleftnG(left)−nrightnG(right)

For all 342 penguins and "bill length ≤ 42.35":

trees.ipynb

The parent, 151 Adelie, 68 Chinstrap and 123 Gentoo, has Gini 0.636. The left side, 139, 1 and 3, is nearly pure: 0.055. The right side is still mixed, 0.519. The gain is 0.311.

To grow a tree, the algorithm (CART, Breiman and others, 1984) tries every feature and every threshold between two neighbouring values, keeps the split with the biggest gain, and then does the same again inside each side. It's greedy: it takes the best split now, without looking ahead to see whether a worse split now would allow better ones later.

DecisionTreeClassifier, and its rules

scikit-learn's tree, on 70% of the penguins, two levels deep:

trees.ipynb

export_text prints the tree as nested rules, and you can read them aloud: "if the bill is at most 42.35 mm long and more than 15.3 mm deep, it's an Adelie". A vet could check them against what they know. Few models can be read this easily, and when a decision has to be explained to the person it affects, that matters.

trees.ipynb

93.7% on its training penguins and 93.2% on the test penguins: two questions, used twice, and almost no overfitting.

Wrong way: a depth-30 tree

Left alone, a tree keeps splitting until every leaf is pure, with one leaf for every awkward point if it has to. On the noisy moons data:

trees.ipynb

The columns are the depth allowed, the number of leaves, then the training and test accuracy. With depth 30 the tree has 31 leaves and scores 100% on its training points, but only 88.5% on new ones; depth 3, with 8 leaves, did better at 90.5%. Look at the regions:

trees.ipynb

The deep tree has carved little rectangles around single points that fell on the wrong side of the noise. It has memorised the training set (lesson 2.6). The cures are limits on growth: max_depth, min_samples_leaf (no leaf with fewer than this many points), or ccp_alpha (prune back the splits that gain least). Choose them by cross-validation (lesson 4.13).

A second weakness: small changes to the data can change the first split, and with it the whole tree. Trees are unstable. Lesson 4.5 turns that weakness into a strength.

Trees for numbers

A regression tree asks the same kind of questions, but each leaf predicts a number, the mean of the training labels that reach it. Splits are chosen to reduce the squared error instead of the Gini impurity. Body mass from flipper length:

trees.ipynb

Four leaves, four masses: 3,574 g for flippers up to 195.5 mm, up to 5,492 g past 217.5 mm. Against a straight line, and a depth-20 tree:

trees.ipynb

A regression tree's prediction is a staircase: flat between thresholds, jumping at each one. The depth-2 tree (RMSE 419 g on the test penguins) and the straight line (391 g) are close; the depth-20 tree memorises its training penguins (315 g) and does worst on new ones (473 g). And a tree can never predict outside the range of its training labels: past the last step, it stays flat.

When to use it

When to use a decision tree

Good at

  • Rules a person can read, check and explain
  • Any mix of numbers and categories, with no scaling
  • Effects that switch on above a threshold, and interactions
  • Fast to train and to predict

Bad at

  • Accuracy: a single tree is usually beaten by a forest or boosting
  • Stability: a small change in the data can grow a different tree
  • Smooth or diagonal boundaries, which it builds from many small steps
  • Predicting beyond the range of the training labels

Needs from you

  • A depth limit, or a minimum leaf size, chosen by cross-validation
  • No scaling

In scikit-learn

  • Classification: DecisionTreeClassifier
  • Regression: DecisionTreeRegressor

Check what you learned

A group of penguins is 40 Adelie and 40 Gentoo. What is its Gini impurity?
Your tree scores 100% on training data and 80% on test data. Which change is most likely to help?
A regression tree is trained on houses priced ₱1 million to ₱20 million. What does it predict for a mansion far bigger than any in training?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning