{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "58a4d12e",
   "metadata": {},
   "source": [
    "# 🌳 Decision trees in Python\n",
    "\n",
    "In the chapter [Decision Trees](https://ai.kuleuven.be/aivooriedereen/en/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](https://scikit-learn.org), the standard library for machine learning in Python.\n",
    "\n",
    "You will:\n",
    "\n",
    "1. 🍹 grow the tree of the cocktails from the chapter and read its questions;\n",
    "2. 🏭 predict which runs of a milling machine end in a failure, with one tree and with a random forest;\n",
    "3. 🔧 give the tree a few features from physics, and see it find the failure rules of the machine.\n",
    "\n",
    "Each time, you look at what the model learned: the questions of a tree, and the features a forest relies on most.\n",
    "\n",
    "**Prior knowledge**: the chapter [Decision Trees](https://ai.kuleuven.be/aivooriedereen/en/decision-trees). You don't need any programming experience: you can run the whole notebook without changing a single line.\n",
    "\n",
    "**Estimated time**: about 30 minutes.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/decision-trees](https://ai.kuleuven.be/aivooriedereen/en/notebook/decision-trees), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1InJ2fpet1_8I3WYRBrZaITYgwasoit8F?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a232e89e",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "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.\n",
    "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.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/decision-trees.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks), with scikit-learn, pandas and matplotlib installed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f06ec206",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, loops and functions. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `pd.DataFrame({\"color\": [...], ...})` | A **pandas DataFrame**: a table with named columns, like a spreadsheet. `table[\"color\"]` is one column. |\n",
    "| `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. |\n",
    "| `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. |\n",
    "| `forest.feature_importances_` | What the model learned. scikit-learn ends such names with an underscore: they only exist after `fit`. |\n",
    "| `(predicted == 1) & (y_test == 1)` | Compares two columns row by row: `True` where both tests hold. `.sum()` counts the `True`s. |\n",
    "| `HTML(table.to_html())` | Shows a table neatly below the cell. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96e39af6",
   "metadata": {},
   "source": [
    "## 🍹 The cocktails\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "1621064f",
   "metadata": {},
   "source": [
    "import pandas as pd\n",
    "from IPython.display import HTML\n",
    "\n",
    "cocktails = pd.DataFrame({\n",
    "    \"glass\": [\"cylinder\", \"cylinder\", \"cone\", \"trapezoid\", \"cone\", \"trapezoid\", \"cone\", \"cone\"],\n",
    "    \"color\": [\"orange\", \"black\", \"white\", \"green\", \"yellow\", \"orange\", \"orange\", \"orange\"],\n",
    "    \"stirrer\": [False, False, False, True, False, True, False, False],\n",
    "    \"lemon\": [False, True, False, False, True, False, False, True],\n",
    "    \"volume\": [\"25 cl\", \"25 cl\", \"10 cl\", \"15 cl\", \"15 cl\", \"15 cl\", \"15 cl\", \"10 cl\"],\n",
    "    \"nauseous\": [\"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\"],\n",
    "})\n",
    "HTML(cocktails.to_html())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "d531ba4c",
   "metadata": {},
   "source": [
    "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?\".\n",
    "\n",
    "`DecisionTreeClassifier` is the decision tree of scikit-learn. With `criterion=\"entropy\"`, it picks every question with the information gain from the chapter."
   ]
  },
  {
   "cell_type": "code",
   "id": "00ce4cf3",
   "metadata": {},
   "source": [
    "from sklearn.tree import DecisionTreeClassifier, export_text\n",
    "\n",
    "X = pd.get_dummies(cocktails.drop(columns=\"nauseous\"))  # the features, as zeros and ones\n",
    "y = cocktails[\"nauseous\"]                               # the labels\n",
    "\n",
    "cocktail_tree = DecisionTreeClassifier(criterion=\"entropy\")\n",
    "cocktail_tree.fit(X, y)\n",
    "print(export_text(cocktail_tree, feature_names=list(X.columns)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "029e77a0",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "`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."
   ]
  },
  {
   "cell_type": "code",
   "id": "1dc16ab9",
   "metadata": {},
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.tree import plot_tree\n",
    "\n",
    "plt.figure(figsize=(8, 5))\n",
    "plot_tree(cocktail_tree, feature_names=list(X.columns), class_names=list(cocktail_tree.classes_), filled=True, fontsize=10)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0094d408",
   "metadata": {},
   "source": [
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "id": "25eeacdd",
   "metadata": {},
   "source": [
    "new_cocktail = pd.DataFrame({\"glass\": [\"cone\"], \"color\": [\"orange\"], \"stirrer\": [True], \"lemon\": [False], \"volume\": [\"15 cl\"]})\n",
    "new_X = pd.get_dummies(new_cocktail).reindex(columns=X.columns, fill_value=0)  # the same columns as the training data\n",
    "print(\"Nauseous?\", cocktail_tree.predict(new_X)[0])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "b5723dea",
   "metadata": {},
   "source": [
    "## 🏭 Machines that fail\n",
    "\n",
    "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?\n",
    "\n",
    "*The data is the [AI4I 2020 Predictive Maintenance Dataset](https://archive.ics.uci.edu/dataset/601/ai4i+2020+predictive+maintenance+dataset) by Stephan Matzka (UCI Machine Learning Repository, CC BY 4.0): synthetic data that mimics a real machine.*"
   ]
  },
  {
   "cell_type": "code",
   "id": "36497d51",
   "metadata": {},
   "source": [
    "DATA_URL = \"https://ai.kuleuven.be/aivooriedereen/notebooks/data/\"\n",
    "machines = pd.read_csv(DATA_URL + \"ai4i2020.csv\")\n",
    "print(len(machines), \"runs, of which\", machines[\"Machine failure\"].sum(), \"end in a failure\")\n",
    "HTML(machines.head().to_html())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8c13e75d",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "637b05b8",
   "metadata": {},
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "features = [\"Air temperature [K]\", \"Process temperature [K]\", \"Rotational speed [rpm]\", \"Torque [Nm]\", \"Tool wear [min]\"]\n",
    "X = machines[features].copy()\n",
    "X[\"Type\"] = machines[\"Type\"].map({\"L\": 0, \"M\": 1, \"H\": 2})  # the quality type as a number\n",
    "y = machines[\"Machine failure\"]  # 1 = failure\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)\n",
    "print(len(X_test), \"test runs, of which\", y_test.sum(), \"with a failure\")\n",
    "\n",
    "\n",
    "def evaluate(model, X_test):\n",
    "    predicted = model.predict(X_test)\n",
    "    caught = ((predicted == 1) & (y_test == 1)).sum()\n",
    "    false_alarms = ((predicted == 1) & (y_test == 0)).sum()\n",
    "    print(f\"Correct predictions: {(predicted == y_test).mean():.1%}\")\n",
    "    print(f\"Failures caught: {caught} of {y_test.sum()}\")\n",
    "    print(f\"False alarms: {false_alarms}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "bc202fdb",
   "metadata": {},
   "source": [
    "### 🌳 One tree\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "2c757312",
   "metadata": {},
   "source": [
    "tree = DecisionTreeClassifier(max_depth=3, random_state=0)\n",
    "tree.fit(X_train, y_train)\n",
    "evaluate(tree, X_test)\n",
    "print()\n",
    "print(export_text(tree, feature_names=list(X.columns)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "9c715da6",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "**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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bdaa57b",
   "metadata": {},
   "source": [
    "### 🌲 A random forest\n",
    "\n",
    "A random forest from the chapter: 200 trees, each on its own bootstrap sample, with drawn features at every node."
   ]
  },
  {
   "cell_type": "code",
   "id": "2097b0dc",
   "metadata": {},
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "forest = RandomForestClassifier(n_estimators=200, random_state=0)\n",
    "forest.fit(X_train, y_train)\n",
    "evaluate(forest, X_test)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c79c7515",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "609cc967",
   "metadata": {},
   "source": [
    "def show_importance(model, columns):\n",
    "    importance = pd.Series(model.feature_importances_, index=columns).sort_values()\n",
    "    importance.plot.barh(color=\"#16a34a\", figsize=(6, 0.45 * len(columns) + 0.8))\n",
    "    plt.xlabel(\"feature importance\")\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "show_importance(forest, X.columns)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "849d0229",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0abbb496",
   "metadata": {},
   "source": [
    "## 🔧 Features from physics\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "2b1fa5d6",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "\n",
    "X_physics = X.copy()\n",
    "X_physics[\"Power [W]\"] = machines[\"Torque [Nm]\"] * machines[\"Rotational speed [rpm]\"] * 2 * np.pi / 60\n",
    "X_physics[\"Temperature difference [K]\"] = machines[\"Process temperature [K]\"] - machines[\"Air temperature [K]\"]\n",
    "X_physics[\"Strain [min Nm]\"] = machines[\"Tool wear [min]\"] * machines[\"Torque [Nm]\"]\n",
    "Xp_train, Xp_test = X_physics.loc[X_train.index], X_physics.loc[X_test.index]  # the same runs as before\n",
    "\n",
    "physics_tree = DecisionTreeClassifier(max_depth=3, random_state=0)\n",
    "physics_tree.fit(Xp_train, y_train)\n",
    "evaluate(physics_tree, Xp_test)\n",
    "print()\n",
    "print(export_text(physics_tree, feature_names=list(X_physics.columns)))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "78622d85",
   "metadata": {},
   "source": [
    "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](https://archive.ics.uci.edu/dataset/601/ai4i+2020+predictive+maintenance+dataset)). A tree you can read does more than predict: it shows you how the machine behaves.\n",
    "\n",
    "The forest benefits too:"
   ]
  },
  {
   "cell_type": "code",
   "id": "1a64f99e",
   "metadata": {},
   "source": [
    "physics_forest = RandomForestClassifier(n_estimators=200, random_state=0)\n",
    "physics_forest.fit(Xp_train, y_train)\n",
    "evaluate(physics_forest, Xp_test)\n",
    "show_importance(physics_forest, X_physics.columns)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0d353fa7",
   "metadata": {},
   "source": [
    "The forest now catches about four out of five failures, and the strain and the power top its feature importance.\n",
    "\n",
    "**Try it yourself**\n",
    "\n",
    "- 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.\n",
    "- Leave out one of the three new features and run the cells again from 🔧 Features from physics. Which failures does the tree miss now?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83f9b3fa",
   "metadata": {},
   "source": [
    "## 🧰 Trees for your own problem\n",
    "\n",
    "Both problems followed the same recipe:\n",
    "\n",
    "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`.\n",
    "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`.\n",
    "3. Read what it learned: `export_text` or `plot_tree` for one tree, `feature_importances_` for a forest.\n",
    "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.\n",
    "\n",
    "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`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0a9bd20",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/decision-trees](https://ai.kuleuven.be/aivooriedereen/en/notebook/decision-trees).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "beslissingsbomen"
   ],
   "language": "en",
   "title": "Decision trees in Python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
