Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

Decision trees

P3.B340 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A decision tree is the simplest model that makes a prediction by a chain of readable if/else questions, and it is the building block of the strongest methods for tables of data.

Before this: The supervised learning setup, Polynomial regression, underfitting and overfitting, Entropy

After this lesson you can

  • Trace a prediction through a decision tree and say why its decision regions are rectangles
  • Compute the Gini impurity, the entropy and the gain of a candidate split by hand, and choose the best threshold for a numeric feature
  • Describe how a tree is grown greedily, how a regression tree differs, and how depth, a minimum leaf size and pruning control its size
  • Explain why an unlimited tree overfits and is unstable, why greedy is not optimal, and name what trees are good and bad at

Suppose you must guess whether a Titanic passenger survived, and you may ask only two yes/no questions. Ask first: is the passenger female? If the answer is no, ask whether he was at most 9.59.5 years old. If the answer is yes, ask whether she travelled in first or second class. The answers sort the passengers into four groups. Predicting the most common outcome in each group gets 80.5%80.5\% of 262262 held-out passengers right (the split from P2.5). Always guessing “did not survive” gets 63.4%63.4\%.

That set of questions is a decision tree of depth 2. This lesson shows how to read one, how a computer picks the questions, and why a tree that is allowed to ask too many questions stops being useful. A tree is not trained by gradient descent (P1.F1). It has no smooth weights to nudge. It is built by trying many possible questions and keeping the best one.

A tree is a chain of questions

Written as code, the Titanic tree is a pair of nested if statements:

def survives(is_female, age, pclass):
    if is_female == 0:
        return age <= 9.5
    return pclass <= 2.5

The words for the parts of a tree:

  • A node is one place in the tree. The root is the first question. An internal node asks a question about one feature, such as “is x2≤4.9x_2\le4.9?”. The two answers lead to two child nodes. The question’s number (here 4.94.9) is its threshold.
  • A leaf has no question. It holds the training points that reached it and gives the prediction.
  • The depth of a tree is the number of questions on its longest path. A single leaf has depth 00. A tree of depth dd has at most 2d2^d leaves.

To predict, start at the root and follow the answers down to a leaf. For classification the leaf predicts the most common class among the training points that landed there (the majority class). The shares of the classes in the leaf can serve as probabilities, but a leaf with few points gives rough ones (calibration is P3.A10). A tie is broken by a fixed rule.

Because each question compares one feature with a threshold, each question is a straight cut parallel to an axis. Two features give vertical and horizontal lines on a plane. The leaves are therefore rectangles (boxes, in more dimensions), and the prediction is constant inside each one. The signature widget below shows this: the plane is cut into rectangles one split at a time.

How mixed is a group? Gini and entropy

To choose a good question, we need a number for how mixed the classes in a node are. A node with only one class is pure and should score 00. A node with an even mix is as uncertain as it can be. Let pkp_k be the share of class kk among the points in the node. Two common scores are used:

Gini=1−∑kpk2\text{Gini}=1-\sum_k p_k^2 entropy=−∑kpklog⁡2pk\text{entropy}=-\sum_k p_k\log_2 p_k

The Gini impurity is the chance that two points drawn at random from the node, with replacement, belong to different classes. The entropy is the average surprise of a label in bits, as in P1.E2. For two classes, Gini equals 2p(1−p)2p(1-p). Both measures are 00 for a pure node and largest for a half-and-half node:

Share of class AGiniEntropy (bits)
1.01.0 (pure)0000
0.90.90.180.180.4690.469
0.80.80.320.320.7220.722
0.50.5 (even mix)0.50.511

A question splits a node into a left and a right child. The gain of the split is how much the impurity drops:

gain=I(parent)−nLn I(left)−nRn I(right),\begin{aligned} \text{gain}&=I(\text{parent})\\ &\quad-\frac{n_L}{n}\,I(\text{left})-\frac{n_R}{n}\,I(\text{right}), \end{aligned}

where II is Gini or entropy, nLn_L and nRn_R are the numbers of points sent left and right, and n=nL+nRn=n_L+n_R. The children’s impurities are averaged with weights equal to their shares of the points, because a point is more likely to land in a big child. With entropy, the gain is the information gain, the mutual information between the answer to the question and the label (P1.E5).

Choosing the best question: a hand-worked example

Take 1010 emails, 55 spam and 55 not spam. The parent node has Gini 1−0.52−0.52=0.51-0.5^2-0.5^2=0.5 and entropy 11 bit. Four yes/no questions are candidates. The counts are written as (spam, not spam).

  • Contains “free”. Yes: (4,1)(4,1). No: (1,4)(1,4).
  • Has an attachment. Yes: (3,3)(3,3). No: (2,2)(2,2).
  • Is long. Yes: (3,1)(3,1). No: (2,4)(2,4).
  • Contains a link. Yes: (5,2)(5,2). No: (0,3)(0,3).

Work out “free”. Each group has shares (0.8,0.2)(0.8,0.2), so its Gini is 1−0.64−0.04=0.321-0.64-0.04=0.32 and its entropy is H(0.8)=0.722H(0.8)=0.722 bits. Both groups hold 55 of the 1010 emails, so the weighted averages are 0.320.32 and 0.7220.722. The gains are 0.5−0.32=0.180.5-0.32=0.18 for Gini and 1−0.722=0.2781-0.722=0.278 bits for entropy. These are the numbers from P1.E2 and P1.E5.

Now “contains a link”. The yes group has shares (5/7,2/7)(5/7,2/7), so its Gini is 1−(25+4)/49=0.4081-(25+4)/49=0.408. The no group is pure, with impurity 00. The weighted Gini is 710×0.408+310×0=0.286\frac{7}{10}\times0.408+\frac{3}{10}\times0=0.286, and the gain is 0.5−0.286=0.2140.5-0.286=0.214. Running the same arithmetic for all four questions:

QuestionGini gainEntropy gain (bits)
Contains a link0.2140.2140.3960.396
Contains “free”0.1800.1800.2780.278
Is long0.0830.0830.1250.125
Has an attachment0.0000.0000.0000.000

“Contains a link” wins under both measures, so it becomes the root question. “Has an attachment” tells us nothing: both groups are as mixed as the parent. Notice that the winner is not the question that splits the emails most evenly. It is the one that produces the purest groups, weighted by size. The two measures agree here, and they usually choose similar splits. In the widget below they pick the same seven splits.

Questions about a number: try the midpoints

A numeric feature has no short list of yes/no questions, so the builder invents one: “is x≤tx\le t?” for a threshold tt. Moving tt between two neighbouring sorted values does not change which points go left, so only one tt per gap matters. The standard choice is the midpoint of each gap. A feature with mm distinct values has m−1m-1 candidates.

Take 88 students: hours studied 1,2,…,81,2,\dots,8, and a result of fail (00) or pass (11): 0,0,1,0,1,1,1,10,0,1,0,1,1,1,1. The parent has 33 fails and 55 passes, so its Gini is 1−(3/8)2−(5/8)2=0.4691-(3/8)^2-(5/8)^2=0.469. The seven candidate thresholds, with the (fail, pass) counts on each side:

QuestionLeftRightWeighted Gini
x≤1.5x\le1.5(1,0)(1,0)(2,5)(2,5)0.3570.357
x≤2.5x\le2.5(2,0)(2,0)(1,5)(1,5)0.2080.208
x≤3.5x\le3.5(2,1)(2,1)(1,4)(1,4)0.3670.367
x≤4.5x\le4.5(3,1)(3,1)(0,4)(0,4)0.1880.188
x≤5.5x\le5.5(3,2)(3,2)(0,3)(0,3)0.3000.300
x≤6.5x\le6.5(3,3)(3,3)(0,2)(0,2)0.3750.375
x≤7.5x\le7.5(3,4)(3,4)(0,1)(0,1)0.4290.429

The best is x≤4.5x\le4.5 with weighted Gini 0.18750.1875, a gain of 0.469−0.1875=0.2810.469-0.1875=0.281. Its right side is pure: everyone with 55 or more hours passed. The left side, students 11 to 44 with results 0,0,1,00,0,1,0, is still mixed, so the same procedure runs on it alone. Its best question is x≤2.5x\le2.5 (weighted Gini 0.250.25, against 0.3330.333 for the other two), and a last question x≤3.5x\le3.5 separates student 33 from student 44. The finished tree has four leaves. Its last two questions exist only to separate the student with 33 hours, who passed, from the one with 44, who failed. That is a first sign of memorizing noise.

Growing the whole tree

The same step repeats on every node. The procedure is called recursive binary splitting, and it is greedy: it takes the best split for the current node and never looks ahead.

  1. Put all the training points in the root.
  2. For the current node, if it is pure or a stopping rule applies, make it a leaf.
  3. Otherwise, for every feature and every candidate threshold, compute the gain. Keep the split with the largest gain.
  4. Send each point to the left or right child, and repeat from step 2 on each child on its own.

Stopping rules limit the size of the tree. The usual ones are a maximum depth, a minimum number of points in a leaf, a minimum number of points needed to split and a minimum gain. Without any rule, growth stops only when every leaf is pure, or when no split is possible because identical inputs remain together.

Two practical notes. A category such as “port of embarkation” has no order, so a threshold means little. Some libraries split the set of categories into two groups. scikit-learn’s trees expect numbers (they raised a ValueError on a text column in version 1.8), so categories are encoded first (P3.A11). Missing values are handled in different ways by different libraries (scikit-learn 1.8 accepted NaN in a tree).

Watch a tree cut the plane

The widget grows a tree on 4040 made-up points of two classes. Press Play or Step: each step adds the best split for the next node, level by level, so a lower maximum depth gives the first part of the same sequence. The line drawn is the question, the rectangles are shaded by the class the tree predicts, and the tree diagram grows with it. Points with a ring are classified wrongly by the tree as it stands.

00551010x₁x₂
x₂ ≤ 4.90x₁ ≤ 7.75A12B3x₁ ≤ 4.95x₁ ≤ 3.55x₁ ≤ 0.95A1B5A3x₁ ≤ 8.85B13x₁ ≤ 9.30A1B2

Upper branch: the answer is yes (≤). Lower branch: no. A is the circle class and B the triangle class; counts are training points.

class A class B wrong in the current tree newest cut

Split 7 of 7: ask whether x₁ ≤ 9.30 at the node holding 3 points. Gini impurity before 0.444, weighted average after 0, so the gain is 0.444.

Impurity measure
splits so far = 7 of 7
leaves = 8
Gini impurity of the root = 0.489
weighted impurity of the leaves = 0
training accuracy = 1 (40 of 40)

The 40 points are made up. Class B is mostly where x₁ + x₂ is above 10, but 2 labels were flipped at random. Training accuracy is measured on these same points. Each split looks at one feature, so every cut is a straight horizontal or vertical line.

A decision tree growing on 40 made-up points: class A (blue circles) and class B (pink triangles), mostly separated by a diagonal line, with two labels flipped at random. Each step adds one split. The shaded rectangles show the prediction, the tree is drawn sideways beside (or below) the plane, and the readouts give the impurity and the training accuracy.

Things to try, with what the widget shows on the machine used for this lesson (Gini, maximum depth 4, the widget’s starting setting):

  • Step through. Before any split the single leaf predicts class B and gets 2323 of 4040 points right (0.5750.575). The first split, x2≤4.90x_2\le4.90, takes the Gini impurity from 0.4890.489 to a weighted 0.3200.320 (a gain of 0.1690.169) and lifts the accuracy to 0.8000.800.
  • Accuracy can stall while impurity falls. After split 22 the accuracy is 0.8750.875 and the weighted Gini is 0.2000.200. Split 33 leaves the accuracy at 0.8750.875 but lowers the weighted Gini to 0.1580.158. A split can make the groups purer without changing any majority vote, and the builder still counts that as progress. The same happens between splits 44 and 55 (0.950.95 both times).
  • The staircase. The true boundary is diagonal, but every cut is axis-parallel. The tree approximates the diagonal with steps, and more steps are needed for a closer fit.
  • Depth. Depth 11, 22, 33 and 44 give training accuracies 0.8000.800, 0.8750.875, 0.9500.950 and 1.0001.000, using 11, 33, 55 and 77 splits. Depth 55 changes nothing, because every leaf is already pure. The last two cuts each carve out a single class A point that depth 33 got wrong: (0.4,8.1)(0.4, 8.1) and (9.1,7.5)(9.1, 7.5). The tree is now fitting the particular points it was given, noise included.
  • Entropy. Switch the measure to entropy. The root impurity becomes 0.9840.984 bits and the first split is the same, with weighted impurity 0.7220.722 and gain 0.2620.262. All seven splits are the same as with Gini.

Trees that predict a number

A regression tree predicts a number. Only two things change. A leaf predicts the mean of the training targets that reached it. And the impurity of a node is the mean squared error around its own mean, which is the variance of its targets. A split is scored by how much it lowers the size-weighted variance, which is the same as lowering the sum of squared errors (SSE) of the leaves.

Take x=1,…,6x=1,\dots,6 with targets y=2,4,3,9,10,8y=2,4,3,9,10,8. One leaf holding everything predicts the mean 66, with SSE 5858 and mean squared error 9.679.67. The five midpoints give:

QuestionLeaf meansTotal SSE
x≤1.5x\le1.522, 6.86.838.838.8
x≤2.5x\le2.533, 7.57.531.031.0
x≤3.5x\le3.533, 994.04.0
x≤4.5x\le4.54.54.5, 9931.031.0
x≤5.5x\le5.55.65.6, 8853.253.2

The best split is x≤3.5x\le3.5: the SSE falls from 5858 to 44, and the mean squared error from 9.679.67 to 0.670.67. The fitted function is a staircase: 33 for x≤3.5x\le3.5 and 99 above. A regression tree cannot extrapolate. Its prediction at x=100x=100 is the mean of the last leaf, here 99, however far outside the training range xx is.

How deep? Overfitting and stopping

With no stopping rule, a tree keeps splitting until every leaf is pure. Then every training point is classified correctly, unless two points have identical inputs but different labels, which no question can separate. That is the memorizing of the degree-9 polynomial in P3.A3, in a different form. The number of leaves is the tree’s capacity: more leaves, more flexibility.

The cell below builds a tree from scratch with NumPy. The data are made up: points in [0,10]2[0,10]^2 with label 11 when x1+x2>10x_1+x_2>10, except that each label is flipped with probability 0.150.15 (the rule itself scores 0.8490.849 on the test points, so no model can be expected to beat about 0.850.85 on them). The training set has 150150 points and the test set 30003000 fresh ones. Because greedy growth decides each node independently, a tree of depth dd is just the top dd levels of the unlimited tree, so the cell grows one tree and truncates it. The second half repeats a depth-2 tree on five resamples of the training rows, which the weaknesses section uses.

Try it: a tree from scratch, depth against accuracy

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints this (the printed outputs in this lesson come from the machine used to write it):

max_depth  leaves  train  test
        1       2   0.73  0.66
        2       4   0.78  0.71
        3       8   0.86  0.78
        4      14   0.89  0.74
        5      23   0.92  0.73
        6      28   0.95  0.72
        8      35   0.97  0.70
       30      42   1.00  0.70
min_leaf=10: 11 leaves, train 0.81, test 0.74

Read the two accuracy columns. The training accuracy rises with every extra level and reaches 1.001.00 with 4242 leaves for 150150 points. The test accuracy rises to 0.780.78 at depth 33 and then falls to 0.700.70: the deeper levels fit the flipped labels, and a flipped label teaches nothing about new points. This is the same overfitting story as the polynomial in P3.A3, with depth in place of the degree, and the depth should be chosen on validation data or by cross-validation (P3.A4), never on the training accuracy. Requiring every leaf to hold at least 1010 points gave 0.740.74 on the test points with only 1111 leaves, much better than the unlimited tree’s 0.700.70 (the depth-33 peak of 0.780.78 was found by looking at the test set, which is only allowed here because we are demonstrating, not tuning). The resampling lines at the end of the cell are used in the weaknesses section.

Pruning is the other way to control size. Instead of stopping early, grow a large tree and then cut branches that earn little. Cost-complexity pruning, from the CART method, scores a tree as its training error plus a price α\alpha for each leaf and keeps the subtree with the best score. A larger α\alpha gives a smaller tree. In scikit-learn the price is the argument ccp_alpha; the Code tab shows it shrinking the Titanic tree. Pre-stopping (depth, leaf size) is simpler and is what most people use first, and the pruning price is also chosen on validation data.

Greedy is not the best possible tree

At each node the builder takes the best question now. That is fast, but it can miss a pair of questions that work together. The classic case is XOR: four points at (0,0)(0,0) and (1,1)(1,1) of class A, and (0,1)(0,1) and (1,0)(1,0) of class B. The parent Gini is 0.50.5. Any single question, such as x1≤0.5x_1\le0.5, leaves each side with one A and one B, so both children have Gini 0.50.5 and the gain is 00. A one-question tree is right on only 22 of the 44 points. Yet two questions in a row, one on each feature, classify all four correctly, and scikit-learn’s tree does build that depth-2 tree. A greedy rule that stopped whenever the gain was 00 would have missed it.

How far from the best tree can greedy be? Finding the tree with the fewest expected questions is NP-complete (Hyafil and Rivest, 1976), so unless P = NP no fast method finds it, and finding the best tree for fitting data is also hard in related settings. So practical methods do not search for the best tree. They take the best split at each node and accept that the whole tree may not be the best one.

Strengths and weaknesses

Strengths.

  • Readable. The tree is a set of rules a person can follow, and the path to a prediction is its explanation.
  • No scaling needed. A question compares one feature with a threshold, so only the order of the values matters. Multiplying a feature by 10001000, or taking its logarithm, changes the thresholds but not which points go where. On the Titanic training rows, standardizing the three features gave the same training predictions and the same 172172 leaves for an unlimited tree. So did replacing the fare by log⁡(1+fare)\log(1+\text{fare}) in the seven-feature set of P2.5 (P3.A11 covers scaling for other models).
  • Mixed features. Counts, prices and yes/no flags can sit side by side, whatever their units, once categories are encoded.
  • Interactions. A question under another question depends on the answer above it, so a tree can represent “young and in third class” without being told to. A single linear classifier on the raw features cannot represent XOR at all.

Weaknesses.

  • High variance (instability). A small change in the training data can change an early question, and every question below it. The cell above grew a depth-2 tree on the 150150 points and then on five resamples of those rows. The root cut moved from x2≤6.02x_2\le6.02 to 5.075.07, 5.075.07, 5.385.38 and 6.036.03, and in one resample to x2≤2.33x_2\le2.33, and the second-level questions changed with it. A model whose shape depends this much on the sample overfits easily (P3.A5 names this variance). Averaging many trees fixes much of it: that is bagging and random forests (P3.B4).
  • Axis-aligned boundaries. A diagonal boundary needs a staircase of many cuts, as in the widget. A single linear model draws that boundary with one line.
  • Piecewise-constant predictions. A regression tree cannot extrapolate and is not smooth.
  • Overfitting when unlimited. See the size controls above.
  • Greedy, not optimal. See the previous section.

One more option removes the “one tree is weak” problem from the other side: boosting builds many small trees, each fitted to the mistakes of the previous ones (P3.B5). Together, forests and boosted trees are among the strongest methods for tables of data.

Which features matter?

A fitted tree gives a quick feature importance. For each feature, add up the impurity reduction (weighted by the share of points reaching the node) of all splits that use it, and divide by the total over all features. The numbers sum to 11. For the depth-2 Titanic tree below, the importances are 0.7580.758 for sex, 0.1890.189 for passenger class and 0.0530.053 for age.

Impurity-based importance has a known weakness: it is computed on the training data, and features with many distinct values offer many candidate thresholds, so they have more chances to look useful. The lesson’s Titanic training rows plus one column of random numbers show it.

Go deeper A pure-noise column gets a high importance

Take the 10471047 Titanic training rows with the seven features of P2.5 and add a column of uniform random numbers that has nothing to do with survival. An unlimited tree gives the noise column an importance of 0.2550.255 in one random draw (seeded with 0), and 0.230.23 to 0.260.26 in six draws. That is second only to sex (0.2790.279) and above age, passenger class and fare in all six draws. A tree limited to depth 33 gives the noise column 0.000.00 to 0.020.02. The unlimited tree is splitting its small, deep nodes on whichever feature happens to separate the few points left, and a random column with a different value for every row is always available. Importance computed on held-out data (permutation importance) is less open to this, and importance says what the tree used, not what causes survival.

A tree on the Titanic data

The scikit-learn code below uses the same split as P2.5 (random_state=2, 10471047 training and 262262 test rows) and three features. scikit-learn is not available in the browser on this site, so the block is static, with the output of a real local run (scikit-learn 1.8). The training rows give the fill value for the missing ages.

import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text

df = pd.read_csv("titanic.csv")
train = df.sample(frac=0.8, random_state=2)
test = df.drop(train.index)
age_fill = train["age"].median()          # from the training rows only

def features(part):
    return pd.DataFrame({
        "pclass": part["pclass"],
        "is_female": (part["sex"] == "female").astype(int),
        "age": part["age"].fillna(age_fill),
    })

X_train, y_train = features(train), train["survived"]
X_test, y_test = features(test), test["survived"]

tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_train, y_train)
print(export_text(tree, feature_names=list(X_train.columns)))
print("always 'died': test accuracy %.3f" % (1 - y_test.mean()))
print("depth  leaves  train   test")
for depth in [1, 2, 3, None]:
    t = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
    print(f"{str(depth):>5} {t.get_n_leaves():7d} {t.score(X_train, y_train):7.3f} {t.score(X_test, y_test):6.3f}")
|--- is_female <= 0.50
|   |--- age <= 9.50
|   |   |--- class: 1
|   |--- age >  9.50
|   |   |--- class: 0
|--- is_female >  0.50
|   |--- pclass <= 2.50
|   |   |--- class: 1
|   |--- pclass >  2.50
|   |   |--- class: 0

always 'died': test accuracy 0.634
depth  leaves  train   test
    1       2   0.778  0.786
    2       4   0.784  0.805
    3       8   0.797  0.802
 None     172   0.852  0.798

The scikit-learn tree uses the same arithmetic as the hand examples. At the root, 10471047 passengers (643643 died, 404404 survived) have Gini 0.4740.474. The best of all candidate questions is the sex question (“is_female ≤0.5\le0.5”), which splits them into 667667 men (539539 died, 128128 survived, Gini 0.3100.310) and 380380 women (104104 died, 276276 survived, Gini 0.3980.398). The weighted Gini is 0.3420.342, a gain of 0.1320.132. The best question about class, “≤2.5\le2.5”, has a gain of only 0.0370.037, and the best question on age, “≤15.5\le15.5”, only 0.0090.009. The four leaves are:

  • Men aged at most 9.59.5: 3434 passengers, 1919 survived. The leaf predicts survival.
  • Men older than 9.59.5: 633633 passengers, 109109 survived. It predicts death.
  • Women in first or second class: 206206 passengers, 190190 survived. It predicts survival.
  • Women in third class: 174174 passengers, 8686 survived and 8888 died. It predicts death, but this is nearly a coin flip.

The depth-2 tree scores 0.8050.805 on the test rows (211211 of 262262); the sex question alone scores 0.7860.786. Deeper trees add leaves and raise the training accuracy but not the test accuracy. The unlimited tree has 172172 leaves and a training accuracy of 0.8520.852, not 1.01.0, because many passengers share the same class, sex and age but not the same outcome (578578 of the 10471047 training rows share all three values with a passenger who had the other outcome), and no question can separate identical inputs. The test accuracies differ by under half a point between depths 22 and 33 on 262262 passengers, which is within the noise of such a small test set (P3.A4).

Intuition

A decision tree is a game of twenty questions played to be as informative as possible. Each question is chosen so that the answer leaves the groups as clear as it can: the leftover guessing is the impurity. The comparison breaks in one way. In twenty questions you pick each question knowing only the answers so far and then stop. A tree is built once from the training data, and every passenger then gets the same questions in the same order, so it is tuned to that data.

Math

The formulas are in the main text: Gini 1−∑kpk21-\sum_kp_k^2, entropy −∑kpklog⁡2pk-\sum_kp_k\log_2p_k and the gain of a split. A tree picks the feature and midpoint with the largest gain. For regression, II is the node variance 1n∑i(yi−yˉ)2\frac1n\sum_i(y_i-\bar y)^2.

Cost-complexity pruning minimizes R(T)+α∣T∣R(T)+\alpha\lvert T\rvert: the training error of tree TT plus a price α≥0\alpha\ge0 per leaf. The impurity-based importance of a feature adds up nnodenΔnode\frac{n_{\text{node}}}{n}\Delta_{\text{node}} over the nodes that use it, divided by the total over all features.

Code

The scikit-learn names of the controls from this lesson (scikit-learn 1.8, run locally; the in-browser cells use NumPy only). criterion picks the impurity, max_depth, min_samples_leaf and ccp_alpha limit the size. Here they are on the Titanic features of the previous section, with the number of leaves each setting leaves:

settings = {"default": {}, "ccp_alpha=0.001": dict(ccp_alpha=0.001),
            "ccp_alpha=0.005": dict(ccp_alpha=0.005), "ccp_alpha=0.02": dict(ccp_alpha=0.02),
            "min_samples_leaf=20": dict(min_samples_leaf=20),
            "criterion=entropy": dict(criterion="entropy")}
print("setting              leaves  test")
for name, kw in settings.items():
    t = DecisionTreeClassifier(random_state=0, **kw).fit(X_train, y_train)
    print(f"{name:20s} {t.get_n_leaves():6d} {t.score(X_test, y_test):6.3f}")
setting              leaves  test
default                 172  0.798
ccp_alpha=0.001          27  0.809
ccp_alpha=0.005           6  0.805
ccp_alpha=0.02            3  0.794
min_samples_leaf=20      32  0.771
criterion=entropy       172  0.798

A regression tree is DecisionTreeRegressor. On the six points of the regression example it finds the cut at 3.53.5 and predicts the leaf means, also far outside the training range:

import numpy as np
from sklearn.tree import DecisionTreeRegressor, export_text

x = np.arange(1, 7).reshape(-1, 1)
y = np.array([2, 4, 3, 9, 10, 8.0])
reg = DecisionTreeRegressor(max_depth=1, random_state=0).fit(x, y)
print(export_text(reg, feature_names=["x"]))
print("at x = 3 and 100:", reg.predict([[3], [100]]))
|--- x <= 3.50
|   |--- value: [3.00]
|--- x >  3.50
|   |--- value: [9.00]

at x = 3 and 100: [3. 9.]

Try it

  1. In the widget, set the depth to 33 and press Step until the end. Which points are still ringed, and which later cuts remove the rings? Then raise the depth to 44 and check the two single points.
  2. In the cell, change make(150, 1) to make(150, 2) and make(150, 3). Does the test accuracy still peak around depth 33? How does the best depth move?
  3. In the cell, change min_leaf=10 to 22, 55, 2020 and 4040. Which value gives the best test accuracy, and what happens to the number of leaves and the training accuracy as it grows?

Check yourself

Check your understanding

  1. A node has 88 points: 66 of class A and 22 of class B. What is its Gini impurity?

  2. A node of 1010 points, 55 of each class, is split into a left group of 66 points with 55 of class A and 11 of class B, and a right group of 44 points, all of class B. What is the weighted Gini of the children, and is the split better than one whose weighted Gini is 0.320.32?

  3. A tree is grown with no limit on depth on training data in which no two identical inputs have different labels. What is true of it?

  4. You multiply one feature by 10001000 before training a decision tree. What happens?

  5. You grow depth-2 trees on several resamples of the same training data, and the root question differs between resamples. What does this show?

Exercises

  1. A node holds 66 points of class A and 22 of class B. Find its entropy in bits.
    Show answerThe shares are 0.750.75 and 0.250.25. Entropy is −0.75log⁡20.75−0.25log⁡20.25=0.311+0.5=0.811-0.75\log_2 0.75-0.25\log_2 0.25=0.311+0.5=0.811 bits. Its Gini is 0.3750.375.
  2. A node has 1212 points, 66 of each class. A question sends (5,1)(5,1) left and (1,5)(1,5) right, with the counts as (class A, class B). Find the Gini gain and the entropy gain.
    Show answerEach child has 66 points. Its Gini is 1−(5/6)2−(1/6)2=0.2781-(5/6)^2-(1/6)^2=0.278 and its entropy is 0.6500.650 bits. The parent has Gini 0.50.5 and entropy 11 bit. The Gini gain is 0.5−0.278=0.2220.5-0.278=0.222 and the entropy gain is 1−0.650=0.3501-0.650=0.350 bits.
  3. A regression has x=1,2,3,4x=1,2,3,4 and y=1,3,8,10y=1,3,8,10. Which threshold does the best first split use, and by how much does it cut the sum of squared errors?
    Show answerOne leaf with the mean 5.55.5 has SSE 5353. The three midpoints give a total SSE of 2626 at 1.51.5, 44 at 2.52.5 and 2626 at 3.53.5. The best is x≤2.5x\le2.5 (leaf means 22 and 99), which cuts the SSE from 5353 to 44, a reduction of 4949.
  4. A regression tree is trained on xx between 00 and 1010. What does it predict at x=50x=50, and why can this be a problem for a trend that keeps rising?
    Show answerIt predicts the mean of the training targets in the right-most leaf, the same value as for the largest training xx. A tree makes constant predictions inside each leaf, so it cannot continue a trend outside the range it saw.
  5. How many leaves can a tree of depth 55 have at most? A training set has 10001000 points: can an unlimited tree have more than 10001000 leaves?
    Show answerAt most 25=322^5=32 leaves. An unlimited tree cannot have more than 10001000 leaves, because every leaf holds at least one training point and a point is in only one leaf.
  6. Why does a greedy tree sometimes make a split whose gain is 00, and why would it be a mistake to forbid it?
    Show answerSome problems need two questions together, with no single question helping alone, such as XOR. A split with zero gain can make the children easier to split next. Forbidding all zero-gain splits would stop the tree at the root for XOR and leave 22 of 44 points wrong.

Next: P3.B4 averages many trees, grown on resampled data, to cut the variance seen here (bagging and random forests). P3.B5 builds trees one after another, each correcting the errors of the others (boosting, XGBoost and LightGBM). P3.A5 gives the bias and variance names to what depth does, and P3.A11 returns to feature scaling and the encoding of categories.

Key takeaways

  • A decision tree predicts with nested yes/no questions about one feature at a time. Each question is a vertical or horizontal cut, so the leaves are rectangles. A leaf predicts the majority class (classification) or the mean (regression) of its training points.
  • Impurity measures how mixed a node is: Gini is 1−∑p21-\sum p^2 and entropy is −∑plog⁡2p-\sum p\log_2 p. Both are 00 for a pure node. The gain of a split is the parent's impurity minus the size-weighted impurity of the two children. A tree is grown top-down by taking, at every node, the split with the largest gain, trying midpoints between sorted values for a numeric feature.
  • A regression tree uses the variance (the mean squared error around the node mean) as its impurity. For the lesson's six points the best split cuts the sum of squared errors from 5858 to 44.
  • An unlimited tree reaches zero training error when no two identical inputs have different labels. In the lesson's example, training accuracy rises from 0.730.73 to 1.001.00 with depth while accuracy on 30003000 fresh points peaks at 0.780.78 (depth 33) and falls to 0.700.70. Maximum depth, a minimum leaf size and cost-complexity pruning limit the size.
  • Greedy growth is fast but not optimal: a split with zero gain can still be needed (XOR), and finding an optimal tree is NP-hard in general. Trees are easy to read, need no scaling and mix feature types, but they are unstable (resampling the data moved the root cut from x2≤6.02x_2\le6.02 to x2≤2.33x_2\le2.33 in one of five tries) and cut diagonals into staircases.
  • Impurity-based feature importance is quick but biased: on training data, a column of pure random noise got an importance of 0.2550.255 in one random draw (seeded with 0), and 0.230.23 to 0.260.26 in six draws, in an unlimited tree.
Found a mistake? Tell us