Decision trees
Split the data with yes/no questions until the leaves are pure, and learn how to stop before the tree memorises noise.
Lesson 27 of 6614 minIntermediate
You will learn to
- Explain how a decision tree chooses its questions and makes a prediction
- Name the hyperparameters that limit tree size and their effect
- Say when a single tree is a good or a bad choice
Before this lesson
Intuition
Think of the game of twenty questions. To guess an animal you ask "Does it fly?", then, depending on the answer, a different next question. A decision tree does the same with your rows. It asks a yes/no question about one column, sends the row down the "yes" or "no" branch, and asks another question there. When the questions stop, the row lands in a leaf, and the leaf holds the prediction: the majority class for classification, or the average target for regression.
The tree is learned, not written. At every step it looks for the question that separates the rows best, meaning that each group afterwards is as close to one class as possible.
Trees read like a flowchart, so they are easy to explain. They need little preparation: no scaling, and they cope with different kinds of columns. The price is stability. A tree allowed to grow without limit keeps asking questions until each leaf holds a handful of rows, which is memorisation. See Overfitting and the bias-variance trade-off.
Picture it
Each question is a vertical or horizontal cut through the feature space, so a tree carves the space into rectangles. With one input, the cuts are points on a line, as in the picture. With two inputs the leaves are boxes. This is why trees fit step-like patterns well, and smooth diagonal patterns badly (they need many small steps).
The math
To decide how good a node is, trees use an impurity measure. For a node where a fraction of the rows belong to class , the Gini impurity is
It is 0 when the node is pure and is largest when the classes are evenly mixed (0.5 for two classes). The other common measure is entropy, . The two usually give very similar trees.
A split sends rows left and rows right out of . Its quality is the weighted impurity of the children:
The tree picks, over every column and every threshold, the split with the lowest , then repeats inside each child. For regression, the impurity is the variance of the target in the node, and a leaf predicts the mean. Growth stops when a limit is reached: maximum depth, minimum rows to split or in a leaf, or no improvement.
Worked example
Eight customers, with tenure in months and whether they churned (1) or stayed (0):
| Tenure | 2 | 4 | 6 | 9 | 12 | 18 | 24 | 30 |
|---|---|---|---|---|---|---|---|---|
| Churned | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 |
Four of eight churned, so the root impurity is 1 - (0.5² + 0.5²) = 0.5. Candidate splits sit between neighbouring tenures:
| Split | Left rows (churned) | Right rows (churned) | Weighted impurity |
|---|---|---|---|
| under 3 | 1 (1) | 7 (3) | 0.43 |
| under 5 | 2 (2) | 6 (2) | 0.33 |
| under 7.5 | 3 (3) | 5 (1) | 0.20 |
| under 10.5 | 4 (3) | 4 (1) | 0.38 |
| under 21 | 6 (4) | 2 (0) | 0.33 |
For "under 7.5" the left group is pure (impurity 0) and the right group has one churner in five rows, impurity 1 - (0.2² + 0.8²) = 0.32. The weighted impurity is (3/8) x 0 + (5/8) x 0.32 = 0.20. That is the lowest, so it is the first question. The impurity fell from 0.5 to 0.20.
The remaining question is whether to split the right group again to chase the single churner at 18 months. With eight rows that would be memorising one customer, which is exactly what the depth and leaf-size limits prevent.
A computed comparison on a sample dataset with 768 rows, scored with 5-fold stratified cross-validation in scikit-learn (seed 42): an unlimited tree reaches an accuracy of 0.70, while a tree limited to depth 3 reaches 0.75. The simpler tree wins on unseen folds.
How mlflow does it
The algorithms are Decision Tree Classifier and Decision Tree Regressor (dt). The parameters you can tune include max_depth (searched from 1 to 15), min_samples_leaf, min_samples_split, max_features, criterion (gini or entropy for classification) and min_impurity_decrease. In Automatic mode the tree uses the library defaults, which means no depth limit. Switch the card to Manual to set a limit; the tooltip next to each parameter explains what raising or lowering it does.
Common mistakes
- Using a single unlimited tree and trusting its training score. It always reaches near-perfect training accuracy. Judge it on cross-validation and limit the depth.
- Expecting a smooth prediction. A tree predicts step functions. For a smooth relationship, a linear model or an ensemble of trees is a better fit.
- Assuming the tree is stable. A small change in the training rows can change the top question and everything below it. Do not over-interpret one tree. Random forests fix this.
- Encoding categories as arbitrary numbers and forgetting the order is meaningless. A split like "city code under 5" is not meaningful for nominal codes. Use one-hot encoding when the categories have no order.
- Reading feature importance from a single deep tree. It reflects the noise in that tree. Use cross-validated or permutation importance.
Try it in mlflow
Grow a tree, then limit its depth
- Open Pipelines and pick a classification pipeline.
- Open the Models part, search for Decision Tree Classifier and add it in Automatic mode.
- Add it a second time, switch that card to Manual and lower max_depth to 3.
- Click Train and compare the cross-validated scores of the two cards. The shallow tree is often better on new data.