ML Atlas

Machine learning from zero · Lesson 5.1 · 26 of 33 lessons ready · 10 min

Decision trees: twenty questions with data

In short

A decision tree classifies by asking yes-or-no questions, each chosen to split the data as cleanly as possible. The example: who survived the Titanic.

Warm-up Two questions from earlier lessons. A minute, and it never blocks the lesson.
From lesson 4.6: Pipelines: from a table to a prediction Why do you fit the scaler on the training part only?

Show the answer

Correct answer: Because the scaler is part of the model, and the test must play data the model never saw

The test plays new penguins. The mean and the spread are also something the model learns, so they are computed on the training part only.

From lesson 4.5: Data leakage You fill missing values with the mean of the whole file, split into training and test, train on training and score on test. Which step leaks?

Show the answer

Correct answer: Filling the gaps with the mean computed over the whole file

The mean includes the test data, so the test shapes training. Fit the imputation on training only, ideally in a pipeline.

Remember the game of twenty questions? "Is it alive?" "Is it bigger than a cat?" A good player does not ask random questions; they ask the one that cuts the remaining possibilities roughly in half. A decision tree is a model that plays this game with data — and because its questions are written in plain language, it is one of the few models you can read like a flowchart.

Predict, then check A tree of depth 20 gets more than 98% of the training passengers right, and a tree of depth 1 (a single question) about 79%. Which one gets more right on the test passengers?
How sure are you?

Interactive lab

This interactive lab runs in a browser with JavaScript enabled. The text around it describes what the lab shows.

Show the answer

Correct answer: The shallow one (depth 1)

Depth 20 scores 98.7% on training but 73.9% on test. Depth 1 scores 79.3% on training and 77.2% on test. The deep tree memorised the passengers (114 of its 145 leaves cover 5 people or fewer) instead of learning a rule; the best test score, 79.5%, comes from depth 3.

Try this

  • Set the max depth slider to 1. The tree may ask only one question. Read it in the list of splits: which feature did the algorithm consider most informative?
  • Raise the max depth slider one step at a time. Watch the training accuracy climb and compare it with the test accuracy at each depth.
  • Push the max depth slider to the maximum. Is the training accuracy close to perfect? What happened to the test accuracy?
  • Find the depth where test accuracy is best and read the top splits there. Could you explain this tree to someone in two sentences?

Now that you've tried it, let's see what was actually going on.

The idea in plain words

A decision tree predicts by asking a sequence of yes-or-no questions about the features: "Is the passenger's age below some value?", "Did they travel in first class?". Each answer sends the example down one branch, and the next question depends on the previous answers. At the end of every path sits a leaf with a prediction — usually the most common label among the training examples that ended up there.

In this lesson we use data on 891 passengers of the Titanic, of whom 342 survived. The features include ticket class, sex, age, the number of relatives on board and the fare paid. The tree learns which questions about these features best separate those who survived from those who did not.

Think of a triage nurse in an emergency room. She does not compute a weighted sum; she follows a short chain of questions — breathing? bleeding? conscious? — each one narrowing down what to do. A tree is that chain, learned from data instead of written by doctors.

Why it works

The tree is built from the top, one question at a time. At each step the algorithm tries every feature and every possible cut-off value and asks: which question splits this group into two groups that are as pure as possible, meaning each contains mostly one label? A popular measure of impurity is the Gini index of a group:

Gini = 1 − Σ pₖ²

where pₖ is the share of label k in the group. A group where everyone has the same label has Gini 0; a group split half and half between two labels has Gini 0.5, the worst possible for two classes. The algorithm picks the question that lowers the average impurity the most, then repeats the procedure separately inside each branch. This greedy, step-by-step search does not guarantee the best possible tree, but it is fast and works well in practice.

Left alone, the tree keeps splitting until every leaf is pure — even if a leaf holds a single passenger. At that point it has memorised the training data, noise and all: the overfitting of lesson 7 in a new costume. The main control is the maximum depth, the number of questions allowed along any path. A shallow tree is easy to read but may miss real patterns; a deep tree fits the training data almost perfectly and generalises worse. Cross-validation from lesson 8 is the honest way to pick the depth.

Common mistake

A split is not an explanation of cause. The tree asks about the feature that best separates the labels in this data, and that can be a stand-in for something else: ticket class and fare go together, and both say something about where on the ship a passenger slept. The second mistake is trusting a deep tree because its rules look so precise. A rule like "age between 31.5 and 32.5 and fare above some value" is usually the tree describing one or two passengers, not a pattern. Small changes in the data can also change the first split and therefore the entire tree, which makes single trees unstable.

