Measuring the mix
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.
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.
Growing the tree
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.
"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.
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.
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.
Using the tree
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.
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.
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.
What happens
;; step 1/9 · data 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
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.