AI voor Iedereen

Search

Search chapters and demos

🌳 Decision trees in Python

The cocktails from the chapter and a milling machine that sometimes fails: read the questions of a tree, compare a random forest with one tree, look at the feature importance, and let a tree find the failure rules of the machine.

Run in Google Colab

Colab requires a Google account, but you can also .

Reading mode. Below is the whole notebook, with the output of the code included. So you can simply read all of it here. To change the code and see what happens, you can go to Google Colab (external link).

In the chapter Decision Trees, a tree asked one yes/no question after another, and a forest of trees voted. This notebook shows what that looks like in code, with scikit-learn (external link), the standard library for machine learning in Python.

You will:

  1. 🍹 grow the tree of the cocktails from the chapter and read its questions;
  2. 🏭 predict which runs of a milling machine end in a failure, with one tree and with a random forest;
  3. 🔧 give the tree a few features from physics, and see it find the failure rules of the machine.

Each time, you look at what the model learned: the questions of a tree, and the features a forest relies on most.

Prior knowledge: the chapter Decision Trees. You don't need any programming experience: you can run the whole notebook without changing a single line.

Estimated time: about 30 minutes.

This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/decision-trees, and you can open it directly in Google Colab (external link).

🚀 First time in a notebook?

Then the short introductory notebook explains everything step by step. The most important things:

  1. Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
  2. Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
  3. Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.

Prefer not to use Google? Download the notebook file and open it in Jupyter (external link) or Visual Studio Code (external link), with scikit-learn, pandas and matplotlib installed.

🐍 Python in this notebook

New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:

CodeMeaning
pd.DataFrame({"color": [...], ...})A pandas DataFrame: a table with named columns, like a spreadsheet. table["color"] is one column.
pd.get_dummies(table)Turns every category into its own column of zeros and ones: color_orange is 1 for an orange cocktail and 0 for the others.
tree.fit(X, y)Trains the model on the examples in X (one row per example, one column per feature) and their labels in y. Every model in scikit-learn has this fit, and a predict that classifies new examples.
forest.feature_importances_What the model learned. scikit-learn ends such names with an underscore: they only exist after fit.
(predicted == 1) & (y_test == 1)Compares two columns row by row: True where both tests hold. .sum() counts the Trues.
HTML(table.to_html())Shows a table neatly below the cell.

🍹 The cocktails

These are the eight cocktails from the chapter, with what you see (the glass, the color, a stirrer, a slice of lemon, the volume) and whether they made you nauseous.

import pandas as pd
from IPython.display import HTML

cocktails = pd.DataFrame({
    "glass": ["cylinder", "cylinder", "cone", "trapezoid", "cone", "trapezoid", "cone", "cone"],
    "color": ["orange", "black", "white", "green", "yellow", "orange", "orange", "orange"],
    "stirrer": [False, False, False, True, False, True, False, False],
    "lemon": [False, True, False, False, True, False, False, True],
    "volume": ["25 cl", "25 cl", "10 cl", "15 cl", "15 cl", "15 cl", "15 cl", "10 cl"],
    "nauseous": ["no", "no", "no", "no", "no", "yes", "yes", "yes"],
})
HTML(cocktails.to_html())
Output
glass color stirrer lemon volume nauseous
0 cylinder orange False False 25 cl no
1 cylinder black False True 25 cl no
2 cone white False False 10 cl no
3 trapezoid green True False 15 cl no
4 cone yellow False True 15 cl no
5 trapezoid orange True False 15 cl yes
6 cone orange False False 15 cl yes
7 cone orange False True 10 cl yes

A tree in scikit-learn only asks questions about numbers, such as "is this number at most 0.5?". So first, get_dummies turns every category into a column of zeros and ones. The question "is the cocktail orange?" from the chapter then becomes "is color_orange larger than 0.5?".

DecisionTreeClassifier is the decision tree of scikit-learn. With criterion="entropy", it picks every question with the information gain from the chapter.