That instability is a weakness, but it can be turned into a strength. In the next lesson we grow many different trees and let them vote.

Quiz

Three questions to check yourself. Pick an answer, or open the answer under a question. Keyboard: arrow keys choose, Enter or Space confirms.

1. How does a decision tree choose the question at each step?
Show the answer

Correct answer: It tries possible questions and picks the one that leaves the purest groups

The greedy search evaluates candidate splits and keeps the one that lowers impurity, such as the Gini index, the most.

2. A tree with unlimited depth reaches almost perfect training accuracy. Why is that a warning sign?
Show the answer

Correct answer: Because it has probably memorised the passengers, so it generalises worse

A tree that splits until every leaf is pure fits the noise of the training sample, the classic sign of overfitting.

3. What is the Gini index of a group in which every passenger survived?
Show the answer

Correct answer: 0 — the group is perfectly pure

If one label has share 1, the sum of squared shares is 1 and Gini equals 1 − 1 = 0, a perfectly pure group.

Key takeaways

  • A decision tree predicts with a chain of yes-or-no questions that you can read like a flowchart.
  • Each split is chosen greedily to make the resulting groups as pure as possible, for example by the Gini index.
  • Maximum depth controls complexity: shallow trees underfit, deep trees memorise.
  • A split shows what separates the labels in the data, not what causes the outcome.

Going further: formula, code, practice

The math

For a group with label shares pₖ, Gini = 1 − Σ pₖ². For two classes it runs from 0 (one label only) to 0.5 (half and half). The whole Titanic table, 342 survivors of 891, has Gini = 1 − (342/891)² − (549/891)² ≈ 0.473.

A split sends n_L rows left and n_R rows right, n = n_L + n_R. Its quality is the drop in impurity: Δ = G(parent) − (n_L/n) · G(left) − (n_R/n) · G(right). The tree takes the question with the largest Δ, then repeats inside each branch. Entropy, −Σ pₖ log₂ pₖ, is an alternative impurity that behaves similarly.

A tree of depth d has at most 2^d leaves. A leaf predicts the majority label of its training rows, so a leaf of one passenger predicts that passenger's label exactly.

In code (Python)

The 891 passengers with six features (sex as 0/1, missing ages filled with the training median) and a stratified 30% test split. This is the same kind of experiment as the lab but another split, so the numbers differ a little from the lab's. The notebook linked under the output fetches the data itself.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

df = pd.read_csv("data/raw/titanic.csv")
X = pd.DataFrame({"female": (df["sex"] == "female").astype(int)}).join(df[["pclass", "age", "sibsp", "parch", "fare"]])
Xtr, Xte, ytr, yte = train_test_split(X, df["survived"], test_size=0.3, stratify=df["survived"], random_state=1)
Xtr, Xte = Xtr.fillna({"age": Xtr["age"].median()}), Xte.fillna({"age": Xtr["age"].median()})  # train median for both
print(f"passengers {len(df)}, survived {df['survived'].sum()}")
for d in (1, 3, 20):
    t = DecisionTreeClassifier(max_depth=d, random_state=0).fit(Xtr, ytr)
    print(f"depth {d:2d}: train {t.score(Xtr, ytr):.3f}, test {t.score(Xte, yte):.3f}, leaves {t.get_n_leaves()}")

Output

passengers 891, survived 342
depth  1: train 0.780, test 0.802, leaves 2
depth  3: train 0.833, test 0.802, leaves 8
depth 20: train 0.986, test 0.780, leaves 141

A depth-1 tree is a single question. The depth-20 tree is almost perfect on the training passengers and worse than the single question on the test passengers.

For practitioners
  • Limit the tree: max_depth, min_samples_leaf or ccp_alpha (pruning). Choose the value by cross-validation, not by training accuracy.
  • Do not read a deep tree as a set of rules. A leaf with a handful of passengers is memory, not a pattern.
  • Trees do not need scaled features, but they need numbers. Encode categories (for example sex as 0/1) and decide what to do with missing values. Fit the imputation on the training set only.
  • A single tree is unstable: a small change in the data can change the first split. If you only need accuracy, an ensemble of trees is a safer choice.
  • A split is a statement about this data, not about cause. Ticket class and fare stand in for each other, so the tree may pick either one.

Go deeper in the Atlas

Encyclopedia entries on the ideas in this lesson: