TExcelTAD
Home › Machine Learning › ML Decision Tree

ML Decision Tree

So far we predicted numbers. Many questions have a category as the answer instead: yes or no, spam or not spam, which species. Predicting a category is called classification, and one of the most intuitive classifiers is the decision tree.

A decision tree is a flowchart of yes/no questions. To classify an example you start at the top (the root), answer a question about one feature, follow the matching branch, and repeat until you reach a leaf that holds the answer. You have probably made decisions like this yourself:

text
Is it raining more than 2 mm?
├── yes → stay home
└── no  → Is it warmer than 8 °C?
          ├── yes → go hiking
          └── no  → stay home

The machine-learning part: the computer learns the questions from data.

The data

Here is an invented record of 16 weekends: the weather, whether friends were free, and whether the person went hiking. Machine-learning models need numbers, so yes/no columns are stored as 1/0.

python · try it yourself
import io
import pandas as pd

csv = """temp_c,rain_mm,wind_kmh,friends,hike
18,0,10,1,1
22,0,5,0,1
9,4,20,1,0
14,1,15,1,1
25,0,30,0,0
6,0,10,1,0
16,6,12,1,0
20,0,8,1,1
11,0,25,0,0
19,2,10,0,1
24,0,12,1,1
13,8,18,0,0
17,0,35,1,0
21,1,9,0,1
8,0,6,1,0
15,0,11,0,1"""
weekends = pd.read_csv(io.StringIO(csv))
print(weekends.head(8))
print("hiked on", weekends["hike"].sum(), "of", len(weekends), "weekends")
   temp_c  rain_mm  wind_kmh  friends  hike
0      18        0        10        1     1
1      22        0         5        0     1
2       9        4        20        1     0
3      14        1        15        1     1
4      25        0        30        0     0
5       6        0        10        1     0
6      16        6        12        1     0
7      20        0         8        1     1
hiked on 8 of 16 weekends

Training a tree

DecisionTreeClassifier follows the usual pattern. export_text prints the learned rules in a readable form:

python · try it yourself
import io
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text

csv = """temp_c,rain_mm,wind_kmh,friends,hike
18,0,10,1,1
22,0,5,0,1
9,4,20,1,0
14,1,15,1,1
25,0,30,0,0
6,0,10,1,0
16,6,12,1,0
20,0,8,1,1
11,0,25,0,0
19,2,10,0,1
24,0,12,1,1
13,8,18,0,0
17,0,35,1,0
21,1,9,0,1
8,0,6,1,0
15,0,11,0,1"""
weekends = pd.read_csv(io.StringIO(csv))
features = ["temp_c", "rain_mm", "wind_kmh", "friends"]
X, y = weekends[features], weekends["hike"]

tree = DecisionTreeClassifier(random_state=0)
tree.fit(X, y)
print(export_text(tree, feature_names=features))
|--- temp_c <= 13.50
|   |--- class: 0
|--- temp_c >  13.50
|   |--- wind_kmh <= 22.50
|   |   |--- rain_mm <= 4.00
|   |   |   |--- class: 1
|   |   |--- rain_mm >  4.00
|   |   |   |--- class: 0
|   |--- wind_kmh >  22.50
|   |   |--- class: 0

Each line is one question. The tree discovered thresholds for wind, temperature and rain by itself — and it found that friends doesn't help to decide, so that feature is never used.

Drawing the tree

plot_tree draws the same structure as a picture. Every box shows the question, the gini impurity, how many samples reach it and how they split between the classes:

python · try it yourself
import io
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, plot_tree

csv = """temp_c,rain_mm,wind_kmh,friends,hike
18,0,10,1,1
22,0,5,0,1
9,4,20,1,0
14,1,15,1,1
25,0,30,0,0
6,0,10,1,0
16,6,12,1,0
20,0,8,1,1
11,0,25,0,0
19,2,10,0,1
24,0,12,1,1
13,8,18,0,0
17,0,35,1,0
21,1,9,0,1
8,0,6,1,0
15,0,11,0,1"""
weekends = pd.read_csv(io.StringIO(csv))
features = ["temp_c", "rain_mm", "wind_kmh", "friends"]
tree = DecisionTreeClassifier(random_state=0).fit(weekends[features], weekends["hike"])