from sklearn.tree import DecisionTreeClassifier, export_text

X = pd.get_dummies(cocktails.drop(columns="nauseous"))  # the features, as zeros and ones
y = cocktails["nauseous"]                               # the labels

cocktail_tree = DecisionTreeClassifier(criterion="entropy")
cocktail_tree.fit(X, y)
print(export_text(cocktail_tree, feature_names=list(X.columns)))
Output
|--- color_orange <= 0.50
|   |--- class: no
|--- color_orange >  0.50
|   |--- glass_cylinder <= 0.50
|   |   |--- class: yes
|   |--- glass_cylinder >  0.50
|   |   |--- class: no

export_text writes the tree as indented lines: every line is a question, and class: is a leaf. Read color_orange > 0.50 as "the cocktail is orange", and glass_cylinder <= 0.50 as "the glass is not a cylinder". The tree first asks about the color and then about the glass: the two questions of the chapter. The stirrer, the lemon and the volume don't appear, because the tree doesn't need them.

plot_tree draws the same tree. Each box shows the question, the entropy, the number of cocktails, and how many of each label (value = [no, yes]). Left of a question is its True branch, right its False branch.

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

plt.figure(figsize=(8, 5))
plot_tree(cocktail_tree, feature_names=list(X.columns), class_names=list(cocktail_tree.classes_), filled=True, fontsize=10)
plt.show()
Output

Try it yourself: the cell below asks the tree about a new cocktail: an orange one in a cone glass, with a stirrer. Change the glass to "cylinder", or the color, and run it again.

new_cocktail = pd.DataFrame({"glass": ["cone"], "color": ["orange"], "stirrer": [True], "lemon": [False], "volume": ["15 cl"]})
new_X = pd.get_dummies(new_cocktail).reindex(columns=X.columns, fill_value=0)  # the same columns as the training data
print("Nauseous?", cocktail_tree.predict(new_X)[0])
Output
Nauseous? yes

🏭 Machines that fail

A milling machine logs every run: the air temperature, the temperature of the process, the rotational speed, the torque, how long the tool has been in use, and the quality type of the product (L, M or H for low, medium and high). Now and then, a run ends in a failure. Can a tree see that coming from the measurements?

The data is the AI4I 2020 Predictive Maintenance Dataset (external link) by Stephan Matzka (UCI Machine Learning Repository, CC BY 4.0): synthetic data that mimics a real machine.

DATA_URL = "https://ai.kuleuven.be/aivooriedereen/notebooks/data/"
machines = pd.read_csv(DATA_URL + "ai4i2020.csv")
print(len(machines), "runs, of which", machines["Machine failure"].sum(), "end in a failure")
HTML(machines.head().to_html())
Output
10000 runs, of which 339 end in a failure
UDI Product ID Type Air temperature [K] Process temperature [K] Rotational speed [rpm] Torque [Nm] Tool wear [min] Machine failure TWF HDF PWF OSF RNF
0 1 M14860 M 298.1 308.6 1551 42.8 0 0 0 0 0 0 0
1 2 L47181 L 298.2 308.7 1408 46.3 3 0 0 0 0 0 0
2 3 L47182 L 298.1 308.5 1498 49.4 5 0 0 0 0 0 0
3 4 L47183 L 298.2 308.6 1433 39.5 7 0 0 0 0 0 0
4 5 L47184 L 298.2 308.7 1408 40.0 9 0 0 0 0 0 0

Only 339 of the 10,000 runs end in a failure: 3.4%. A "model" that always says "no failure" is therefore right 96.6% of the time, and catches nothing. So the percentage of correct predictions says little here. Below, you also count how many failures a model catches, and how many false alarms it raises.

A quarter of the runs stays aside as a test: runs the models never see during training. stratify=y makes sure the test set also has 3.4% failures.

from sklearn.model_selection import train_test_split

