ML fundamentals9 / 22

Lesson 9 · Other ways to draw a boundary

Decision trees

The problem

Back to the pizza shop's rush-hour data. Each delivery has two features: the distance in km and the time it was sent. Most of the evening, trips over about 6 km run late. Around 19:00 the roads jam, and even short trips run late.

on time late P = 0.5
The rush-hour data: 200 deliveries, ○ on time and × late. The line is the rule that made the data. Late trips sit above it.

Logistic regression draws one straight line through this picture and gets 76% of new deliveries right. Nearest neighbours follows the dip, but it has to keep every past delivery and search them for each new one.

A shift manager would do something else. They'd write a few rules of thumb on a card:

  1. Is the trip 6 km or more? Then it will be late.
  2. If not, was it sent between 18:30 and 19:30? Then it will be late.
  3. Otherwise, it will be on time.

This lesson turns that card into a model, and then lets the data write the card.

A tree of questions

Here's the manager's card drawn two ways. On one side it's a flowchart of questions. On the other, it's the plane cut into rectangles, one for each final answer.

yesyesnoyesnonokm < 6?99 : 101time < 18:30?96 : 62on time26 : 12time < 19:30?70 : 50late3 : 28on time67 : 22late3 : 39

Counts are on time : late.

1718192021222302468time sent (hour)distance (km)

on timelate

This rule gets 160 of the 200 deliveries right (80%). Tap a box or a rectangle to see where it is in the other picture.

The manager's rule of thumb as a tree (each box is a question; 'yes' goes left) and as the rectangles it cuts the plane into. Counts under each box are on time : late.

Things to notice:

  • Each question looks at one feature and compares it with a number. So each cut is a straight line parallel to an axis.
  • The cuts nest. The time questions only apply to trips under 6 km, so their lines stop at 6 km.
  • Each end of the flowchart owns one rectangle. Every delivery in that rectangle gets the same answer.

This is a decision tree. The words come from the picture of the flowchart, drawn upside down:

  • The first question, at the top, is the root.
  • Each question is a node. Its two answers lead to two branches.
  • An end of the flowchart, with no question left, is a leaf. A leaf predicts the most common label among the training deliveries that reach it.
  • The depth of a tree is the most questions any delivery has to answer. The manager's tree has depth 3.

To predict for a new delivery, start at the root and follow the answers down to a leaf. A 4 km trip sent at 19:00: under 6 km? Yes. Before 18:30? No. Before 19:30? Yes. That's the leaf with 3 on time and 28 late, so the tree says late.

The manager's rule gets 160 of the 200 deliveries right. Could a better card exist? To find out, we need a way to score a question.

Which question first?

A good question splits the deliveries into groups that are each mostly one label. A group with only late deliveries is pure: once a delivery lands there, you know the answer. So we want questions that make the groups as pure as possible.

Here are eight deliveries, small enough to count by hand. Half were late.

DeliveryDistance (km)Sent in rush hour?Late?
A1.5nono
B2.5yesno
C3.5nono
D4.5yesyes
E5.5yesyes
F6.0yesyes
G6.5nono
H7.0noyes

Two questions you could ask first:

  • Split A: "Is it more than 4 km?" Yes gives D, E, F, G, H (4 late, 1 on time). No gives A, B, C (0 late, 3 on time).
  • Split B: "Was it sent in rush hour?" Yes gives B, D, E, F (3 late, 1 on time). No gives A, C, G, H (1 late, 3 on time).

Predict first

Which split leaves purer groups?

Gini impurity

We need one number that says how mixed a group is. Here's one. Pick a delivery from the group at random, put it back, and pick again. How likely is it that the two picks have different labels?

  • In a pure group, the picks always agree. The chance is 0.
  • In a 50–50 group, they disagree half the time. The chance is 0.5, the most it can be with two labels.

This chance is the Gini impurity of the group.

Worked example

