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

yesnotenure < 7.5 ?8 rows, impurity 0.50churn3 of 3 rowsimpurity 0stay4 of 5 rowsimpurity 0.32tenure (months)07.51530churnstay
One question (tenure under 7.5 months) cuts the tenure axis in two. The left group is pure; the right group still mixes classes and could be split again.

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 pkp_k of the rows belong to class kk, the Gini impurity is

G=1−∑kpk2G = 1 - \sum_k p_k^{2}

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, −∑kpkln⁡pk-\sum_k p_k \ln p_k. The two usually give very similar trees.

A split sends nLn_L rows left and nRn_R rows right out of nn. Its quality is the weighted impurity of the children:

Gsplit=nLnGL+nRnGRG_{\text{split}} = \frac{n_L}{n} G_L + \frac{n_R}{n} G_R

The tree picks, over every column and every threshold, the split with the lowest GsplitG_{\text{split}}, 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):

Tenure246912182430
Churned11100100

Four of eight churned, so the root impurity is 1 - (0.5² + 0.5²) = 0.5. Candidate splits sit between neighbouring tenures:

SplitLeft rows (churned)Right rows (churned)Weighted impurity
under 31 (1)7 (3)0.43
under 52 (2)6 (2)0.33
under 7.53 (3)5 (1)0.20
under 10.54 (3)4 (1)0.38
under 216 (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

  1. Open Pipelines and pick a classification pipeline.
  2. Open the Models part, search for Decision Tree Classifier and add it in Automatic mode.
  3. Add it a second time, switch that card to Manual and lower max_depth to 3.
  4. Click Train and compare the cross-validated scores of the two cards. The shallow tree is often better on new data.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. How does a decision tree choose the question to ask at a node?
  2. 2. A tree scores 100% on its training rows and 70% in cross-validation. Which change is most likely to help?
  3. 3. Which statement about decision trees is true?