Machine Learning with scikit-learn

Decision Tree in Python with scikit-learn

Train a tree of yes/no questions, print it with export_text, and limit its depth to stop it memorising.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • DecisionTreeClassifier and max_depth
  • Reading the rules with export_text
  • Spotting overfitting from train and test scores
The depth-2 iris tree
  • petal width <= 0.75
    • class 0
    • petal length <= 4.75
      • class 1
      • class 2

A tree of questions

The problem

Sometimes you need a model whose decisions you can explain to a person, step by step: why was this loan refused, why is this flower a versicolor?

Think of it like this

A decision tree works like the game of twenty questions. Each question splits the remaining possibilities in two, and the best questions come first. When the answer is clear, you stop and name the class.

From twenty questions to code
fit(X_train, y_train)❓ Find the questions that split the classes best
max_depth=2✋ Ask at most two questions in a row
export_text(tree)📜 Print the questions as rules
predict(X_test)🌸 Follow the answers down to a class
Each node is a yes/no question about one feature.
In one sentence

A decision tree splits the data again and again on the feature and threshold that best separate the classes, and predicts the majority class of the leaf a sample ends in.

Key points

  1. The first question is petal width (cm) <= 0.75: if yes, the flower is class 0.
  2. Otherwise petal length (cm) <= 4.75 separates class 1 from class 2.
  3. The depth-2 tree scores 0.956 on the test set.
  4. Without a limit the tree reaches depth 6 and 1.000 on the training data, a sign of memorising.

When should you use it?

  • Models that must be explained to people.
  • Data with a mix of numeric and category features.
  • The building block of random forests and gradient boosting.

When not to use it

  • When you need the best accuracy: a random forest is usually better.
  • Small changes in the data can change a single tree a lot; average many trees for stability.

Example code

Open in editor →
main.py
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.3, random_state=1, stratify=iris.target
)

# max_depth=2 keeps the tree small enough to read
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)
print(f"Test accuracy (depth 2): {tree.score(X_test, y_test):.3f}")
print(export_text(tree, feature_names=list(iris.feature_names)))

deep = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"No depth limit: depth {deep.get_depth()}, train {deep.score(X_train, y_train):.3f}, test {deep.score(X_test, y_test):.3f}")
Get a Run button for this example

Result of running the code

Test accuracy (depth 2): 0.956
|--- petal width (cm) <= 0.75
|   |--- class: 0
|--- petal width (cm) >  0.75
|   |--- petal length (cm) <= 4.75
|   |   |--- class: 1
|   |--- petal length (cm) >  4.75
|   |   |--- class: 2

No depth limit: depth 6, train 1.000, test 0.978

Code explanation

DecisionTreeClassifier(max_depth=2) may ask at most two questions in a row. export_text prints them: a petal width of 0.75 cm or less means class 0 (setosa), otherwise a petal length of 4.75 cm separates class 1 from class 2. Even this small tree scores 0.956 on the test set. Without a depth limit the tree grows to depth 6 and gets every training flower right (1.000), a sign it is memorising the training data; on this easy dataset the test score still holds at 0.978, but on noisier data an unlimited tree usually does worse.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Growing the tree without any limit

A full-depth tree fits the training data perfectly and often does worse on new data.

Problem
DecisionTreeClassifier().fit(X_train, y_train)
Fix
DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson