Decision trees
About this lesson
A decision tree predicts by asking a short chain of yes/no questions about the features. Learning one means choosing those questions: try every "feature ≤ threshold" split, keep the one that leaves the purest groups by Gini impurity, and repeat on each group until it is pure or the tree is deep enough. Watch eight students grow a two-question tree, predict a new student, and see why deep trees overfit.
Eight labelled students
Our training data: eight students. For each we know two features, hours studied and hours slept, and a label: did they pass or fail the quiz? A decision tree learns to predict the label by asking yes/no questions.
hours sleep label 1 8 fail 2 6 fail 2 9 fail 3 7 pass 4 4 fail 4 8 pass 5 5 fail 6 6 pass 5 fail, 3 pass
Read the lesson step by step
Eight labelled students
Our training data: eight students. For each we know two features, hours studied and hours slept, and a label: did they pass or fail the quiz? A decision tree learns to predict the label by asking yes/no questions.
hours sleep label 1 8 fail 2 6 fail 2 9 fail 3 7 pass 4 4 fail 4 8 pass 5 5 fail 6 6 pass 5 fail, 3 passHow mixed is a group?
All eight start at the root. A group is pure when every label matches. Gini impurity measures the mix: 1 minus each label's share squared. Here 5 fail, 3 pass: 1 − (5/8)² − (3/8)² = 0.47.
def gini(labels): n = len(labels) return 1 - sum((labels.count(c) / n) ** 2 for c in set(labels)) root: 5 fail, 3 pass gini = 1 - (5/8)**2 - (3/8)**2 = 30/64 = 0.46875 pure group -> 0 · half and half -> 0.5Try every question
The learner tries every question "feature ≤ threshold", with thresholds halfway between neighbouring values: 10 in all. Each splits the group in two. Its score: the two Gini values, weighted by group size. Lower means purer.
question yes no weighted Gini hours ≤ 2.5? 3 5 0.30 hours ≤ 5.5? 7 1 0.36 sleep ≤ 5.5? 2 6 0.38 sleep ≤ 7.5? 5 3 0.47 ... 10 questions tried in all, 4 shownKeep the best question
"hours ≤ 2.5?" scores lowest. Yes: 3 students, all fail, Gini 0. No: 2 fail, 3 pass, Gini 0.48. Weighted: 3/8 × 0 + 5/8 × 0.48 = 0.30. The two groups become child nodes.
best: hours ≤ 2.5? weighted Gini 0.30 yes (1,8) (2,6) (2,9) all fail no (3,7) (4,4) (4,8) (5,5) (6,6) 2 fail, 3 pass -> Gini 0.48 impurity: 0.47 -> 0.30A pure group is a leaf
The yes group is pure: all three failed. No question can make it purer, so growing stops there and it becomes a leaf. A leaf holds an answer instead of a question: here, fail.
labels = ["fail", "fail", "fail"] gini(labels) -> 0.0 gini == 0 -> stop: return "fail" leaf = an answer, not a questionRepeat on the mixed group
The no group is still mixed, so the same recipe runs again on just those five. Now "sleep ≤ 5.5?" wins: 2 fail on the yes side, 3 pass on the no side. Both are pure, so both become leaves.
rows: (3,7) (4,4) (4,8) (5,5) (6,6) best_split(rows) -> sleep ≤ 5.5? weighted Gini 0.00 yes (4,4) (5,5) fail, fail no (3,7) (4,8) (6,6) pass x3 the same function, called again on a smaller group: that is recursionThe tree is a rule
Every leaf is pure, so growing stops. The tree has depth 2 and 3 leaves, and it is just nested if statements: the kind of rule a person might write, but found from the data.
def predict(hours, sleep): if hours <= 2.5: return "fail" if sleep <= 5.5: return "fail" return "pass" print(tree) -> (0, 2.5, 'fail', (1, 5.5, 'fail', 'pass')) (feature 0 = hours, feature 1 = sleep)Predict a new student
A new student studied 4 hours and slept 7. Is hours ≤ 2.5? No, go right. Is sleep ≤ 5.5? No, go right. That leaf says pass. Each prediction costs only two comparisons.
predict(4, 7) hours <= 2.5? 4 <= 2.5 -> no sleep <= 5.5? 7 <= 5.5 -> no return "pass" the tree never saw this student; it answers anywayDeep trees memorise noise
Real data is noisy. Add one odd student: 5 hours studied, 9 slept, failed. Grown until every leaf is pure, the tree adds "sleep ≤ 8.5?" just for that student: overfitting. With max_depth = 2, the leaf keeps its majority: pass.
odd student: (5, 9, fail) no depth cap: depth 3, 4 leaves max_depth=2: depth 2, 3 leaves, same questions its leaf: 3 pass, 1 fail -> answers "pass" limits that fight overfitting: max_depth, min_samples_leaf, pruning
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A group holds 2 pass and 2 fail. What is its Gini impurity?
1 − (2/4)² − (2/4)² = 1 − 0.25 − 0.25 = 0.5, the most mixed a two-label group can be. A pure group scores 0.
02A split sends 3 students to a pure group (Gini 0) and 5 to a group with Gini 0.48. What is the split's weighted Gini?
Weight each side by its share of the 8 students: 3/8 × 0 + 5/8 × 0.48 = 0.30. The learner keeps the question with the lowest weighted Gini.
03Hours studied takes the values 1, 2, 3, 4, 5 and 6 in the data. Which thresholds does the learner try for that feature?
Any threshold between two neighbouring values splits the data the same way, so trying the halfway points covers every possible split: 5 per feature here, 10 in all.
04Using the learned tree (hours ≤ 2.5? then sleep ≤ 5.5?), what does it predict for a student who studied 6 hours and slept 5?
6 ≤ 2.5 is false, so go to the second question; 5 ≤ 5.5 is true, so the leaf answers "fail". A tree answers for any student, seen or not.
05Why would you cap a tree with max_depth instead of growing it until every leaf is pure?
Grown until pure, a tree memorises odd examples with extra questions. Limits such as max_depth, min_samples_leaf or pruning keep it simpler, which usually predicts unseen data better.
Glossary
- Decision tree
- A model that predicts by asking a chain of yes/no questions about the features, from the root down to a leaf.
- Feature
- One measured property of an example, such as hours studied. A question compares one feature with a threshold.
- Node, root, leaf
- A node holds a question; the root is the first one. A leaf holds an answer (here pass or fail) instead of a question.
- Gini impurity
- How mixed a group's labels are: 1 minus the sum of each label's share squared. 0 means pure.
- Weighted Gini
- A split's score: each side's Gini, weighted by the share of examples that went to that side. Lower is better.
- Greedy splitting
- Choosing the best question at each node on its own, without looking ahead. Fast, but not guaranteed to find the best whole tree.
- Overfitting
- Fitting the training data so closely, noise included, that predictions on new data get worse.
- max_depth
- A limit on how many questions deep a tree may grow; one of several ways to stop overfitting, with min_samples_leaf and pruning.
Notes and sources
- The eight students are made up, and far too few for a real model; they keep every number small enough to check by hand.
- This is the CART recipe (Breiman et al., 1984): binary questions scored by Gini impurity. ID3 and C4.5 (Quinlan) use entropy and information gain instead; both usually pick similar questions.
- Growing is greedy: each node keeps the best question for itself and never looks ahead. Finding the very best whole tree is far too slow in general, so all common libraries grow greedily.
- In practice you would use scikit-learn: DecisionTreeClassifier(max_depth=2), then .fit(X, y) and .predict(...). It uses an optimised CART with Gini by default and the same "feature <= threshold" questions.
- The Python learner in the lesson is real: run it and it prints the tree and then "pass".
- scikit-learn User Guide, 1.10 Decision Trees: CART, Gini and entropy, max_depth, min_samples_leaf, overfitting
- scikit-learn API: sklearn.tree.DecisionTreeClassifier (criterion="gini" by default)
- Hastie, Tibshirani & Friedman, The Elements of Statistical Learning, 2nd ed. (2009), section 9.2: tree-based methods, Gini index, pruning
- James, Witten, Hastie & Tibshirani, An Introduction to Statistical Learning, 2nd ed. (2021), chapter 8: tree-based methods
- J. R. Quinlan, Induction of Decision Trees, Machine Learning 1, 81–106 (1986): ID3 and information gain
- Breiman, Friedman, Olshen & Stone, Classification and Regression Trees (Wadsworth, 1984; CRC Press reprint): CART
- Python Tutorial, 4.1 if statements
Quiz Unlocks after the last step.