plt.figure(figsize=(9, 5))
plot_tree(tree, feature_names=features, class_names=["stay", "hike"], filled=True)
plt.show()
print("depth:", tree.get_depth(), " leaves:", tree.get_n_leaves())
depth: 3  leaves: 4

How the tree picks a question: Gini impurity

At every step the tree tries many candidate questions and keeps the one that produces the "purest" groups. Gini impurity measures how mixed a group is:

text
gini = 1 - (share of class 0)² - (share of class 1)²

A group with only one class has gini 0 (pure). A 50/50 mix has gini 0.5 (as mixed as two classes can be). Let's score the tree's first question, temp_c <= 13.5:

python · try it yourself
def gini(counts):
    total = sum(counts)
    return 1 - sum((c / total) ** 2 for c in counts)

print("all 16 weekends (8 stay, 8 hike):", round(gini([8, 8]), 3))
print("temp <= 13.5   (5 stay, 0 hike):", round(gini([5, 0]), 3))
print("temp >  13.5   (3 stay, 8 hike):", round(gini([3, 8]), 3))
all 16 weekends (8 stay, 8 hike): 0.5
temp <= 13.5   (5 stay, 0 hike): 0.0
temp >  13.5   (3 stay, 8 hike): 0.397

The cold weekends form a perfectly pure group, and the warm group is far less mixed than the original 50/50. The tree chooses the split whose two child groups have the lowest weighted gini. It then repeats the process inside each child until the groups are pure or a limit (like max_depth) is reached.

Making predictions

python · try it yourself
import io
import pandas as pd
from sklearn.tree import DecisionTreeClassifier

csv = """temp_c,rain_mm,wind_kmh,friends,hike
18,0,10,1,1
22,0,5,0,1
9,4,20,1,0
14,1,15,1,1
25,0,30,0,0
6,0,10,1,0
16,6,12,1,0
20,0,8,1,1
11,0,25,0,0
19,2,10,0,1
24,0,12,1,1
13,8,18,0,0
17,0,35,1,0
21,1,9,0,1
8,0,6,1,0
15,0,11,0,1"""
weekends = pd.read_csv(io.StringIO(csv))
features = ["temp_c", "rain_mm", "wind_kmh", "friends"]
tree = DecisionTreeClassifier(random_state=0).fit(weekends[features], weekends["hike"])

forecast = pd.DataFrame({
    "temp_c":   [19, 23, 17],
    "rain_mm":  [0, 0, 7],
    "wind_kmh": [8, 40, 10],
    "friends":  [1, 0, 1],
})
forecast["prediction"] = tree.predict(forecast[features])
print(forecast)
   temp_c  rain_mm  wind_kmh  friends  prediction
0      19        0         8        1           1
1      23        0        40        0           0
2      17        7        10        1           0

Note: A tree grown until every leaf is pure fits its training data perfectly — and often overfits. Limit its growth with max_depth, min_samples_leaf or min_samples_split, and measure accuracy on a test set. Combining many trees (the Bootstrap Aggregation and Random Forests lessons) is another strong fix.

Go further: Decision Trees: Splits, Gini and Entropy compares the impurity measures and the hyperparameters, and A Decision Tree from Scratch builds the CART algorithm in NumPy.

Test yourself

What is the Gini impurity of a group that contains only one class?

  1. 0
  2. 0.5
  3. 1
  4. It depends on the size

Which function prints a fitted tree's rules as indented text?

  1. plot_tree
  2. export_text
  3. tree.rules()
  4. print_tree

Which parameter limits how many levels of questions a decision tree may ask?

  1. n_estimators
  2. max_depth
  3. random_state
  4. criterion