features = ["Air temperature [K]", "Process temperature [K]", "Rotational speed [rpm]", "Torque [Nm]", "Tool wear [min]"]
X = machines[features].copy()
X["Type"] = machines["Type"].map({"L": 0, "M": 1, "H": 2})  # the quality type as a number
y = machines["Machine failure"]  # 1 = failure

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
print(len(X_test), "test runs, of which", y_test.sum(), "with a failure")


def evaluate(model, X_test):
    predicted = model.predict(X_test)
    caught = ((predicted == 1) & (y_test == 1)).sum()
    false_alarms = ((predicted == 1) & (y_test == 0)).sum()
    print(f"Correct predictions: {(predicted == y_test).mean():.1%}")
    print(f"Failures caught: {caught} of {y_test.sum()}")
    print(f"False alarms: {false_alarms}")
Output
2500 test runs, of which 85 with a failure

🌳 One tree

Start with a small tree, with at most three questions from the root to a leaf (max_depth=3), so that you can still read it.

tree = DecisionTreeClassifier(max_depth=3, random_state=0)
tree.fit(X_train, y_train)
evaluate(tree, X_test)
print()
print(export_text(tree, feature_names=list(X.columns)))
Output
Correct predictions: 97.0%
Failures caught: 15 of 85
False alarms: 6

|--- Torque [Nm] <= 63.55
|   |--- Torque [Nm] <= 13.15
|   |   |--- Type <= 1.50
|   |   |   |--- class: 1
|   |   |--- Type >  1.50
|   |   |   |--- class: 0
|   |--- Torque [Nm] >  13.15
|   |   |--- Rotational speed [rpm] <= 1380.50
|   |   |   |--- class: 0
|   |   |--- Rotational speed [rpm] >  1380.50
|   |   |   |--- class: 0
|--- Torque [Nm] >  63.55
|   |--- Rotational speed [rpm] <= 1292.00
|   |   |--- Tool wear [min] <= 160.50
|   |   |   |--- class: 0
|   |   |--- Tool wear [min] >  160.50
|   |   |   |--- class: 1
|   |--- Rotational speed [rpm] >  1292.00
|   |   |--- Torque [Nm] <= 64.65
|   |   |   |--- class: 1
|   |   |--- Torque [Nm] >  64.65
|   |   |   |--- class: 1

The tree is right for about 97% of the test runs, hardly better than always saying "no failure", and it catches only a handful of the failures. Its questions do make sense: they are about the torque, the speed and the tool wear, and a very high torque, especially at a low speed with a worn tool, means trouble.

Try it yourself: set max_depth to 5, or to None (no limit), and run the cell again. Without a limit, the tree learns every training run by heart: it catches more failures, but it also raises many more false alarms, and it is far too big to read.

🌲 A random forest

A random forest from the chapter: 200 trees, each on its own bootstrap sample, with drawn features at every node.

from sklearn.ensemble import RandomForestClassifier

forest = RandomForestClassifier(n_estimators=200, random_state=0)
forest.fit(X_train, y_train)
evaluate(forest, X_test)
Output
Correct predictions: 98.5%
Failures caught: 55 of 85
False alarms: 7

The forest catches about two thirds of the failures, with only a few false alarms. You can't read 200 trees, but the forest does tell you which features it relies on: the feature importance from the chapter, which adds up over all trees how much each feature reduced the uncertainty.

def show_importance(model, columns):
    importance = pd.Series(model.feature_importances_, index=columns).sort_values()
    importance.plot.barh(color="#16a34a", figsize=(6, 0.45 * len(columns) + 0.8))
    plt.xlabel("feature importance")
    plt.show()


show_importance(forest, X.columns)
Output

The torque, the rotational speed and the tool wear matter most; the quality type hardly matters. Even without reading a single tree, that tells whoever maintains the machine where to look.

🔧 Features from physics

The machine doesn't fail on one measurement, but on combinations: the power it delivers (torque × rotational speed), how well it gets rid of its heat (the difference between the process and the air temperature), and the strain on the tool (tool wear × torque). A tree only asks about one feature at a time, so it can only find such combinations with many questions. Give it those three as extra columns.

import numpy as np

X_physics = X.copy()
X_physics["Power [W]"] = machines["Torque [Nm]"] * machines["Rotational speed [rpm]"] * 2 * np.pi / 60
X_physics["Temperature difference [K]"] = machines["Process temperature [K]"] - machines["Air temperature [K]"]
X_physics["Strain [min Nm]"] = machines["Tool wear [min]"] * machines["Torque [Nm]"]
Xp_train, Xp_test = X_physics.loc[X_train.index], X_physics.loc[X_test.index]  # the same runs as before

physics_tree = DecisionTreeClassifier(max_depth=3, random_state=0)
physics_tree.fit(Xp_train, y_train)
evaluate(physics_tree, Xp_test)
print()
print(export_text(physics_tree, feature_names=list(X_physics.columns)))
Output
Correct predictions: 98.5%
Failures caught: 47 of 85
False alarms: 0

|--- Strain [min Nm] <= 10998.50
|   |--- Power [W] <= 9000.17
|   |   |--- Power [W] <= 3495.94
|   |   |   |--- class: 1
|   |   |--- Power [W] >  3495.94
|   |   |   |--- class: 0
|   |--- Power [W] >  9000.17
|   |   |--- class: 1
|--- Strain [min Nm] >  10998.50
|   |--- Type <= 0.50
|   |   |--- class: 1
|   |--- Type >  0.50
|   |   |--- Strain [min Nm] <= 12128.50
|   |   |   |--- class: 0
|   |   |--- Strain [min Nm] >  12128.50
|   |   |   |--- class: 1

With the same three questions per path, the tree now catches more than half of the failures, without a single false alarm. And its questions read like the specifications of the machine: a failure when the power drops below about 3,500 W or rises above 9,000 W, or when the strain on the tool passes about 11,000 min·Nm (a little more for the better quality types). Those are exactly the rules the makers of this synthetic dataset used to decide when the machine fails (see the description of the dataset (external link)). A tree you can read does more than predict: it shows you how the machine behaves.

The forest benefits too:

physics_forest = RandomForestClassifier(n_estimators=200, random_state=0)
physics_forest.fit(Xp_train, y_train)
evaluate(physics_forest, Xp_test)
show_importance(physics_forest, X_physics.columns)
Output
Correct predictions: 99.3%
Failures caught: 69 of 85
False alarms: 2

The forest now catches about four out of five failures, and the strain and the power top its feature importance.

Try it yourself

  • Set max_depth=5 for the physics tree. It then also finds the rule for overheating: a failure when the temperature difference stays below about 8.6 K at a speed below about 1,380 rpm.
  • Leave out one of the three new features and run the cells again from 🔧 Features from physics. Which failures does the tree miss now?

🧰 Trees for your own problem

Both problems followed the same recipe:

  1. Put your examples in a table X, one row per example and one column per feature, and their labels in y. Turn categories into numbers, with pd.get_dummies or a map.
  2. Train a DecisionTreeClassifier (with a max_depth) when you want to read the model, or a RandomForestClassifier when you want the best predictions. Both have fit and predict.
  3. Read what it learned: export_text or plot_tree for one tree, feature_importances_ for a forest.
  4. Test on data the model didn't see, and count the mistakes that matter for your problem (here: missed failures and false alarms), not only the percentage of correct predictions.

To predict a number instead of a class, use DecisionTreeRegressor and RandomForestRegressor in the same way. Gradient boosting, in which every new tree corrects the mistakes of the previous ones, is HistGradientBoostingClassifier, again with fit and predict.


By Thomas Winters (external link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/decision-trees.