Decision Trees

Updated · 5 min read
mediumPython 3.13aimachine-learningdecision-treesoverfittingscikit-learn

A decision tree is a model that makes predictions by asking a series of yes-or-no questions about the features, like a flowchart. Each question splits the data into two groups that are as pure as possible; each final group, called a leaf, gives a prediction. Trees are easy to read and explain, handle mixed features without scaling, and are the building block of the powerful models in the next lesson.

Reading a Tree

Questions, groups, and when to stop growing
PartDescription
SplitIt is used to divide the data by a question, such as past_late <= 1.5
LeafIt is used to make the prediction for every example that ends there
max_depthIt is used to limit how many questions in a row the tree may ask
OverfittingLearning the training data's noise, so test accuracy drops

Example

This program uses payments_history.csv from "Supervised Learning".

Python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
 
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
small = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_train, y_train)
print(export_text(small, feature_names=list(X.columns), show_weights=True))  # [on time, late] counts
 
for depth in [2, 4, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
    print(f"max_depth {str(depth):4}: train {tree.score(X_train, y_train):.1%}, test {tree.score(X_test, y_test):.1%}")
Output
|--- past_late <= 1.50
|   |--- amount <= 155.00
|   |   |--- weights: [456.00, 24.00] class: 0
|   |--- amount >  155.00
|   |   |--- weights: [82.00, 31.00] class: 0
|--- past_late >  1.50
|   |--- autopay <= 0.50
|   |   |--- weights: [53.00, 43.00] class: 0
|   |--- autopay >  0.50
|   |   |--- weights: [52.00, 9.00] class: 0
 
max_depth 2   : train 85.7%, test 85.6%
max_depth 4   : train 89.1%, test 87.6%
max_depth None: train 98.3%, test 83.2%

Explanation: The first split is on past late payments, the strongest signal. Each leaf shows [on time, late] counts from the training data: families with two or more late payments and no autopay paid late 43 times out of 96, the riskiest group. Every leaf still predicts "on time" because on-time payers are the majority in every group, which is why the depth-2 tree only matches the baseline. Depth 4 does best on the test set (87.6%). With no depth limit, the tree scores 98.3% on training data but only 83.2% on new families: it has memorized noise.

Strengths and Weaknesses

StrengthsWeaknesses
Easy to read and explainOne tree overfits easily
No feature scaling neededSmall data changes can change the tree a lot
Captures interactions, like amount and autopay togetherUsually less accurate than ensembles of trees

Common Mistakes

Growing trees without limits. Set max_depth or min_samples_leaf.

Trusting one tree's structure too much. A slightly different sample can produce different questions.

Ignoring the leaf counts. A leaf labeled "on time" may still hold a risky group.

Interview Corner

How does a decision tree choose its splits?

At each step it picks the feature and value that best separate the labels into purer groups, measured with criteria such as Gini impurity or entropy.

How do you stop a decision tree from overfitting?

Limit its growth with max_depth, min_samples_leaf or pruning, and choose the limits by validating on unseen data.

Practice

Exercise: find the best depth. Try depths 1 to 8 and print train and test accuracy for each. At what depth does the gap between them start to grow?

Check your understanding:

  1. What does the first split tell you?
  2. Which group was riskiest, and how risky?
  3. Why did the unlimited tree do worse on the test set?

Quick check: decision trees

4 questions
1What was the tree's first question?
2What did the unlimited-depth tree score on the test set?
3What does a big train-test gap show?
4Do decision trees need scaled features?

Key Takeaways

Quick reference

NeedCode
ModelDecisionTreeClassifier(max_depth=4)
Print rulesexport_text(tree, feature_names=..., show_weights=True)
Check overfittingCompare score on train and test

Was this tutorial helpful?

Lesson 123 of 186