Module 1 · Beginner · Getting started with machine learning

How a decision tree makes predictions

How a decision tree makes predictions, for beginners: yes/no questions, leaves, depth and overfitting, with iris flowers and scikit-learn in Python.

By theprogrammers team · · 15 min read

A bank clerk deciding on a small loan might think: "Does the applicant have a steady income? If not, refuse. If yes, is the loan more than three months' salary? If it is, ask for a guarantor. If not, approve." That's a decision tree: a flowchart of yes/no questions, where each answer sends you down one branch until you reach a decision.

A machine learning decision tree works the same way, except that it learns the questions from data instead of being told them. Understanding how a decision tree makes predictions is worth an early lesson, because this course uses trees as an example model long before their own module: they need no scaling, train in a blink and, when small, you can read every rule they learnt.

What you need first: machine learning for beginners, where you trained your first tree, and data, features and labels.

Key terms

  • Decision tree: a model that predicts by asking a series of yes/no questions about the features.
  • Split (or node): one question, such as "is the petal shorter than 2.45 cm?".
  • Root: the first question, at the top of the tree.
  • Leaf: an end point with no more questions. It holds the prediction.
  • Depth: the largest number of questions asked on the way from the root to a leaf.

A tree you can write by hand

The iris data has 150 flowers from three species: setosa, versicolor and virginica. Two measurements are enough to tell them apart well: the length and width of the petal, in centimetres.

Download the data: iris.csv (4 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("iris.csv").

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris(as_frame=True)
flowers = iris.frame[["petal length (cm)", "petal width (cm)"]].copy()
flowers.columns = ["petal_length", "petal_width"]
flowers["species"] = iris.target_names[iris.target]
print(flowers.sample(6, random_state=1))
     petal_length  petal_width     species
14            1.2          0.2      setosa
98            3.0          1.1  versicolor
75            4.4          1.4  versicolor
16            1.3          0.4      setosa
131           6.4          2.0   virginica
56            4.7          1.6  versicolor

load_iris(as_frame=True) returns the data as a pandas DataFrame. iris.target holds the species as numbers 0, 1 and 2, and iris.target_names[...] turns them into names. sample(6, random_state=1) picks six random rows; random_state fixes which six, so you see the same ones.

Look at the six flowers and you can almost write the rules yourself: setosa petals are tiny, virginica petals are the widest. Here are those rules as Python, a hand-made tree of two questions:

def my_tree(petal_length, petal_width):
    if petal_length < 2.5:          # question 1: a tiny petal?
        return "setosa"
    if petal_width < 1.75:          # question 2: a narrow petal?
        return "versicolor"
    return "virginica"

guesses = [my_tree(l, w) for l, w in zip(flowers["petal_length"], flowers["petal_width"])]
print("correct:", round(np.mean(np.array(guesses) == flowers["species"]), 3))
correct: 0.96

zip walks through the two columns side by side, one flower at a time. np.mean(... == ...) counts the share of guesses that match the real species, because True counts as 1 and False as 0.

Two questions, and nearly every flower is right. A decision tree is exactly this kind of function. The only difference is that the computer chooses the questions and the cut-off numbers, 2.5 and 1.75, by looking at the data.

Let scikit-learn learn the questions

Split the flowers into training and test sets, as in the first model you trained, and let a tree of depth 2 learn from the training flowers. max_depth=2 allows at most two questions on any path, like the hand-made tree.

Predict first: which measurement will the tree ask about first, and roughly what cut-off will it choose?

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

X = flowers[["petal_length", "petal_width"]]
y = flowers["species"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)

tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_train, y_train)
print(export_text(tree, feature_names=list(X.columns)))
print("test accuracy:", round(tree.score(X_test, y_test), 3))
|--- petal_width <= 0.80
|   |--- class: setosa
|--- petal_width >  0.80
|   |--- petal_width <= 1.75
|   |   |--- class: versicolor
|   |--- petal_width >  1.75
|   |   |--- class: virginica

test accuracy: 0.956

export_text prints the learnt questions as indented text: each |--- line is one branch, and class: marks a leaf. stratify=y keeps the same share of each species in both sets, and random_state=0 makes the split repeatable.

Compare it with the hand-made tree. The second question is identical: petal width at 1.75. The first is different: the tree asks about petal width (at most 0.80 cm) where the hand-made tree asked about length. Both questions pick out the setosas perfectly, as the next sections show, so either is as good as the other. The tree doesn't know any botany: it tried many possible questions and kept the ones that separated the species best. (Scikit-learn always writes its questions as "at most", <=.)

Draw the tree

The same tree as a picture. This is the one picture to keep for decision trees: a flowchart of yes/no questions.

import matplotlib.pyplot as plt
from sklearn.tree import plot_tree

fig, ax = plt.subplots(figsize=(10, 6))
plot_tree(tree, feature_names=list(X.columns), class_names=list(tree.classes_),
          filled=True, rounded=True, impurity=False, fontsize=11, ax=ax)
plt.show()
A decision tree drawn as a flowchart. The root box asks whether petal width is at most 0.8 and holds 105 training flowers, 35 of each species. The True branch leads to an orange leaf of 35 setosa. The False branch leads to a second question, petal width at most 1.75, holding 70 flowers. Its two leaves are a green versicolor leaf with 34 versicolor and 3 virginica, and a purple virginica leaf with 1 versicolor and 32 virginica.

Each box shows its question at the top (flowers that answer "True" go left), then samples (how many training flowers reached it), value (how many of each species, in the order setosa, versicolor, virginica) and class (the majority, which is the prediction). filled=True colours each box by its majority species, and impurity=False hides a score you'll meet in the decision trees module.

Follow one flower down the tree

A new flower has a petal 4.8 cm long and 1.6 cm wide. Follow it through the picture before running the code: is 4.8 short enough for the first question? Which way does the second question send it?

new_flower = pd.DataFrame({"petal_length": [4.8], "petal_width": [1.6]})
print(tree.predict(new_flower))
print({name: round(float(p), 2) for name, p in zip(tree.classes_, tree.predict_proba(new_flower)[0])})
['versicolor']
{'setosa': 0.0, 'versicolor': 0.92, 'virginica': 0.08}

The new flower is wrapped in a one-row DataFrame with the same column names as the training data, because scikit-learn checks that the names match. predict_proba gives the share of each species among the training flowers in the leaf where the new flower lands. The tree's "probability" is just that leaf's mix of species.

A tree cuts the data into boxes

Every question is a straight cut across one feature: "petal width at most 0.80" is a horizontal line on a chart of length against width. Both of this tree's questions are about width, so its two cuts are both horizontal lines, and they divide the chart into three bands, and every flower in a band gets that band's species.

from sklearn.inspection import DecisionBoundaryDisplay

fig, ax = plt.subplots(figsize=(7, 5))
DecisionBoundaryDisplay.from_estimator(tree, X, ax=ax, alpha=0.3, cmap="viridis",
                                       response_method="predict")
for name, colour in zip(tree.classes_, ["#440154", "#21918c", "#fde725"]):
    part = X[y == name]
    ax.scatter(part["petal_length"], part["petal_width"], color=colour, edgecolor="k", s=30, label=name)
ax.set_xlabel("Petal length (cm)")
ax.set_ylabel("Petal width (cm)")
ax.set_title("Two questions, three bands")
ax.legend()
plt.show()
Scatter plot of petal width against petal length for the iris flowers, with the background split into three horizontal bands. Below a width of 0.8, a purple band holds the setosa cluster in the bottom left. Between 0.8 and 1.75, a teal band holds most versicolor flowers, with a few yellow virginica points inside it. Above 1.75, a yellow band holds the virginica flowers, with one teal versicolor point.

DecisionBoundaryDisplay asks the model to predict every point on a fine grid and colours the chart by the answer. The boundaries are always made of straight lines parallel to the axes, because each question looks at one feature at a time. That's why a tree draws a staircase when the real boundary is a diagonal.

How does a tree choose its questions?

Think of sorting a mixed bag of coins into piles. A good first question ("is it silver?") leaves piles that are each mostly one kind. A useless one ("was it minted on a Tuesday?") leaves every pile as mixed as the bag.

A tree does the same with the training data. At each step it tries every feature and many cut-off values, and keeps the question that leaves the two groups least mixed. Here are three possible first questions for the training flowers, with the number of each species on the "yes" side and the "no" side:

for feature, cut in [("petal_length", 2.45), ("petal_width", 1.0), ("petal_length", 4.0)]:
    yes = y_train[X_train[feature] < cut].value_counts().reindex(tree.classes_, fill_value=0)
    no = y_train[X_train[feature] >= cut].value_counts().reindex(tree.classes_, fill_value=0)
    print(f"{feature} < {cut}: yes {list(yes)}   no {list(no)}")
