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 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 of held-out passengers right (the split from P2.5). Always guessing “did not survive” gets .
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 ?”. The two answers lead to two child nodes. The question’s number (here ) 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 . A tree of depth has at most 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 . A node with an even mix is as uncertain as it can be. Let be the share of class among the points in the node. Two common scores are used:
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 . Both measures are for a pure node and largest for a half-and-half node:
| Share of class A | Gini | Entropy (bits) |
|---|---|---|
| (pure) | ||
| (even mix) |
A question splits a node into a left and a right child. The gain of the split is how much the impurity drops:
where is Gini or entropy, and are the numbers of points sent left and right, and . 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 emails, spam and not spam. The parent node has Gini and entropy bit. Four yes/no questions are candidates. The counts are written as (spam, not spam).
- Contains “free”. Yes: . No: .
- Has an attachment. Yes: . No: .
- Is long. Yes: . No: .
- Contains a link. Yes: . No: .
Work out “free”. Each group has shares , so its Gini is and its entropy is bits. Both groups hold of the emails, so the weighted averages are and . The gains are for Gini and bits for entropy. These are the numbers from P1.E2 and P1.E5.
Now “contains a link”. The yes group has shares , so its Gini is . The no group is pure, with impurity . The weighted Gini is , and the gain is . Running the same arithmetic for all four questions:
| Question | Gini gain | Entropy gain (bits) |
|---|---|---|
| Contains a link | ||
| Contains “free” | ||
| Is long | ||
| Has an attachment |
“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 ?” for a threshold . Moving between two neighbouring sorted values does not change which points go left, so only one per gap matters. The standard choice is the midpoint of each gap. A feature with distinct values has candidates.
Take students: hours studied , and a result of fail () or pass (): . The parent has fails and passes, so its Gini is . The seven candidate thresholds, with the (fail, pass) counts on each side:
| Question | Left | Right | Weighted Gini |
|---|---|---|---|
The best is with weighted Gini , a gain of . Its right side is pure: everyone with or more hours passed. The left side, students to with results , is still mixed, so the same procedure runs on it alone. Its best question is (weighted Gini , against for the other two), and a last question separates student from student . The finished tree has four leaves. Its last two questions exist only to separate the student with hours, who passed, from the one with , 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.
- Put all the training points in the root.
- For the current node, if it is pure or a stopping rule applies, make it a leaf.
- Otherwise, for every feature and every candidate threshold, compute the gain. Keep the split with the largest gain.
- 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 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.
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 of points right (). The first split, , takes the Gini impurity from to a weighted (a gain of ) and lifts the accuracy to .
- Accuracy can stall while impurity falls. After split the accuracy is and the weighted Gini is . Split leaves the accuracy at but lowers the weighted Gini to . 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 and ( 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 , , and give training accuracies , , and , using , , and splits. Depth changes nothing, because every leaf is already pure. The last two cuts each carve out a single class A point that depth got wrong: and . The tree is now fitting the particular points it was given, noise included.
- Entropy. Switch the measure to entropy. The root impurity becomes bits and the first split is the same, with weighted impurity and gain . 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 with targets . One leaf holding everything predicts the mean , with SSE and mean squared error . The five midpoints give:
| Question | Leaf means | Total SSE |
|---|---|---|
| , | ||
| , | ||
| , | ||
| , | ||
| , |
The best split is : the SSE falls from to , and the mean squared error from to . The fitted function is a staircase: for and above. A regression tree cannot extrapolate. Its prediction at is the mean of the last leaf, here , however far outside the training range 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 with label when , except that each label is flipped with probability (the rule itself scores on the test points, so no model can be expected to beat about on them). The training set has points and the test set fresh ones. Because greedy growth decides each node independently, a tree of depth is just the top 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.
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 with leaves for points. The test accuracy rises to at depth and then falls to : 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 points gave on the test points with only leaves, much better than the unlimited tree’s (the depth- peak of 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 for each leaf and keeps the subtree with the best score. A larger 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 and of class A, and and of class B. The parent Gini is . Any single question, such as , leaves each side with one A and one B, so both children have Gini and the gain is . A one-question tree is right on only of the 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 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 , 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 leaves for an unlimited tree. So did replacing the fare by 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 points and then on five resamples of those rows. The root cut moved from to , , and , and in one resample to , 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 . For the depth-2 Titanic tree below, the importances are for sex, for passenger class and 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 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 in one random draw (seeded with 0), and to in six draws. That is second only to sex () and above age, passenger class and fare in all six draws. A tree limited to depth gives the noise column to . 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, training and 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, passengers ( died, survived) have Gini . The best of all candidate questions is the sex question (“is_female ”), which splits them into men ( died, survived, Gini ) and women ( died, survived, Gini ). The weighted Gini is , a gain of . The best question about class, “”, has a gain of only , and the best question on age, “”, only . The four leaves are:
- Men aged at most : passengers, survived. The leaf predicts survival.
- Men older than : passengers, survived. It predicts death.
- Women in first or second class: passengers, survived. It predicts survival.
- Women in third class: passengers, survived and died. It predicts death, but this is nearly a coin flip.
The depth-2 tree scores on the test rows ( of ); the sex question alone scores . Deeper trees add leaves and raise the training accuracy but not the test accuracy. The unlimited tree has leaves and a training accuracy of , not , because many passengers share the same class, sex and age but not the same outcome ( of the 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 and on 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 , entropy and the gain of a split. A tree picks the feature and midpoint with the largest gain. For regression, is the node variance .
Cost-complexity pruning minimizes : the training error of tree plus a price per leaf. The impurity-based importance of a feature adds up 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.798A regression tree is DecisionTreeRegressor. On the six points of the regression example it finds the cut at 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
- In the widget, set the depth to and press Step until the end. Which points are still ringed, and which later cuts remove the rings? Then raise the depth to and check the two single points.
- In the cell, change
make(150, 1)tomake(150, 2)andmake(150, 3). Does the test accuracy still peak around depth ? How does the best depth move? - In the cell, change
min_leaf=10to , , and . 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
A node has points: of class A and of class B. What is its Gini impurity?
The shares are and , so the Gini impurity is . The value is just the share of the minority class. The value is the Gini of an even mix, which this node is not. The value is the share of the majority class, not an impurity.
A node of points, of each class, is split into a left group of points with of class A and of class B, and a right group of points, all of class B. What is the weighted Gini of the children, and is the split better than one whose weighted Gini is ?
The left group has Gini . The right group is pure, with Gini . The weighted average is . A lower weighted impurity means purer groups and a larger gain, so beats . The value is only one child, and the average must include the pure child. The value is the other split’s score.
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?
Growth continues until every leaf is pure, so every training point is classified correctly. That does not carry over to new points: the deep splits fit noise, and test accuracy often falls. Training accuracy never falls as a tree grows. Using every split gives the biggest tree, not the best one, and greedy growth does not search for the best tree.
You multiply one feature by before training a decision tree. What happens?
A split only asks which side of a threshold a value falls on, so the order of the values is all that matters. Scaling by a positive number keeps the order, so the same points go left and right, and only the threshold changes. The size of a feature does not make it more attractive, and the gain depends on class counts, not on feature values.
You grow depth-2 trees on several resamples of the same training data, and the root question differs between resamples. What does this show?
The best root question can change when a few points are added or removed, because several thresholds have nearly equal gain. This sensitivity to the sample is variance, which random forests reduce by averaging many trees. It does not mean the data are wrong. The greedy rule does not use randomness to pick the best split (apart from breaking exact ties). A deeper tree does not stabilize the root.
Exercises
- A node holds points of class A and of class B. Find its entropy in bits.
Show answer
The shares are and . Entropy is bits. Its Gini is . - A node has points, of each class. A question sends left and right, with the counts as (class A, class B). Find the Gini gain and the entropy gain.
Show answer
Each child has points. Its Gini is and its entropy is bits. The parent has Gini and entropy bit. The Gini gain is and the entropy gain is bits. - A regression has and . Which threshold does the best first split use, and by how much does it cut the sum of squared errors?
Show answer
One leaf with the mean has SSE . The three midpoints give a total SSE of at , at and at . The best is (leaf means and ), which cuts the SSE from to , a reduction of . - A regression tree is trained on between and . What does it predict at , and why can this be a problem for a trend that keeps rising?
Show answer
It predicts the mean of the training targets in the right-most leaf, the same value as for the largest training . A tree makes constant predictions inside each leaf, so it cannot continue a trend outside the range it saw. - How many leaves can a tree of depth have at most? A training set has points: can an unlimited tree have more than leaves?
Show answer
At most leaves. An unlimited tree cannot have more than leaves, because every leaf holds at least one training point and a point is in only one leaf. - Why does a greedy tree sometimes make a split whose gain is , and why would it be a mistake to forbid it?
Show answer
Some 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 of 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.