Scoring split A

  1. The "more than 4 km" group has 4 late and 1 on time. A random pick is late with probability 4/5=0.84/5 = 0.8 and on time with probability 0.20.2.

Now try every place to cut along distance. Drag the cut, and watch the score below.

012345678distance (km)ABCDEFGH

Under 4 km: 0 late, 3 on time → Gini 0

Over 4 km: 4 late, 1 on time → Gini 0.32

Weighted: 0.2

For comparison, “sent in rush hour?” scores 0.375.

01234567800.20.40.6where the cut is (km)Gini impurity0.2

Below: the weighted Gini impurity for every place you could cut. The best cut is the lowest point.

The eight deliveries along distance (○ on time, × late). Drag the cut. The readout scores the two groups; the curve below shows the weighted score for every cut.

Things to notice:

  • The score only changes when the cut passes a delivery. Between two deliveries, the groups stay the same.
  • The lowest point is any cut between C (3.5 km) and D (4.5 km). That's split A. Trees put the cut halfway, at 4 km.
  • Cutting at 1 km or 7.5 km puts everyone in one group. The score stays at 0.5: the question taught us nothing.

The maths

If a fraction pkp_k of a group has label kk, its Gini impurity is

G=1−∑kpk2.G = 1 - \sum_k p_k^2 .

For two labels this is the same as the worked example: 1−(0.82+0.22)=1−0.68=0.321 - (0.8^2 + 0.2^2) = 1 - 0.68 = 0.32. The sum ∑kpk2\sum_k p_k^2 is the chance that two picks agree, so 1 minus it is the chance they disagree.

A split sends nLn_L of the nn examples left and nRn_R right. Its score is the weighted average

nLn GL+nRn GR.\frac{n_L}{n}\, G_L + \frac{n_R}{n}\, G_R .

In words: each side's impurity counts in proportion to how many examples it holds. A tiny pure group can't make a split look good on its own. In the figure, GLG_L and GRG_R are the two readout lines, and the weighted score is the height of the curve.

Entropy and information gain

Gini impurity isn't the only way to measure a mix. The entropy of the labels works too: it's the average surprise of a label, in bits. A pure group has entropy 0, and a 50–50 group has 1 bit.

With entropy, the score of a split is how much it lowers the entropy. This is called information gain:

gain=H(before)−(nLn HL+nRn HR).\text{gain} = H(\text{before}) - \Big(\frac{n_L}{n}\, H_L + \frac{n_R}{n}\, H_R\Big).

Worked example

Information gain of splits A and B

  1. Before splitting, 4 late and 4 on time: H=1H = 1 bit.

The two measures almost always choose the same split, so the choice rarely matters. Gini impurity is scikit-learn's default, and it's a little cheaper to compute, because it needs no logarithm.

Growing a tree

Now let the data write the card. The recipe, called CART (classification and regression trees), is:

  1. Put all the training deliveries in one group: the root.
  2. Try every feature, and every cut halfway between two neighbouring values of it. Score each cut by its weighted Gini impurity.
  3. Keep the cut with the lowest score. It splits the group in two.
  4. Repeat steps 2 and 3 on each new group, until a group is pure or the tree reaches its depth limit.

Step through it on the 200 rush-hour deliveries, with a depth limit of 3.

late99 : 101

Counts are on time : late.

1718192021222302468time sent (hour)distance (km)

on timelate

Split 0 of 7

No questions yet: one leaf holds all 200 deliveries (99 on time, 101 late), so the tree says “late” for everyone.

Training accuracy: 50.5%

A tree growing on the rush-hour data, one split per step: the tree (counts are on time : late) and the plane, cut into one rectangle per leaf. The newest split is outlined.

Things to notice:

  • The first question is km < 4.87?. Of all 343 possible cuts (176 on distance, 167 on time), it lowers the Gini impurity most, from 0.500 to 0.364.
  • Every split is a cut parallel to an axis, inside one rectangle. Together they make a staircase that roughly follows the dip.
  • Training accuracy climbs with each split: 50.5% with no questions, 75% after one, 91% after seven.
  • Some leaves exist only to catch odd deliveries. Step 5 makes a leaf for three short trips sent after 22:40 (two of them late). Step 7 makes one for a single long trip that was on time. These are probably the 5% of labels that were flipped at random.

Each split is the best one right now. The tree never goes back to change an earlier question, even if a different first question would have led to a better tree. Choosing this way is called greedy. Searching every possible tree for the best one would take far too long, even for small data, so every common tree method is greedy.

Predict first

Suppose the true rule were a diagonal line: late when km is more than (hour − 17). What would a tree's boundary look like?

How deep should a tree grow?

Without a limit, a tree keeps splitting until every leaf is pure. Drag the depth and watch both pictures.

on time late P = 0.5

8 leaves · training 91.0% · validation 87.0%

1234567891070%75%80%85%90%95%100%maximum depthaccuracy— training- - validation
A tree with the chosen maximum depth. The shading is each leaf's share of late deliveries, and the dark line is where it crosses one half. Below: accuracy on the training deliveries (solid) and on 200 new validation deliveries (dashed).

Predict first

With no depth limit, what's the tree's accuracy on its own training data?

Things to notice:

  • Training accuracy only goes up: 75% at depth 1, 91% at depth 3, 100% at depth 10 (36 leaves).
  • Validation accuracy stops improving after depth 3. From there it stays between 86.5% and 87.5%.
  • The deep trees draw small islands around single deliveries. Those islands fit noise, not the dip.

This is overfitting. A tree's depth sets its capacity: one more level can double the number of leaves. A shallow tree misses the dip (high bias); a deep one chases every flipped label (high variance). That's the bias–variance trade-off again.

The fix is pruning: limiting a tree, or cutting it back, so that it doesn't grow a leaf for every noisy example. There are two ways:

  • Stop early. Cap the depth, or require every leaf to hold at least some number of training examples. Switch the figure to "Leaves of 5 or more" and set the depth to 6 or more. The tree stops at 20 leaves, with 90% on training and 91% on validation. That's better than any depth limit alone.
  • Grow, then cut back. Grow the full tree, then remove the splits that help least for the leaves they add. scikit-learn calls this cost-complexity pruning, set by ccp_alpha.

Either way, the limit is a hyperparameter. Choose it with a validation set or cross-validation, never with the training score.

DigressionRegression trees: leaves predict the averageThe same tree can predict a number, like minutes, by averaging its leaf. · 2 min

Trees also do regression. Suppose the label is the delivery time in minutes. Two things change.

  • A leaf predicts the average of its training examples. A leaf holding deliveries of 20, 24 and 28 minutes predicts 24.
  • Splits are scored by spread, not purity. Each group's impurity is its variance: the average squared distance from the group's mean. A split is good if both groups have small variance, so each leaf's average is a good guess for its members.

The weighted average is the same as before. For a group of 20, 24 and 28 minutes, the variance is (16+0+16)/3=10.7(16 + 0 + 16) / 3 = 10.7. Split off the 28 and the groups {20,24}\{20, 24\} and {28}\{28\} have variances 4 and 0. The weighted score is 23×4+13×0=2.7\tfrac{2}{3} \times 4 + \tfrac{1}{3} \times 0 = 2.7, so the split helps.

A regression tree's prediction is a step function: flat inside each rectangle, jumping at each cut. Boosting builds its models out of small regression trees, so you'll see these steps again in boosting. In scikit-learn it's DecisionTreeRegressor, whose default criterion, "squared_error", is this variance.

DigressionTrees are easy to read, while they're smallA depth-3 tree is a flowchart anyone can check. A depth-10 tree is not. · 2 min

The depth-3 tree from the step-through fits on an index card:

  • Under 4.87 km, sent between 18:14 and 19:50: late (30 of 33).
  • Under 4.87 km, sent before 18:14 or between 19:50 and 22:40: on time.
  • 4.87 km or more: late, except trips from 4.87 to 5.68 km sent after 21:02, and one trip over 7.95 km.

A manager can read it, check it against what they know, and spot the odd leaves (like "late after 22:40", which rests on three deliveries). That's a real strength. In some settings, such as lending, people may need to be told why a decision was made, and a small tree can tell them.

It doesn't last. The full tree on this data has 36 leaves and depth 10. Each leaf is still a rectangle you could describe, but nobody can hold 36 rules in their head, or see which ones are noise. Forests of hundreds of trees, in the next lesson, give up readability completely, in exchange for accuracy.

DigressionWhere decision trees come fromCART, ID3 and the two impurity measures, from the 1980s. · 1 min

Two lines of work in the 1980s made trees a standard tool.

  • CART (Classification and Regression Trees) is a 1984 book by Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone. It grows binary trees with Gini impurity for classification and variance for regression, then prunes them with cost-complexity pruning. The trees in scikit-learn are an optimised version of CART.
  • ID3, by Ross Quinlan (published in 1986), chose splits by information gain. Its successor, C4.5 (1993), added pruning and handled missing values and numeric features.

Breiman went on to invent bagging and random forests, the subject of the next lesson.

In scikit-learn

A tree is a scikit-learn estimator, so it has .fit, .predict and .score. DecisionTreeClassifier uses Gini impurity by default (criterion="entropy" switches to information gain). export_text prints the tree as nested rules:

A depth-3 tree on the rush-hour data
def fit_tree(max_depth: int | None = 3, min_samples_leaf: int = 1) -> DecisionTreeClassifier:
    """A classification tree on the rush-hour data (features: distance in km, hour sent)."""
    x_train, y_train, _, _ = load_rush_hour()
    tree = DecisionTreeClassifier(max_depth=max_depth, min_samples_leaf=min_samples_leaf, random_state=0)
    return tree.fit(x_train, y_train)


tree = fit_tree(max_depth=3)
print(export_text(tree, feature_names=["km", "hour"], class_names=["on time", "late"]))
|--- km <= 4.87
|   |--- hour <= 19.83
|   |   |--- hour <= 18.24
|   |   |   |--- class: on time
|   |   |--- hour >  18.24
|   |   |   |--- class: late
|   |--- hour >  19.83
|   |   |--- hour <= 22.67
|   |   |   |--- class: on time
|   |   |--- hour >  22.67
|   |   |   |--- class: late
|--- km >  4.87
|   |--- km <= 5.68
|   |   |--- hour <= 21.02
|   |   |   |--- class: late
|   |   |--- hour >  21.02
|   |   |   |--- class: on time
|   |--- km >  5.68
|   |   |--- km <= 7.95
|   |   |   |--- class: late
|   |   |--- km >  7.95
|   |   |   |--- class: on time

It's the same tree as the step-through. The text uses <= where the figure uses <. No training delivery sits exactly on a cut, so they agree. Hours are in decimal: 19.83 is 19:50. For a drawing instead of text, sklearn.tree.plot_tree draws the same tree with matplotlib.

To choose a depth, fit one tree per setting and compare training and validation scores:

Training and validation accuracy against depth
def depth_sweep(depths: list[int | None]) -> list[tuple[int | None, int, float, float]]:
    """For each maximum depth: (depth, leaves, training accuracy, validation accuracy)."""
    x_train, y_train, x_val, y_val = load_rush_hour()
    rows = []
    for depth in depths:
        model = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(x_train, y_train)
        rows.append((depth, model.get_n_leaves(), model.score(x_train, y_train), model.score(x_val, y_val)))
    return rows


for depth, leaves, train_acc, val_acc in depth_sweep([1, 2, 3, 4, 6, 8, None]):
    print(f"max_depth={str(depth):>4}  leaves={leaves:>2}  train {train_acc:.1%}  validation {val_acc:.1%}")
max_depth=   1  leaves= 2  train 75.0%  validation 77.0%
max_depth=   2  leaves= 4  train 78.0%  validation 78.5%
max_depth=   3  leaves= 8  train 91.0%  validation 87.0%
max_depth=   4  leaves=14  train 93.0%  validation 88.5%
max_depth=   6  leaves=28  train 97.5%  validation 84.5%
max_depth=   8  leaves=34  train 99.5%  validation 89.5%
max_depth=None  leaves=36  train 100.0%  validation 89.5%

Up to depth 3 these match the figure exactly. Deeper trees differ by a few deliveries. When two cuts score exactly the same, scikit-learn picks between them at random (set by random_state), and the figure picks the first. Either way, validation accuracy wobbles between about 85% and 90% once the tree is deep, while training accuracy heads to 100%. With 200 validation deliveries, one delivery is half a percentage point, so differences of a point or two are mostly noise.

Limiting the leaf size is often the better knob:

Pruning by leaf size
def leaf_size_sweep(sizes: list[int]) -> list[tuple[int, int, float]]:
    """For each min_samples_leaf: (size, leaves, validation accuracy) for an otherwise unlimited tree."""
    _, _, x_val, y_val = load_rush_hour()
    return [(size, (m := fit_tree(None, size)).get_n_leaves(), m.score(x_val, y_val)) for size in sizes]


for size, leaves, val_acc in leaf_size_sweep([1, 5, 20]):
    print(f"min_samples_leaf={size:>2}  leaves={leaves:>2}  validation {val_acc:.1%}")
min_samples_leaf= 1  leaves=36  validation 89.5%
min_samples_leaf= 5  leaves=20  validation 91.0%
min_samples_leaf=20  leaves= 8  validation 86.5%

Leaves of at least 5 give the best validation score here, with 20 leaves. Leaves of 20 are too coarse to follow the dip.

Putting it together

Use the depth-3 tree from the step-through to predict two new deliveries.

Worked example

Two deliveries through the depth-3 tree

  1. A 3 km trip sent at 19:00. Root: km < 4.87? Yes, go left.

Common misconceptions

"A deeper tree is a better tree." A deeper tree always fits the training data better. On new data it usually gets worse after a point, because the extra leaves fit noise. Compare depths on validation data.

"With enough depth, a tree can draw any boundary exactly." Only boundaries made of cuts parallel to the axes. A slanted or curved boundary becomes a staircase. More depth makes the steps smaller, and it needs many more leaves.

"Trees need scaled features, like nearest neighbours." No. Each question compares one feature with a threshold. Measure distance in metres instead of km and the threshold becomes 4,870 instead of 4.87; the tree is otherwise the same. Compare feature scaling, which matters for distance-based models.

"The tree is the best possible tree." It's greedy: each split is the best one at that moment. A different first question might lead to a smaller or more accurate tree, but the method never looks back.

"Gini or entropy: picking the right one matters a lot." They nearly always choose the same split. The depth and leaf-size limits matter far more.

Recap

  • A decision tree is a flowchart of yes/no questions, each comparing one feature with a threshold. Its leaves cut the plane into rectangles, so its boundary is a staircase.
  • Gini impurity is the chance that two random picks from a group disagree: 1−∑kpk21 - \sum_k p_k^2. Entropy is the alternative; the drop in entropy is the information gain.
  • A tree grows greedily: at each group, it tries every feature and every cut, and keeps the one with the lowest weighted impurity.
  • With no limit, a tree reaches 100% training accuracy by fitting noise. Pruning (a depth cap, a minimum leaf size, or cutting back) fixes this; choose the limit with validation data.
  • scikit-learn names in this lesson: DecisionTreeClassifier (max_depth, min_samples_leaf, criterion, ccp_alpha), .fit, .score, get_n_leaves, export_text and plot_tree.