petal_length < 2.45: yes [35, 0, 0]   no [0, 35, 35]
petal_width < 1.0: yes [35, 0, 0]   no [0, 35, 35]
petal_length < 4.0: yes [35, 10, 0]   no [0, 25, 35]

value_counts() counts each species, and reindex(..., fill_value=0) lists all three species in the same order, with 0 for any that's missing.

The first and second questions both give a perfectly pure "yes" group of setosas. The third splits the versicolors across both sides, leaving both groups mixed, so it's worse. The real algorithm measures "mixed" with a score called Gini impurity, covered with its formula in decision trees explained. The idea is just this counting.

Deeper trees: more questions, more risk

max_depth limits how many questions a tree may ask. Without a limit, the tree keeps splitting until every leaf is pure, even if that means a question that exists only to fit one odd flower. That's overfitting: memorising the training data instead of learning the pattern.

Experiment: train trees of depth 1, 2, 3 and unlimited, and predict which one scores best on the test flowers before you run it.

for depth in [1, 2, 3, None]:
    t = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
    print(f"max_depth={str(depth):4}: leaves {t.get_n_leaves():2}, "
          f"train {t.score(X_train, y_train):.3f}, test {t.score(X_test, y_test):.3f}")
max_depth=1   : leaves  2, train 0.667, test 0.667
max_depth=2   : leaves  3, train 0.962, test 0.956
max_depth=3   : leaves  5, train 0.962, test 0.956
max_depth=None: leaves  7, train 0.990, test 0.978

max_depth=None means no limit. get_n_leaves() counts the end points.

A surprise: the unlimited tree does best here, 0.978 on the test flowers. Iris is unusually clean. The species really are separated by petal size, so the extra questions find real detail rather than noise. Real data is rarely this tidy: labels get typed wrongly and measurements are rough.

See it fail: scramble the labels of 15 of the 105 training flowers, giving each a random species, and train again. The test flowers keep their true labels.

rng = np.random.default_rng(3)
noisy = y_train.to_numpy().copy()
scrambled = rng.choice(len(noisy), size=15, replace=False)
noisy[scrambled] = rng.choice(tree.classes_, size=15)

for depth in [2, None]:
    t = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, noisy)
    print(f"max_depth={str(depth):4}: leaves {t.get_n_leaves():2}, "
          f"train {t.score(X_train, noisy):.3f}, test {t.score(X_test, y_test):.3f}")
max_depth=2   : leaves  4, train 0.867, test 0.956
max_depth=None: leaves 29, train 0.952, test 0.889

rng.choice(len(noisy), size=15, replace=False) picks 15 different row positions; the second rng.choice gives each a random species, which may by chance be the right one.

The depth-2 tree shrugs off the noise: its few questions follow the main pattern, and it still scores 0.956 on the test flowers. The unlimited tree grows 29 leaves, many of them little boxes around single mislabelled flowers, and its test score falls to 0.889. That's overfitting: it learnt the mistakes as if they were rules.

A tree can predict numbers too

For a number, such as a price, each leaf predicts the average of the training rows that reach it. Six students' hours of study and marks:

from sklearn.tree import DecisionTreeRegressor

hours = np.array([[1], [2], [3], [6], [7], [8]])
marks = np.array([35, 40, 45, 70, 75, 80])
reg = DecisionTreeRegressor(max_depth=1).fit(hours, marks)
print(reg.predict([[2.5], [5], [9]]))
[40. 75. 75.]

With one question, the tree splits the students into a low-hours group and a high-hours group and predicts each group's average mark. Every student who studied less than the cut-off gets the same prediction, however many hours they studied. Regression trees predict in steps, never along a smooth line.

When to use a decision tree

SituationDecision tree?Better choice
You need rules a person can read and checkYes, a small tree
Mixed features, different units, no time to scaleYes: trees don't need scaling
A quick first model to see which features matterYes
You need the most accurate model on a table of dataUsually not on its ownRandom forests or gradient boosting, built from many trees
A smooth relationship, such as price rising steadily with areaNot ideal: trees predict in stepsLinear regression
Very small dataRisky: a tree changes a lot with a few rowsLogistic regression, KNN

Practice

  1. Using the hand-made my_tree, what species is a flower with a petal 5.0 cm long and 1.5 cm wide? Work it out without running code, then check.
Show the answer

5.0 is not below 2.5, so it's not setosa. 1.5 is below 1.75, so the answer is versicolor.

print(my_tree(5.0, 1.5))
versicolor
  1. Why doesn't a decision tree need its features scaled, when KNN and many other models do?
Show the answer

Each question compares one feature with a cut-off ("is the petal width below 1.75?"). Multiplying a feature by 10 would just multiply the cut-off by 10, and the same flowers would go the same way. Nothing in a tree adds or compares different features, so their units never meet.

  1. In the depth experiment, the unlimited tree has the most leaves. Why does a tree with more leaves score at least as well on the training data, but not necessarily on the test data?
Show the answer

Each extra question can only separate the training flowers more finely, so training accuracy never goes down. But some of those questions exist to fit one or two unusual flowers. New flowers don't share those quirks, so the extra questions can make test predictions worse. That's overfitting.

  1. A regression tree with max_depth=1 predicts house prices. How many different prices can it ever predict? What about max_depth=3?
Show the answer

Depth 1 has one question and two leaves, so it can predict only 2 different prices. Depth 3 has at most 2 × 2 × 2 = 8 leaves, so at most 8 different prices. Every house that lands in the same leaf gets the same price.

  1. Train a tree of depth 3 on all four iris measurements (iris.data, iris.target) with the same kind of split. Print its rules. Does it still ask mostly about petals?
Show the answer
Xa_train, Xa_test, ya_train, ya_test = train_test_split(
    iris.data, iris.target, test_size=0.3, stratify=iris.target, random_state=0)
full = DecisionTreeClassifier(max_depth=3, random_state=0).fit(Xa_train, ya_train)
print(export_text(full, feature_names=list(iris.feature_names)))
|--- petal width (cm) <= 0.80
|   |--- class: 0
|--- petal width (cm) >  0.80
|   |--- petal width (cm) <= 1.75
|   |   |--- petal length (cm) <= 4.95
|   |   |   |--- class: 1
|   |   |--- petal length (cm) >  4.95
|   |   |   |--- class: 1
|   |--- petal width (cm) >  1.75
|   |   |--- petal length (cm) <= 4.85
|   |   |   |--- class: 2
|   |   |--- petal length (cm) >  4.85
|   |   |   |--- class: 2

Every question is about the petals, even though the sepal measurements were available: petal size separates the species far better, so the tree picks it every time. The classes print as 0, 1 and 2 (setosa, versicolor, virginica) because iris.target holds numbers. Notice that two of the depth-3 questions lead to leaves with the same class on both sides: they made the training groups a little purer without changing any prediction.

Interview questions

How does a decision tree make a prediction?

It starts at the root and answers one yes/no question about a feature at each node, following the matching branch until it reaches a leaf. A classification tree predicts the majority class of the training rows in that leaf; a regression tree predicts their average.

How does a decision tree choose where to split?

At each node it tries the possible features and thresholds and picks the split that makes the resulting groups purest, measured with Gini impurity or entropy for classification and squared error for regression. It repeats this greedily for each new node.

Why do decision trees overfit, and how do you prevent it?

Without limits, a tree keeps splitting until every leaf is pure, fitting noise in the training data. Limit max_depth, require a minimum number of rows per leaf (min_samples_leaf), prune the tree, or combine many trees in a random forest.

Key takeaways

  • A decision tree is a flowchart of yes/no questions; each leaf holds a prediction.
  • It learns the questions by trying many cut-offs and keeping the one that leaves the groups least mixed.
  • Each question looks at one feature, so trees need no scaling and draw boundaries out of straight, axis-parallel cuts.
  • Classification leaves predict the majority class; regression leaves predict the average, so predictions come in steps.
  • Deeper trees fit the training data better but can overfit; limit them with max_depth.

Frequently asked questions

Is a decision tree supervised or unsupervised?

Supervised: it learns from rows that already have the answer (the label), and it predicts that answer for new rows.

What's the difference between a decision tree and a random forest?

A random forest trains hundreds of trees, each on a slightly different random sample of the data, and lets them vote. It's usually more accurate and less likely to overfit than one tree, but much harder to read.

Why does this course use decision trees before teaching them fully?

Because they need no scaling and train instantly, they're a convenient example model for lessons about data and evaluation. This lesson gives enough to follow those lessons; the full method, with Gini impurity and pruning, is in the decision trees module.

What to learn next

  1. Turn a vague goal into a clear machine learning problem in how to frame a machine learning problem, the next lesson.
  2. See every step of a project in the machine learning workflow.
  3. Read the full method, with Gini impurity and pruning, in decision trees explained.