Lesson 12 of 227 min
Decision trees
A tree asks one question at a time, and it picks each question by trying every cut and keeping the one whose two piles are least mixed.
After this lesson you can read and grow a tree of splits.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Draw the two-question tree
Put penguins.csv from Palmer Penguins next to your notebook. Fit the tree on the same two measurements and training split as the chapter. plot_tree writes the question at each split. The left branch takes values at or below the cut. Plotting reference
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.tree import DecisionTreeClassifier, plot_tree
features = ["flipper_length_mm", "bill_length_mm"]
penguins = pd.read_csv("penguins.csv").dropna(subset=features)
X, y = penguins[features], penguins["species"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)import matplotlib.pyplot as plt
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)
plt.figure(figsize=(12, 5))
plot_tree(tree, feature_names=features, class_names=list(tree.classes_),
filled=True, precision=2)
plt.show()Read the share in a leaf
predict_proba walks the row to its leaf and gives the share of each kind among the training rows there. The order comes from classes_. The shares can be rough when the leaf has few penguins. Classifier reference
one = pd.DataFrame([[192, 46.5]], columns=features)
shares = tree.predict_proba(one)[0]
print(dict(zip(tree.classes_.tolist(), shares.round(3).tolist()))){'Adelie': 0.064, 'Chinstrap': 0.915, 'Gentoo': 0.021}Stop by leaf size
min_samples_leaf rules out a cut if either side would get too few rows. max_leaf_nodes sets a budget for the whole tree. ccp_alpha can prune branches after the tree is grown. Compare settings on the training folds. Pruning guide
leaf_limit = DecisionTreeClassifier(min_samples_leaf=10, random_state=0)
leaf_limit.fit(X_train, y_train)
print("Depth:", leaf_limit.get_depth())
print("Leaves:", leaf_limit.get_n_leaves())Depth: 4 Leaves: 10
Try entropy
The chapter used Gini to measure how mixed the two piles are. criterion="entropy" uses another measure of mixing. Try both on the same folds and see how much the choice changes. Split criteria
for criterion in ["gini", "entropy"]:
model = DecisionTreeClassifier(max_depth=2, criterion=criterion, random_state=0)
score = cross_val_score(model, X_train, y_train, cv=5).mean()
print(criterion, round(score, 3))gini 0.941 entropy 0.941
Predict a number
A regression tree predicts a number. With the default squared-error rule, each leaf predicts the mean of its training targets. These four made-up measurements give two leaves. Regressor reference
from sklearn.tree import DecisionTreeRegressor
reg = DecisionTreeRegressor(max_depth=1, random_state=0)
reg.fit([[38], [40], [48], [50]], [3100, 3500, 4800, 5200])
print(reg.predict([[39], [49]]))[3300. 5000.]
Keep missing measurements
With dense numeric data and the default splitter="best", scikit-learn can learn which side should receive missing values. This tree saw one blank example during training. Missing values guide
blank = float("nan")
missing = DecisionTreeClassifier(max_depth=1, random_state=0)
missing.fit([[38], [41], [47], [blank]], ["A", "A", "B", "B"])
print(missing.predict([[blank]]).tolist())['B']
Run on Python 3.13.3, scikit-learn 1.9.1, pandas 3.1.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: What machine learning is
On the 86 penguins kept aside, tree.score(X_test, y_test) printed 0.953: the share it got right, 82 of 86. The rule by hand got 83 of the 86 right. Written as the same kind of score, what is it?
2 of 3
One cut on the bill leaves 83 Adelies alone in one pile, a perfect pile, and the other pile very mixed. A cut on the flipper leaves two piles, each mostly one kind. Which does the tree keep as its first question?
3 of 3
On the bank's calls, a tree with no limit prints an area under the ROC curve of 0.9923 on its own calls and 0.5899 on the folds. A coin scores 0.5. What do you change?
The ideas in this lesson
- Decision tree
- Questions in a row, each about one measurement; each answer leads to the next question, and a leaf gives the answer.
- How a tree splits
- It tries every cut of every measurement and keeps the one whose two piles are least mixed (Gini).
- A tree's depth
- How many questions in a row; with no limit it splits until every leaf is one kind and remembers. Choose it on the folds.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Decision trees
Here's a question. A computer learned this tree from the penguins. It asks one question, then the next. But it could start with many different questions. So how does a tree choose its first one?
Keep your guess
Hold on to your guess. Here are the penguins, by flipper length and bill length, just like in the first lesson. Two hundred and fifty-six to learn from, and eighty-six kept aside.
Questions in a row
In the first lesson, a computer found this rule in the penguins. Here it is, drawn as a tree. The first question: is the flipper longer than two hundred and six point five millimeters?
Each answer leads down a branch to the next question, about the bill.
At the end, a leaf gives the kind: Adelie, Chinstrap or Gentoo.
Follow one penguin down it.
A flipper of a hundred and ninety-two millimeters, and a bill of forty-six point five.
Is the flipper longer than two hundred and six point five? No.
Then the question about the bill: is it longer than the cut, just over forty-three? Yes. Chinstrap.
Questions in a row, each about one measurement. That's a decision tree.
Every cut is tried
A tree asks one question at a time, and each question is a cut on one measurement.
So where does the first question come from?
Think of a good first question in a guessing game. It splits the penguins into two piles. Each pile is as close to one kind as it can be.
So the tree tries... every cut. Between each flipper length and the next, there's one cut. That's fifty-three in all. And on the bill, there are a hundred and forty-four.
Mixed, as a number
To compare cuts, the tree needs a number for how mixed a pile is. Pick a penguin from the pile, put it back, and pick again. What's the chance the two are different kinds?
In a pile of one kind, the chance is zero. Four Adelies and one Gentoo: zero point three two.
The pile, and a first cut
All two hundred and fifty-six together: zero point six four. About two times out of three. This number is called the Gini impurity.
Now cut just after a hundred and ninety millimeters. Two piles. Each has its own number. The short-flipper pile is fairly pure: zero point two five. The other is still very mixed: zero point six three.
The least mixed piles win
For the whole cut, average the two piles' numbers, with the bigger pile counting more.
At this cut, the penguins are left mixed: zero point five three.
Now slide the cut along the flipper. The penguins get less mixed, then more. The lowest is at two hundred and six point five millimeters: zero point three one.
Here's every cut on the flipper at once, as a curve. Its lowest point is that cut.
Now the bill. Will its best cut leave them even less mixed?
No. The best cut on the bill leaves zero point three three. The flipper wins, by a little.
So that's how the tree chose its first question. It tried every cut, and kept the one that leaves the least mixed piles.
A pure pile can lose
Now this cut on the bill. It leaves eighty-three Adelies by themselves, a perfect pile. Spot the problem.
It leaves the penguins mixed... zero point four one. That's worse than the best cut on the flipper. It's worse than the best on the bill, too. Why? The other pile is still very mixed. A tree looks at both piles of a cut, not just the purest one.
And again, in each pile
Each question is the cut that leaves the least mixed piles.
Then the tree does the same thing again, inside each pile. On each side, the best cut is on the bill. Two questions.
It's the first lesson's tree, found this way. In a guessing game, you can ask anything. A tree only asks, "is this measurement over this number?"
How many questions it asks in a row is the tree's depth.
No limit remembers
With no limit, it keeps asking until every leaf holds one kind. How many of the two hundred and fifty-six will it get right?
All of them. It has twenty-two leaves. It remembers them... like the tree in the lesson on training and test sets.
Choose the depth on the folds
The depth is a setting. So choose it on five folds of the training set.
With one question, it's right about zero point seven nine of the time. Too few. With two, zero point nine four: the best. With as many as it wants, zero point nine three.
So does having no limit cost much?
On these easy penguins, only a little.
So keep two, and open the test set, just once. Eighty-two out of eighty-six.
In code
In real code, with scikit-learn. Grow the tree with no limit, and count its leaves: twenty-two. With a max depth of two, the folds give zero point nine four. Does a limit matter more on a real table? Take the bank's calls from the earlier lessons.
Here each measurement is a column. The columns of words become one-hot, and the numbers stay as they are. A tree doesn't need scaling, because it compares one column with one number at a time. A tree with no limit goes forty questions deep.
Guess its area under the ROC curve on its own calls, then on the folds.
Zero point nine nine on its own calls.
Zero point five nine on the folds, close to a coin's zero point five. With six questions, the folds give zero point seven one.
And a tree of three questions prints as a rule you can read. Its first question is about the days since an earlier campaign's call, where nine nine nine means never. So it asks: was this customer called in an earlier campaign? Then sixty-four in a hundred said yes. Never called before?
Nine in a hundred.
Three ideas
So: a tree asks questions in a row, each a cut on one measurement. Each question is chosen by trying every cut and keeping the least mixed piles. And you choose the depth on the folds.
The least mixed piles win
Each question is the cut that leaves the least mixed piles. Now try it on this lesson's page, and take the quiz. Find the tree's first question yourself.
You use this lesson in Lab 4: Neighbors, a tree and a forest, after Random forests.
Facts last checked on .
