{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 29: Decision Trees\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 15, Tuesday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. A cell that draws a chart shows it under the cell when you run it. The practice problems are in a separate notebook, topic-29-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 7 to 10 are one project, so start at the first cell of Part 7. The solved problems 5 to 16 are a second project that starts again from reading the file.\n",
    "\n",
    "This notebook reads the file Bank Customer Churn Prediction.csv. Put the file into the same folder as the notebook. On the Asiman Data School website the file is already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. What a decision tree is\n",
    "2. How a tree makes a decision\n",
    "3. How a tree chooses its questions\n",
    "4. Regression trees\n",
    "5. Overfitting and the hyperparameters\n",
    "6. Preprocessing for trees, and for the models still to come\n",
    "7. The project: from the file to the data for the tree\n",
    "8. The first tree\n",
    "9. A tree you can read, and a tree that works\n",
    "10. Tuning the tree\n",
    "11. The workflow, step by step\n",
    "12. Common mistakes\n",
    "13. Solved problems\n",
    "14. Practice (in topic-29-practice.ipynb)\n",
    "15. Check yourself (on the website)\n",
    "16. Summary"
   ],
   "id": "t29-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: a model made of questions\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, a decision tree predicts with a row of yes-or-no questions, from the root to a leaf, and a leaf answers with the most common class of its training rows. Second, the tree chooses each question so that the groups become as pure as possible: it measures the mix of the classes with the Gini impurity (or the entropy) and takes the split with the lowest weighted impurity. Third, a tree without limits learns the training data by heart, so it is limited with `max_depth`, `min_samples_leaf` or `ccp_alpha`, chosen with cross-validation. Fourth, a tree needs no scaling and does not mind outliers, but text must still be encoded. Fifth, a tree explains itself: its rules and its feature importances.\n",
    "\n",
    "Regression trees, entropy and the other hyperparameters are told around these five ideas.\n",
    "\n",
    "The ninth lesson of Module 3. Every model so far calculated a weighted sum of the features: linear regression, Ridge and Lasso, logistic regression. A decision tree works in a completely different way. It asks a row of simple yes-or-no questions about a customer (\"Is the customer older than 44?\", \"Is he an active member?\") and gives the answer that was most common among similar customers in the training data. It is the model that is easiest to explain to a person who has never heard of machine learning, and it is the building block of the strongest models of this module: random forests (Topic 30) and boosting (Topics 37 to 40).\n",
    "\n",
    "The lesson has two halves. The first is done on paper: what a tree is and where it is used, how it makes a decision, how it chooses its first question and every question after it (Gini impurity and entropy), regression trees, the hyperparameters, and what scaling, encoding, outliers and missing values mean for trees and for the models still to come. The second half is the project on `Bank Customer Churn Prediction.csv`, the file of Topics 27 and 28: every step from reading the file to a tuned tree and its measures, explained once more as a real workflow.\n",
    "\n",
    "You need: the workflow of a project (Topics 21 and 27), the train/test split and cross-validation (Topic 23), overfitting and underfitting (Topic 23), encoding (Topic 25), `predict_proba` and the threshold (Topic 27), and the measures of a classifier (Topic 28).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| Decision tree | a model that predicts by asking a row of yes-or-no questions about the features |\n",
    "| Node | one question of the tree, or one end of it |\n",
    "| Root node | the first question, at the top; all training rows start there |\n",
    "| Branch | the way from a question to the next node: \"yes\" or \"no\" |\n",
    "| Internal node | a node with a question, between the root and the leaves |\n",
    "| Leaf | a node without a question: here the tree gives its answer |\n",
    "| Depth | the number of questions on the longest way from the root to a leaf |\n",
    "| Split | dividing the rows of a node into two groups with one question |\n",
    "| Impurity | how mixed the classes in a node are: 0 when all rows have the same class |\n",
    "| Gini impurity | an impurity measure: the chance that two rows drawn at random from the node have different classes |\n",
    "| Entropy | another impurity measure, from information theory |\n",
    "| Information gain | how much a split lowers the impurity |\n",
    "| Pruning | limiting or cutting back a tree so that it does not learn the noise |\n",
    "| Feature importance | how much a feature lowered the impurity, summed over all its splits |\n",
    "\n",
    "## 1. What a decision tree is\n",
    "\n",
    "### 1.1 A row of questions\n",
    "\n",
    "Think of the game \"twenty questions\": one person thinks of an animal, the other may only ask yes-or-no questions. A good player does not start with \"Is it a cat?\". He asks a question that cuts the possibilities roughly in half: \"Does it live in water?\". Each answer leads to the next question, until the answer is clear.\n",
    "\n",
    "A decision tree plays this game with data. For a bank customer it might ask:\n",
    "\n",
    "- Is the customer older than 44?\n",
    "- If yes: is he an active member?\n",
    "- If no: does he have more than 2 products?\n",
    "\n",
    "and at the end it says \"leaves\" or \"stays\". The questions are not written by a person: the tree learns them from the training data, and it learns which question to ask first.\n",
    "\n",
    "### 1.2 The parts of a tree\n",
    "\n",
    "The picture of a tree with its parts is on the lesson page: the root node \"age > 44?\" at the top, two internal nodes (\"more than 2 products?\" and \"active member?\") and four leaves at depth 2.\n",
    "\n",
    "- The root node holds the first question. All training rows start there.\n",
    "- An internal node holds a later question. It receives only the rows that took its branch.\n",
    "- A leaf holds no question. It holds the answer: the class that was most common among the training rows that ended there.\n",
    "- The depth of this tree is 2: every way from the root to a leaf passes two questions.\n",
    "\n",
    "The tree is drawn upside down, with the root at the top. That is the custom in machine learning.\n",
    "\n",
    "### 1.3 Classification and regression\n",
    "\n",
    "Decision trees solve both kinds of supervised tasks (Topic 21):\n",
    "\n",
    "|  | Classification tree | Regression tree |\n",
    "| --- | --- | --- |\n",
    "| The target | a class: leaves or stays, spam or not | a number: a price, a balance, a mark |\n",
    "| A leaf answers with | the most common class of its rows (and their shares as probabilities) | the mean of the target of its rows |\n",
    "| A split is chosen by | the impurity of the classes (Gini, entropy) | the squared error |\n",
    "| scikit-learn | `DecisionTreeClassifier` | `DecisionTreeRegressor` |\n",
    "\n",
    "This lesson works mainly with classification, on the bank data. Part 4 shows the regression tree on a small example.\n",
    "\n",
    "### 1.4 Where trees are used\n",
    "\n",
    "- Banking and credit: who will not pay back a loan, which customer is about to leave, which payment looks like fraud. A bank must often explain a decision to its customer or its supervisor, and the rules of a tree can be read aloud.\n",
    "- Medicine: rules for triage (\"breathing rate above 30? blood pressure below 90?\"), the risk of a disease from a few measurements.\n",
    "- Business: which customers answer an offer, which product a customer buys next.\n",
    "- Industry: which part of a machine will fail, from its sensor values.\n",
    "- As a building block: one tree alone is a good but rarely the best model. Hundreds of trees together are among the strongest models for tables of data: random forests (Topic 30) and gradient boosting (Topics 37 to 40). Whatever you learn about one tree today, you will use there.\n",
    "\n",
    "### 1.5 Strengths and weaknesses\n",
    "\n",
    "| Strengths | Weaknesses |\n",
    "| --- | --- |\n",
    "| Easy to explain: every prediction is a short row of rules | A single tree overfits easily: it can learn the training rows by heart |\n",
    "| No scaling needed (Part 6) | Unstable: a few different training rows can give a quite different tree |\n",
    "| Handles numbers and categories, and effects that are not in order | Its borders are always straight steps; smooth relationships need many steps |\n",
    "| Finds interactions by itself (\"old and not active\") | It is greedy: it takes the best question now, not the best tree overall |\n",
    "| Fast to train and to predict | Its probabilities are coarse: the shares of a few leaves |\n",
    "\n",
    "## 2. How a tree makes a decision\n",
    "\n",
    "### 2.1 Following the path\n",
    "\n",
    "A trained tree predicts for a new row by walking from the root to a leaf. Take the tree of Part 1 and a customer who is 52 years old and not an active member:\n",
    "\n",
    "1. Root: is the age above 44? 52 is above 44: yes, go right.\n",
    "2. Next question: is he an active member? No, go left.\n",
    "3. A leaf: leaves.\n",
    "\n",
    "A second customer, 30 years old with 1 product:\n",
    "\n",
    "1. Is the age above 44? No, go left.\n",
    "2. More than 2 products? No, go left.\n",
    "3. A leaf: stays.\n",
    "\n",
    "Every prediction asks only as many questions as the tree is deep. The tree never adds or multiplies the features: it only compares one feature with one number at a time.\n",
    "\n",
    "### 2.2 The probability from a leaf\n",
    "\n",
    "Every leaf remembers how many training rows of each class ended there. Suppose the leaf \"older than 44, not active\" received 400 training customers, and 260 of them left. Then for every new customer who reaches this leaf:\n",
    "\n",
    "$$\n",
    "\\text{probability of leaving} = \\frac{260}{400} = 0.65\n",
    "$$\n",
    "\n",
    "`predict_proba` returns exactly this share, and `predict` gives the class with the larger share (here \"leaves\", because 0.65 is above 0.5). All customers in the same leaf get the same probability. A tree with 8 leaves can give at most 8 different probabilities: much coarser than logistic regression, which gives every customer his own.\n",
    "\n",
    "### 2.3 The tree as a picture of the data\n",
    "\n",
    "Each question cuts the data along one feature, at one value. Two questions on two features cut the plane of these two features into rectangles, and every rectangle gets one class. A tree draws its borders only parallel to the axes: in steps, never diagonally. Logistic regression draws one straight border in any direction (Topic 27). Which is better depends on the data.\n",
    "\n",
    "## 3. How a tree chooses its questions\n",
    "\n",
    "### 3.1 The goal: pure groups\n",
    "\n",
    "A question is good when it separates the classes: after the split each group should contain mostly one class. A group with only one class is pure. The tree needs a number for \"how mixed is this group?\": an impurity measure. scikit-learn offers two for classification.\n",
    "\n",
    "### 3.2 Gini impurity\n",
    "\n",
    "For a node in which a share $p$ of the rows belongs to class 1 and $1 - p$ to class 0:\n",
    "\n",
    "$$\n",
    "\\text{Gini} = 1 - p^2 - (1 - p)^2\n",
    "$$\n",
    "\n",
    "It is the chance that two rows, drawn at random from the node, have different classes.\n",
    "\n",
    "- A pure node ($p = 0$ or $p = 1$): $\\text{Gini} = 0$.\n",
    "- The most mixed node, half and half ($p = 0.5$): $\\text{Gini} = 1 - 0.25 - 0.25 = 0.5$, the largest value for two classes.\n",
    "\n",
    "### 3.3 Entropy\n",
    "\n",
    "$$\n",
    "\\text{entropy} = -p \\log_2 p - (1 - p) \\log_2 (1 - p)\n",
    "$$\n",
    "\n",
    "It comes from information theory: the number of yes-or-no questions (bits) needed, on average, to tell the class of a row. A pure node has entropy 0, a half-and-half node has entropy 1 (one question is needed).\n",
    "\n",
    "The picture with the two curves is on the lesson page: both are 0 at the ends and highest in the middle, Gini at 0.5 and entropy at 1.\n",
    "\n",
    "Both curves have the same shape: zero at the ends, highest in the middle. They almost always choose the same questions. Gini is the default of scikit-learn because it needs no logarithm and is a little faster.\n",
    "\n",
    "### 3.4 The impurity of a split\n",
    "\n",
    "A split makes two groups. Its impurity is the mean of the two impurities, weighted by the size of the groups:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{impurity after the split} \\\\[4pt]\n",
    "&= \\frac{n_{\\text{left}}}{n} \\times \\text{impurity}_{\\text{left}} \\\\[4pt]\n",
    "&\\quad + \\frac{n_{\\text{right}}}{n} \\times \\text{impurity}_{\\text{right}}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The tree tries every possible question and takes the one with the lowest impurity after the split. With entropy, the drop of the impurity is called the information gain:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{information gain} \\\\[4pt]\n",
    "&= \\text{entropy before} - \\text{entropy after}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 3.5 A worked example: ten customers\n",
    "\n",
    "Ten customers of a bank. For each we know three yes-or-no facts and whether he left:\n",
    "\n",
    "| Customer | Over 50 | Active member | Two or more products | Left |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| A | yes | no | no | yes |\n",
    "| B | yes | no | no | yes |\n",
    "| C | yes | no | yes | yes |\n",
    "| D | yes | yes | yes | no |\n",
    "| E | no | yes | no | yes |\n",
    "| F | no | yes | no | no |\n",
    "| G | no | yes | yes | no |\n",
    "| H | no | yes | no | no |\n",
    "| I | no | no | yes | no |\n",
    "| J | no | no | no | no |\n",
    "\n",
    "4 of the 10 customers left, 6 stayed.\n",
    "\n",
    "Step 1: the impurity of the root. All ten customers are in the root, and $p = 0.4$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini(root)} &= 1 - 0.4^2 - 0.6^2 \\\\[4pt]\n",
    "&= 1 - 0.16 - 0.36 = 0.48\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Step 2: try every question. Each question splits the ten customers into two groups. For each group: count, Gini, then the weighted mean.\n",
    "\n",
    "Question \"Over 50?\": yes = A, B, C, D (3 left of 4); no = E to J (1 left of 6).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini(yes)} &= 1 - 0.75^2 - 0.25^2 \\\\[4pt]\n",
    "&= 1 - 0.5625 - 0.0625 = 0.375 \\\\[8pt]\n",
    "\\text{Gini(no)} &= 1 - \\left(\\tfrac{1}{6}\\right)^2 - \\left(\\tfrac{5}{6}\\right)^2 \\\\[4pt]\n",
    "&= 1 - 0.028 - 0.694 = 0.278 \\\\[8pt]\n",
    "\\text{after the split} &= 0.4 \\times 0.375 + 0.6 \\times 0.278 \\\\[4pt]\n",
    "&= 0.150 + 0.167 = 0.317\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Question \"Active member?\": yes = D, E, F, G, H (1 left of 5); no = A, B, C, I, J (3 left of 5).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini(yes)} &= 1 - 0.2^2 - 0.8^2 \\\\[4pt]\n",
    "&= 1 - 0.04 - 0.64 = 0.32 \\\\[8pt]\n",
    "\\text{Gini(no)} &= 1 - 0.6^2 - 0.4^2 \\\\[4pt]\n",
    "&= 1 - 0.36 - 0.16 = 0.48 \\\\[8pt]\n",
    "\\text{after the split} &= 0.5 \\times 0.32 + 0.5 \\times 0.48 \\\\[4pt]\n",
    "&= 0.16 + 0.24 = 0.40\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Question \"Two or more products?\": yes = C, D, G, I (1 left of 4); no = A, B, E, F, H, J (3 left of 6).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini(yes)} &= 1 - 0.25^2 - 0.75^2 = 0.375 \\\\[8pt]\n",
    "\\text{Gini(no)} &= 1 - 0.5^2 - 0.5^2 = 0.5 \\\\[8pt]\n",
    "\\text{after the split} &= 0.4 \\times 0.375 + 0.6 \\times 0.5 \\\\[4pt]\n",
    "&= 0.15 + 0.30 = 0.45\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Step 3: choose.\n",
    "\n",
    "| Question | Gini after the split | Drop from 0.48 |\n",
    "| --- | --- | --- |\n",
    "| Over 50? | 0.317 | 0.163 |\n",
    "| Active member? | 0.40 | 0.08 |\n",
    "| Two or more products? | 0.45 | 0.03 |\n",
    "\n",
    "\"Over 50?\" lowers the impurity most. It becomes the root node.\n",
    "\n",
    "Step 4: repeat in each group. The tree now does exactly the same inside each of the two groups, with only their rows.\n",
    "\n",
    "The group \"over 50\" (A, B, C, D: 3 left, 1 stayed). \"Active member?\" splits it into A, B, C (all left) and D (stayed): two pure groups, Gini 0 after the split. \"Two or more products?\" gives A, B (both left) and C, D (one each): Gini 0.25 after the split. So the question here is \"Active member?\", and both new nodes are pure: they become leaves, \"leaves\" and \"stays\".\n",
    "\n",
    "The group \"50 or younger\" (E to J: 1 left, 5 stayed) is nearly pure. Whichever question splits it, every new group still has more customers who stayed, so every leaf would say \"stays\". The tree can stop here: the node becomes a leaf, \"stays\".\n",
    "\n",
    "The finished tree:\n",
    "\n",
    "- Over 50? No: stays (5 of 6 stayed).\n",
    "- Over 50? Yes, active member? No: leaves (3 of 3 left).\n",
    "- Over 50? Yes, active member? Yes: stays (1 of 1 stayed).\n",
    "\n",
    "Step 5: the same with entropy. The root has $p = 0.4$. With $\\log_2 0.4 = -1.3219$ and $\\log_2 0.6 = -0.7370$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{entropy(root)} &= 0.4 \\times 1.3219 + 0.6 \\times 0.7370 \\\\[4pt]\n",
    "&= 0.5288 + 0.4422 = 0.971\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For \"Over 50?\", with $\\log_2 0.75 = -0.4150$, $\\log_2 0.25 = -2$, $\\log_2 \\tfrac{1}{6} = -2.585$ and $\\log_2 \\tfrac{5}{6} = -0.263$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{entropy(yes)} &= 0.75 \\times 0.4150 + 0.25 \\times 2 \\\\[4pt]\n",
    "&= 0.311 + 0.5 = 0.811 \\\\[8pt]\n",
    "\\text{entropy(no)} &= \\tfrac{1}{6} \\times 2.585 + \\tfrac{5}{6} \\times 0.263 \\\\[4pt]\n",
    "&= 0.431 + 0.219 = 0.650 \\\\[8pt]\n",
    "\\text{after the split} &= 0.4 \\times 0.811 + 0.6 \\times 0.650 \\\\[4pt]\n",
    "&= 0.324 + 0.390 = 0.714 \\\\[8pt]\n",
    "\\text{information gain} &= 0.971 - 0.714 = 0.257\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The other two questions give a smaller information gain, so entropy chooses the same root as Gini. This is the usual case.\n",
    "\n",
    "### 3.6 Numerical columns: trying every threshold\n",
    "\n",
    "The example had yes-or-no columns. A real column such as `age` has many values. The tree then tries questions of the form \"$\\text{age} > t$?\" for many thresholds $t$. It sorts the values and tries the points half way between two neighbouring values.\n",
    "\n",
    "The real ages of the ten customers, from the youngest:\n",
    "\n",
    "| Customer | I | F | E | H | G | J | D | B | C | A |\n",
    "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
    "| Age | 25 | 29 | 34 | 38 | 41 | 45 | 51 | 55 | 58 | 62 |\n",
    "| Left | no | no | yes | no | no | no | no | yes | yes | yes |\n",
    "\n",
    "Between 45 and 51 lies the threshold 48: \"age > 48?\" gives the same groups as \"Over 50?\", with Gini 0.317. But between 51 and 55 lies 53, and \"age > 53?\" puts B, C and A together, all three of whom left:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini}(\\text{age} > 53) &= 0 \\\\[8pt]\n",
    "\\text{Gini}(\\text{age} \\le 53) &= 1 - \\left(\\tfrac{1}{7}\\right)^2 - \\left(\\tfrac{6}{7}\\right)^2 = 0.2449 \\\\[8pt]\n",
    "\\text{after the split} &= 0.7 \\times 0.2449 + 0.3 \\times 0 \\\\[4pt]\n",
    "&= 0.1714\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The picture of the ten ages and the Gini of every threshold is on the lesson page: the lowest bar belongs to the threshold 53.\n",
    "\n",
    "With the real ages the tree finds a better question than \"Over 50?\". Of the nine thresholds, 53 gives the lowest impurity. This is how `DecisionTreeClassifier` works on every numerical column: it tries the thresholds of every feature and keeps the single best pair of feature and threshold.\n",
    "\n",
    "### 3.7 How the tree grows, and when it stops\n",
    "\n",
    "The whole algorithm in four sentences:\n",
    "\n",
    "1. Start with all training rows in the root.\n",
    "2. Try every feature and every threshold; take the split with the lowest impurity after the split.\n",
    "3. Do the same again in each of the two new nodes, with their rows only.\n",
    "4. Stop in a node when it is pure, or when a limit is reached (a maximal depth, too few rows to split: Part 5). The node becomes a leaf.\n",
    "\n",
    "Two properties of this algorithm explain much of the behaviour of trees:\n",
    "\n",
    "- It is greedy: at each node it takes the best question for this moment. It never goes back to ask whether a weaker first question would have allowed better questions later. Finding the best tree overall would take far too long.\n",
    "- Without limits it grows until every leaf is pure. On real data, where two customers with the same features can behave differently, that means leaves with one or two customers each: the tree learns the training rows by heart. Part 5 is about this.\n",
    "\n",
    "## 4. Regression trees\n",
    "\n",
    "A regression tree predicts a number. It grows in the same way; only two things change:\n",
    "\n",
    "- A leaf answers with the mean of the target of its training rows.\n",
    "- A split is judged by the squared error (the mean squared error, Topic 22) of the two groups, each around its own mean. The tree takes the split with the lowest weighted squared error.\n",
    "\n",
    "A small example: six customers, their age and their balance in thousands.\n",
    "\n",
    "| Age | 25 | 30 | 35 | 50 | 55 | 60 |\n",
    "| --- | --- | --- | --- | --- | --- | --- |\n",
    "| Balance | 10 | 20 | 30 | 100 | 110 | 120 |\n",
    "\n",
    "Without a split the tree predicts the mean, 65, for everybody:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{mean} &= \\frac{10 + 20 + 30 + 100 + 110 + 120}{6} \\\\[4pt]\n",
    "&= \\frac{390}{6} = 65\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{squared errors} &= 55^2 + 45^2 + 35^2 \\\\[4pt]\n",
    "&\\quad + 35^2 + 45^2 + 55^2 \\\\[4pt]\n",
    "&= 12550\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\text{mean squared error} = \\frac{12550}{6} = 2091.7\n",
    "$$\n",
    "\n",
    "With the question \"age > 42.5?\" (half way between 35 and 50):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{left: mean} &= \\frac{10 + 20 + 30}{3} = 20 \\\\[4pt]\n",
    "\\text{squared errors} &= 10^2 + 0^2 + 10^2 = 200 \\\\[8pt]\n",
    "\\text{right: mean} &= \\frac{100 + 110 + 120}{3} = 110 \\\\[4pt]\n",
    "\\text{squared errors} &= 10^2 + 0^2 + 10^2 = 200 \\\\[8pt]\n",
    "\\text{mean squared error} &= \\frac{200 + 200}{6} = 66.7\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The picture of this regression tree is on the lesson page: a step at 42.5, with the leaves at 20 and 110.\n",
    "\n",
    "One question lowers the mean squared error from 2091.7 to 66.7. The prediction of a regression tree is always a step function: a constant number in every leaf. It can never predict a value above the largest or below the smallest target of the training data.\n",
    "\n",
    "In scikit-learn the regression tree is `DecisionTreeRegressor`; its hyperparameters are the same as those of Part 5. The bank project of this lesson is a classification, so the code uses `DecisionTreeClassifier`.\n",
    "\n",
    "## 5. Overfitting and the hyperparameters\n",
    "\n",
    "### 5.1 Why a tree overfits\n",
    "\n",
    "A tree without limits keeps asking questions until every leaf is pure. On the bank data it grows to a depth of more than 20 with more than a thousand leaves (Part 8 shows it). Its training accuracy is then 1.0: it knows every training customer by heart, including the noise. Its test accuracy is clearly lower. This is overfitting (Topic 23): low bias, very high variance. A small change of the training data would give a quite different tree.\n",
    "\n",
    "The cure is to limit the tree: stop it early (pre-pruning), or let it grow and cut it back afterwards (post-pruning). The hyperparameters of `DecisionTreeClassifier` do exactly this.\n",
    "\n",
    "### 5.2 The hyperparameters of `DecisionTreeClassifier`\n",
    "\n",
    "| Hyperparameter | Default | What it does | Effect of a larger value |\n",
    "| --- | --- | --- | --- |\n",
    "| `criterion` | `\"gini\"` | the impurity measure: `\"gini\"`, `\"entropy\"` (or `\"log_loss\"`, the same as entropy) | (a choice, not a size) |\n",
    "| `max_depth` | `None` (no limit) | the largest number of questions from the root to a leaf | a deeper, more complex tree: more overfitting |\n",
    "| `min_samples_split` | `2` | the smallest number of rows a node must have to be split | fewer splits: a simpler tree |\n",
    "| `min_samples_leaf` | `1` | the smallest number of rows every leaf must keep | fewer, larger leaves: a simpler tree, smoother probabilities |\n",
    "| `max_leaf_nodes` | `None` | the largest number of leaves; the best splits are kept | a more complex tree |\n",
    "| `min_impurity_decrease` | `0.0` | a split is made only if it lowers the weighted impurity by at least this much | fewer splits: a simpler tree |\n",
    "| `max_features` | `None` (all) | how many features are tried at each split, chosen at random | `None` tries them all; a smaller number makes the tree more random (used in random forests, Topic 30) |\n",
    "| `class_weight` | `None` | weights for the classes; `\"balanced\"` gives the rare class more weight, as in Topic 27 | (a choice) more recall for the rare class |\n",
    "| `ccp_alpha` | `0.0` | cost-complexity pruning: after growing, branches that help too little are cut; a larger value cuts more | a smaller tree: less overfitting |\n",
    "| `splitter` | `\"best\"` | `\"best\"` tries all thresholds; `\"random\"` draws them at random | (a choice) |\n",
    "| `random_state` | `None` | the seed for the random choices, so that the tree is the same at every run | (no effect on quality) |\n",
    "\n",
    "Five of them matter most in practice:\n",
    "\n",
    "- `max_depth`: the simplest and most used limit. A depth of 3 to 8 is common for a single tree.\n",
    "- `min_samples_leaf`: every leaf must contain at least this many training rows. A leaf of 50 customers gives a reliable share; a leaf of 1 customer gives 0 or 1.\n",
    "- `criterion`: Gini or entropy; the difference is usually small.\n",
    "- `class_weight`: for unbalanced classes, when the recall of the rare class matters (Topic 28).\n",
    "- `ccp_alpha`: post-pruning. The tree is grown fully, then the branches whose improvement is worth less than `ccp_alpha` per leaf are cut back.\n",
    "\n",
    "Why `random_state`, when the algorithm is not random? When two features give exactly the same improvement, the tree must pick one, and scikit-learn shuffles the features before it tries them. With a fixed `random_state` the tree is the same at every run, and so are the numbers in this lesson.\n",
    "\n",
    "### 5.3 Choosing the hyperparameters\n",
    "\n",
    "A hyperparameter is chosen with cross-validation on the training data, never with the test data (Topic 23): try a few values, keep the one with the best mean score over the folds, then judge the finished tree once on the test data. Part 9 does this for `max_depth`. A systematic search over several hyperparameters at once is the subject of Topic 42.\n",
    "\n",
    "## 6. Preprocessing for trees, and for the models still to come\n",
    "\n",
    "Every project so far prepared the data in the same steps: fill or drop missing values, look at outliers, encode text, scale. Not every model needs every step. Knowing why a step is needed tells you when it can be left out.\n",
    "\n",
    "### 6.1 Scaling: not needed\n",
    "\n",
    "A tree asks \"is `balance` above 57,003?\". If the balance were measured in thousands, the question would be \"is `balance` above 57.003?\": the same customers go left and right. Scaling (Topic 24) changes the numbers, not their order, so every split, every leaf and every prediction stays the same. Part 9 shows it in code. Scaling a tree's features does no harm; it is just unnecessary work.\n",
    "\n",
    "Linear and logistic regression needed scaling for two reasons: the penalty of the regularization treats all weights alike (Topic 26), and the solver walks faster on features of the same scale (Topic 27). A tree has neither weights nor a solver.\n",
    "\n",
    "### 6.2 Encoding: still needed\n",
    "\n",
    "scikit-learn's trees accept only numbers, so the text columns `gender` and `country` must still be encoded (Topic 25). Two remarks:\n",
    "\n",
    "- A tree is not troubled by the order that label encoding invents. If `country` were coded France $= 0$, Germany $= 1$, Spain $= 2$, the tree could isolate Germany with two questions (\"$> 0.5$?\" and \"$\\le 1.5$?\"). One-hot encoding is still clearer, and this lesson keeps it.\n",
    "- A numerical column whose effect is not in order, such as `products_number`, needed one-hot encoding for logistic regression (Topic 27: customers with 2 products leave least, with 1 product more, with 3 or 4 almost all). A tree handles it as it is: \"products ≤ 1.5?\" and \"products > 2.5?\" carve out the groups. This lesson keeps `products_number` as a number.\n",
    "\n",
    "### 6.3 Outliers: trees are robust\n",
    "\n",
    "A split depends only on the order of the values. A customer aged 92 ends up in the same branch as a customer aged 70 when the question is \"age > 44?\"; how far he lies beyond the others does not matter. So extreme values of the features do not pull a tree as they pull a regression line. They are still looked at (Topic 25): a value that is a mistake must be corrected or removed for any model.\n",
    "\n",
    "Extreme values of the target do matter for a regression tree: a leaf predicts the mean of its rows, and one extreme value moves the mean.\n",
    "\n",
    "### 6.4 Missing values\n",
    "\n",
    "scikit-learn's decision trees (since version 1.3) can work with missing values: at each split they also learn to which side a missing value should go. Most other models of scikit-learn stop with an error. In this course the habit stays the same for every model: look at the missing values first (Topic 11), understand why they are missing, then fill or drop them on purpose. The bank file has none.\n",
    "\n",
    "### 6.5 Unbalanced classes\n",
    "\n",
    "A tree, like every model, is pulled towards the large class. `class_weight=\"balanced\"` works for trees as it did for logistic regression (Topics 27 and 28). Topic 41 is about unbalanced data.\n",
    "\n",
    "### 6.6 A table for this and the coming topics\n",
    "\n",
    "| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values in scikit-learn |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Linear and logistic regression, Ridge, Lasso (22, 26, 27) | needed | needed | sensitive | must be filled |\n",
    "| Decision tree (29) | not needed | needed | robust | handled since version 1.3 |\n",
    "| Random forest (30, 31) | not needed | needed | robust | see Topic 30 |\n",
    "| k-nearest neighbours (32, 33) | essential: distances | needed | sensitive | must be filled |\n",
    "| Support vector machines (35, 36) | essential: distances | needed | sensitive | must be filled |\n",
    "| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost and LightGBM handle them |\n",
    "| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | must be filled |\n",
    "\n",
    "The rule behind the table: models built from trees only compare a feature with a threshold, so they do not need scaling and do not mind outliers. Models built from distances, weights or variances need features on the same scale. Topic 42 will show how to put all preprocessing steps and the model into one object, so that none of them is forgotten.\n",
    "\n",
    "## 7. The project: from the file to the data for the tree\n",
    "\n",
    "Now the data: `Bank Customer Churn Prediction.csv`, 10,000 customers of a bank, and the column `churn` says who left (1) and who stayed (0).\n",
    "\n",
    "Every step is done again and explained as if it were new, so that the whole workflow is in one place. The cells continue from each other like the cells of a notebook.\n",
    "\n",
    "### 7.1 Step 1: read and look"
   ],
   "id": "t29-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head())"
   ],
   "id": "t29-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10,000 rows and 12 columns. Each row is one customer: an identification number, ten features (credit score, country, gender, age, years as a customer, balance, number of products, credit card, active membership, estimated salary) and the target `churn`.\n",
    "\n",
    "### 7.2 Step 2: check"
   ],
   "id": "t29-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())\n",
    "print(df.dtypes)"
   ],
   "id": "t29-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No missing values and no repeated rows, so nothing has to be filled or dropped (Topic 11). Two columns are text: `country` and `gender`.\n",
    "\n",
    "### 7.3 Step 3: drop what carries no information"
   ],
   "id": "t29-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t29-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An identification number is different for every customer and says nothing about him. A tree would even use it: it could find a threshold on the number that happens to separate a few customers in the training data, and learn noise (Topic 24).\n",
    "\n",
    "### 7.4 Step 4: the target"
   ],
   "id": "t29-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"churn\"].value_counts())\n",
    "print(round(df[\"churn\"].mean(), 4))"
   ],
   "id": "t29-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "About 20 percent of the customers left: the classes are unbalanced. So the accuracy alone will not judge the tree; the measures of Topic 28 will.\n",
    "\n",
    "### 7.5 Step 5: outliers\n",
    "\n",
    "The upper limit of the IQR rule for `age` (Topic 25):"
   ],
   "id": "t29-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = df[\"age\"].quantile(0.25)\n",
    "q3 = df[\"age\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((df[\"age\"] > upper).sum())"
   ],
   "id": "t29-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "359 customers are older than 62. They are real customers, not mistakes, and a tree only asks whether an age is above a threshold, not how far above it lies (Part 6). They stay in the data.\n",
    "\n",
    "### 7.6 Step 6: encode\n",
    "\n",
    "`gender` has two values and becomes 0 and 1. `country` has three values without an order and gets one-hot encoding (Topic 25). `products_number` stays a number: the tree can split it where it needs to (Part 6)."
   ],
   "id": "t29-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist())"
   ],
   "id": "t29-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Eleven features and the target, all numbers.\n",
    "\n",
    "### 7.7 Step 7: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 3,000 customers become test data."
   ],
   "id": "t29-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t29-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "8,000 customers for training, 2,000 for the test (Topic 23). The same `random_state` as in Topics 27 and 28 gives the same test customers, so the results can be compared.\n",
    "\n",
    "### 7.8 Step 8: no scaling\n",
    "\n",
    "There is no scaling step. The tree will work with the features as they are: ages in years, balances in euros. Part 9 checks that scaling would change nothing.\n",
    "\n",
    "## 8. The first tree\n",
    "\n",
    "### 8.1 Train and judge\n",
    "\n",
    "Change it and run: write `DecisionTreeClassifier(max_depth=4, random_state=42)` and run: the training accuracy falls below 1 and the test accuracy rises."
   ],
   "id": "t29-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "tree = DecisionTreeClassifier(random_state=42)\n",
    "tree.fit(X_train, y_train)\n",
    "\n",
    "print(tree.score(X_train, y_train))\n",
    "print(round(tree.score(X_test, y_test), 4))"
   ],
   "id": "t29-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A training accuracy of 1.0 and a test accuracy of 0.7845. The tree is right for every training customer and for only 78 of 100 new customers: it is lower than the baseline of always answering \"stays\" (0.8035, Topic 27). This is overfitting in its purest form.\n",
    "\n",
    "### 8.2 How big is it?"
   ],
   "id": "t29-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(tree.get_depth())\n",
    "print(tree.get_n_leaves())"
   ],
   "id": "t29-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A depth of 24 and 1,150 leaves for 8,000 training customers: on average fewer than 7 customers per leaf. Many leaves hold a single customer. The tree has written down the training data, it has not learned rules.\n",
    "\n",
    "### 8.3 The measures of Topic 28"
   ],
   "id": "t29-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "predicted = tree.predict(X_test)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))"
   ],
   "id": "t29-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The recall, 0.5038, is better than that of logistic regression (0.3639 in Topic 28), but the precision is low: almost every second customer the tree marks as leaving stays."
   ],
   "id": "t29-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "leaving = tree.predict_proba(X_test)[:, 1]\n",
    "\n",
    "print(sorted(set(leaving)))\n",
    "print(round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t29-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every leaf of this tree is pure, so the only probabilities it can give are 0 and 1. The ROC curve has a single point between its corners, and the AUC is only 0.6785, far below the 0.837 of logistic regression. A tree with pure leaves cannot rank its customers.\n",
    "\n",
    "## 9. A tree you can read, and a tree that works\n",
    "\n",
    "### 9.1 A small tree\n",
    "\n",
    "Change it and run: change `max_depth=3` to `max_depth=2` and run."
   ],
   "id": "t29-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "small = DecisionTreeClassifier(max_depth=3, random_state=42)\n",
    "small.fit(X_train, y_train)\n",
    "\n",
    "print(round(small.score(X_train, y_train), 4))\n",
    "print(round(small.score(X_test, y_test), 4))"
   ],
   "id": "t29-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Only three questions on every path, and the test accuracy rises from 0.7845 to 0.8485. Training and test accuracy are now almost equal: the tree no longer learns noise.\n",
    "\n",
    "### 9.2 Its rules as text\n",
    "\n",
    "`export_text` writes the tree as rules. `show_weights=True` adds, for every leaf, how many training customers of each class ended there:"
   ],
   "id": "t29-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import export_text\n",
    "\n",
    "print(export_text(small, feature_names=list(X.columns), show_weights=True))"
   ],
   "id": "t29-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How to read it:\n",
    "\n",
    "- Every line with `<=` or `>` is a question; the deeper the indentation, the deeper the node.\n",
    "- The root question is `age <= 44.50`: the tree found that the age separates leaving and staying customers best, as the hand example of Part 3 did with its ten customers.\n",
    "- For the younger customers the next question is about `products_number`: customers with more than 2 products leave far more often. For the older customers it is `active_member`.\n",
    "- `weights: [a, b]` are the training customers of the leaf who stayed (a) and who left (b). The class is the larger of the two, and `predict_proba` is $\\frac{b}{a + b}$.\n",
    "\n",
    "The root and the second level tell the story of the data in three lines: the age, the number of products and the activity of a customer decide most of the churn. It is the same story the weights of logistic regression told in Topic 27, now as rules.\n",
    "\n",
    "### 9.3 The tree as a picture"
   ],
   "id": "t29-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.tree import plot_tree\n",
    "\n",
    "plt.figure(figsize=(16, 7))\n",
    "plot_tree(small, feature_names=list(X.columns), class_names=[\"stays\", \"leaves\"], filled=True, fontsize=9)\n",
    "plt.show()"
   ],
   "id": "t29-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`plot_tree` draws the same tree. Every box shows its question, its Gini impurity, its number of training customers (`samples`), the customers of each class (`value`) and its class. `filled=True` colours a box by its class: the stronger the colour, the purer the node.\n",
    "\n",
    "### 9.4 Following one customer\n",
    "\n",
    "Change it and run: change `iloc[[0]]` to `iloc[[1]]` and follow the second test customer through the rules."
   ],
   "id": "t29-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer = X_test.iloc[[0]]\n",
    "\n",
    "print(customer[[\"age\", \"products_number\", \"active_member\", \"balance\"]])\n",
    "print(small.predict(customer))\n",
    "print(small.predict_proba(customer).round(3))"
   ],
   "id": "t29-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`X_test.iloc[[0]]` is the first test customer, kept as a table of one row (two brackets). Follow him through the rules above: he is 32, so `age <= 44.50` sends him left; he has 2 products, so `products_number <= 2.50` and then `products_number > 1.50`. He lands in the leaf with `weights: [2886.00, 149.00]`: 149 of its 3,035 training customers left.\n",
    "\n",
    "$$\n",
    "\\text{probability of leaving} = \\frac{149}{3035} = 0.049\n",
    "$$\n",
    "\n",
    "That is the second number of `predict_proba`, and because it is below 0.5 the tree predicts 0: he stays. Every other test customer in the same leaf gets exactly the same probability.\n",
    "\n",
    "### 9.5 Which features did the tree use?"
   ],
   "id": "t29-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "importances = pd.Series(small.feature_importances_, index=X.columns)\n",
    "\n",
    "print(importances.sort_values(ascending=False).round(3))"
   ],
   "id": "t29-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`feature_importances_` adds up, for every feature, how much its splits lowered the impurity, weighted by the number of rows they split, and scales the sums to add up to 1. The small tree uses only a few features; the rest have importance 0. A feature with importance 0 was not useless in general, it was simply never chosen.\n",
    "\n",
    "## 10. Tuning the tree\n",
    "\n",
    "### 10.1 `max_depth`: from underfitting to overfitting"
   ],
   "id": "t29-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for depth in [1, 2, 3, 4, 5, 6, 8, 10, 15, None]:\n",
    "    model = DecisionTreeClassifier(max_depth=depth, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(depth, round(model.score(X_train, y_train), 4), round(model.score(X_test, y_test), 4))"
   ],
   "id": "t29-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the depth, the training accuracy and the test accuracy.\n",
    "\n",
    "- The training accuracy rises with every level, up to 1.0 for the unlimited tree (`None`).\n",
    "- The test accuracy rises at first, is highest around the depths 5 and 6, and then falls again, down to 0.7845 for the unlimited tree."
   ],
   "id": "t29-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "depths = list(range(1, 16))\n",
    "train_scores = []\n",
    "test_scores = []\n",
    "\n",
    "for depth in depths:\n",
    "    model = DecisionTreeClassifier(max_depth=depth, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    train_scores.append(model.score(X_train, y_train))\n",
    "    test_scores.append(model.score(X_test, y_test))\n",
    "\n",
    "plt.plot(depths, train_scores, marker=\"o\", label=\"training data\")\n",
    "plt.plot(depths, test_scores, marker=\"o\", label=\"test data\")\n",
    "plt.xlabel(\"max_depth\")\n",
    "plt.ylabel(\"accuracy\")\n",
    "plt.title(\"Accuracy of a tree against its depth\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t29-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is the picture of Topic 23 again: on the left the tree is too simple (underfitting: both accuracies low), on the right it is too complex (overfitting: the curves drift apart). The best depth lies in between.\n",
    "\n",
    "### 10.2 Choosing the depth with cross-validation\n",
    "\n",
    "The test data may not choose the depth (Topic 23). Cross-validation on the training data does. Because the classes are unbalanced, the folds are judged here with the AUC of Topic 28: `scoring=\"roc_auc\"` tells `cross_val_score` which measure to use.\n",
    "\n",
    "Change it and run: add `scoring=\"f1\"` in the place of `\"roc_auc\"` and run: the F1-score may prefer another depth."
   ],
   "id": "t29-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for depth in [3, 4, 5, 6, 7, 8]:\n",
    "    model = DecisionTreeClassifier(max_depth=depth, random_state=42)\n",
    "    scores = cross_val_score(model, X_train, y_train, cv=5, scoring=\"roc_auc\")\n",
    "    print(depth, round(scores.mean(), 4))"
   ],
   "id": "t29-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mean AUC over the five folds is highest for a depth of 5. That is the choice. (Without `scoring`, `cross_val_score` uses the accuracy; other names are `\"f1\"`, `\"recall\"` and `\"precision\"`.)\n",
    "\n",
    "### 10.3 `min_samples_leaf`: large leaves\n",
    "\n",
    "A second way to stop a tree: every leaf must keep a number of customers."
   ],
   "id": "t29-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for leaf in [1, 10, 20, 50, 100]:\n",
    "    model = DecisionTreeClassifier(min_samples_leaf=leaf, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    leaving = model.predict_proba(X_test)[:, 1]\n",
    "    print(leaf, model.get_n_leaves(), round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t29-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows `min_samples_leaf`, the number of leaves and the test AUC. With leaves of at least 50 customers the tree has about a hundred leaves instead of 1,150, and its AUC rises from 0.68 to 0.84: larger leaves give reliable shares, and reliable shares rank the customers well.\n",
    "\n",
    "### 10.4 `criterion`: Gini or entropy"
   ],
   "id": "t29-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for criterion in [\"gini\", \"entropy\"]:\n",
    "    model = DecisionTreeClassifier(max_depth=5, criterion=criterion, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(criterion, round(model.score(X_test, y_test), 4))"
   ],
   "id": "t29-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two measures give almost the same tree, as Part 3 said.\n",
    "\n",
    "### 10.5 `ccp_alpha`: pruning after growing"
   ],
   "id": "t29-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for alpha in [0.0, 0.0005, 0.001, 0.002, 0.005]:\n",
    "    model = DecisionTreeClassifier(ccp_alpha=alpha, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(alpha, model.get_n_leaves(), round(model.score(X_test, y_test), 4))"
   ],
   "id": "t29-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows `ccp_alpha`, the number of leaves and the test accuracy. The tree is grown in full and then cut back. Already a small `ccp_alpha` removes most of the 1,150 leaves, and the test accuracy rises from 0.78 to about 0.86. Too large a value cuts too much, and the accuracy falls again.\n",
    "\n",
    "### 10.6 The tuned tree\n",
    "\n",
    "Change it and run: change `max_depth=5` to `max_depth=6` and run."
   ],
   "id": "t29-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "final = DecisionTreeClassifier(max_depth=5, random_state=42)\n",
    "final.fit(X_train, y_train)\n",
    "\n",
    "predicted = final.predict(X_test)\n",
    "leaving = final.predict_proba(X_test)[:, 1]\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "print(round(final.score(X_test, y_test), 4))\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))\n",
    "print(round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t29-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The confusion matrix, the accuracy, the precision, the recall, the F1-score and the AUC of the tuned tree, on the same 2,000 test customers as in Topic 28:\n",
    "\n",
    "| Measure | Logistic regression (Topic 28) | Full tree | Tree with `max_depth=5` |\n",
    "| --- | --- | --- | --- |\n",
    "| Accuracy | 0.843 | 0.7845 | 0.8575 |\n",
    "| Precision | 0.6908 | 0.4562 | 0.7647 |\n",
    "| Recall | 0.3639 | 0.5038 | 0.3969 |\n",
    "| F1-score | 0.4767 | 0.4788 | 0.5226 |\n",
    "| AUC | 0.837 | 0.6785 | 0.8328 |\n",
    "\n",
    "The tuned tree beats logistic regression on the accuracy, the precision and the F1-score, and reaches almost the same AUC, with eleven features as they are: no scaling and no one-hot encoding of `products_number`. The full tree loses on almost every measure. The same model can be the worst or the best of the three: the hyperparameters decide.\n",
    "\n",
    "### 10.7 More recall: `class_weight`\n",
    "\n",
    "For the bank a missed customer is the expensive mistake (Topic 28). The tuned tree finds only about 40 of 100 leaving customers."
   ],
   "id": "t29-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = DecisionTreeClassifier(max_depth=5, class_weight=\"balanced\", random_state=42)\n",
    "balanced.fit(X_train, y_train)\n",
    "\n",
    "predicted_balanced = balanced.predict(X_test)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted_balanced))\n",
    "print(round(recall_score(y_test, predicted_balanced), 4))\n",
    "print(round(precision_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t29-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The recall roughly doubles, and the precision falls: more customers are found, at the price of more false alarms, exactly as with logistic regression in Topic 28.\n",
    "\n",
    "### 10.8 The importances of the tuned tree"
   ],
   "id": "t29-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "importances = pd.Series(final.feature_importances_, index=X.columns)\n",
    "\n",
    "importances.sort_values().plot(kind=\"barh\")\n",
    "plt.title(\"Feature importances of the tuned tree\")\n",
    "plt.xlabel(\"importance\")\n",
    "plt.show()"
   ],
   "id": "t29-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The age and the number of products carry most of the tree (0.431 and 0.334 of the importance), followed by the activity (0.155). Germany, the balance and the salary add a little; the gender, the credit score, the credit card and Spain are not used at all by this tree.\n",
    "\n",
    "### 10.9 Seeing a large tree\n",
    "\n",
    "The tuned tree has 5 levels and 32 leaves: too many to read at once. Both tools can show only its top. `max_depth` inside `export_text` (and inside `plot_tree`) limits the drawing, not the model:"
   ],
   "id": "t29-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(final.get_depth(), final.get_n_leaves())\n",
    "print(export_text(final, feature_names=list(X.columns), max_depth=2))"
   ],
   "id": "t29-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line gives the real size of the tree. In the rules, `truncated branch of depth 3` marks a branch that goes on below the shown levels."
   ],
   "id": "t29-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(16, 7))\n",
    "plot_tree(final, max_depth=2, feature_names=list(X.columns), class_names=[\"stays\", \"leaves\"], filled=True, fontsize=9)\n",
    "plt.show()"
   ],
   "id": "t29-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The boxes with `(...)` below them continue further down. The top of the tuned tree asks the same first questions as the small tree: the age, then the number of products and the activity.\n",
    "\n",
    "### 10.10 Scaling changes nothing: the proof"
   ],
   "id": "t29-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "scaled_tree = DecisionTreeClassifier(max_depth=5, random_state=42)\n",
    "scaled_tree.fit(X_train_scaled, y_train)\n",
    "\n",
    "print((scaled_tree.predict(X_test_scaled) == final.predict(X_test)).all())"
   ],
   "id": "t29-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`True`: on scaled features the tree gives exactly the same prediction for every one of the 2,000 test customers. Only the thresholds in its questions are different numbers.\n",
    "\n",
    "## 11. The workflow, step by step\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look | shape, first rows, the meaning of the columns | 10,000 customers, 12 columns |\n",
    "| 2. Check | missing values, repeated rows, text columns | nothing missing; two text columns |\n",
    "| 3. Drop | columns without information | `customer_id` |\n",
    "| 4. Target | the share of each class | 20 percent left: unbalanced |\n",
    "| 5. Outliers | find them, decide: mistake or real | 359 older customers: real, kept; a tree does not mind them |\n",
    "| 6. Encode | text to numbers | `gender` 0 and 1, `country` one-hot; `products_number` stays a number |\n",
    "| 7. Split | training and test data | 8,000 and 2,000 |\n",
    "| 8. Scale | only for models that need it | not for a tree |\n",
    "| 9. First model | a simple start | the full tree: overfits (test accuracy 0.7845) |\n",
    "| 10. Tune | hyperparameters with cross-validation | `max_depth=5`, chosen by the AUC of 5 folds |\n",
    "| 11. Judge | the measures of Topic 28 on the test data | accuracy 0.8575, F1 0.5226, AUC 0.8328 |\n",
    "| 12. Explain | the rules and the feature importances | age, number of products, activity |\n",
    "\n",
    "Compared with Topics 27 and 28, scaling has dropped out, the one-hot encoding of `products_number` is not needed, and a new step has come in: reading and explaining the model itself.\n",
    "\n",
    "## 12. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Training a tree without any limit and reporting the training accuracy. | A full tree is always right on its training data: 1.0 says nothing. | Judge on the test data; limit the tree. |\n",
    "| Choosing `max_depth` with the test data. | The test data then takes part in building the model. | Cross-validation on the training data. |\n",
    "| Scaling the features \"because the workflow says so\". | It changes nothing for a tree. | Scale only for models that need it (Part 6). |\n",
    "| Leaving text columns in `X`. | scikit-learn's trees accept only numbers: an error. | Encode `gender` and `country` first. |\n",
    "| Keeping `customer_id` as a feature. | A tree can split on it and learn noise. | Drop identification numbers. |\n",
    "| Reading `feature_importances_` as \"how a feature changes the probability\". | It says how much a feature lowered the impurity, not in which direction it pushes. | Read the rules for the direction. |\n",
    "| Thinking a feature with importance 0 is useless. | It was only never chosen; a similar feature may have taken its place. | Treat importance as \"used by this tree\". |\n",
    "| Trusting the probabilities of a deep tree. | Pure leaves give only 0 and 1: the AUC collapses. | Limit the depth, or use `min_samples_leaf`. |\n",
    "| Expecting the same tree after a small change of the data. | A tree is unstable: a different first split changes everything below it. | Random forests (Topic 30) average many trees. |\n",
    "| Forgetting `random_state`. | Ties between features are broken at random: the tree can differ between runs. | Fix `random_state`. |\n",
    "| Thinking a tree finds the best tree overall. | It is greedy: the best question now, one node at a time. | It is a good heuristic, not a guarantee. |\n",
    "| Expecting a regression tree to predict beyond the training values. | A leaf is a mean of training targets. | Know the range of its predictions. |\n",
    "\n",
    "## 13. Solved problems\n",
    "\n",
    "Sixteen problems. The first four are short and solved by hand. Problems 5 to 16 are one project on `Bank Customer Churn Prediction.csv`, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.\n",
    "\n",
    "Problem 1. Gini and entropy of a node\n",
    "\n",
    "A node holds 10 customers: 3 left and 7 stayed. Calculate its Gini impurity and its entropy. Use $\\log_2 0.3 = -1.7370$ and $\\log_2 0.7 = -0.5146$.\n",
    "\n",
    "Idea. $p = 0.3$; the formulas of Part 3.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini} &= 1 - 0.3^2 - 0.7^2 \\\\[4pt]\n",
    "&= 1 - 0.09 - 0.49 = 0.42 \\\\[8pt]\n",
    "\\text{entropy} &= 0.3 \\times 1.7370 + 0.7 \\times 0.5146 \\\\[4pt]\n",
    "&= 0.5211 + 0.3602 = 0.8813\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: both numbers are clearly above 0 and below their highest values (0.5 and 1): the node is mixed, but not half and half.\n",
    "\n",
    "Problem 2. Choosing between two questions\n",
    "\n",
    "A node holds 10 customers, 4 of them left. Question A splits it into 5 customers (4 left) and 5 customers (0 left). Question B splits it into 6 customers (3 left) and 4 customers (1 left). Which question does the tree choose?\n",
    "\n",
    "Idea. The Gini of each group, then the mean weighted with the group sizes; the lowest wins (Part 3).\n",
    "\n",
    "Question A:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini} &= 1 - 0.8^2 - 0.2^2 = 0.32 \\quad \\text{and} \\quad 0 \\\\[6pt]\n",
    "\\text{after the split} &= 0.5 \\times 0.32 + 0.5 \\times 0 = 0.16\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Question B:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Gini} &= 1 - 0.5^2 - 0.5^2 = 0.5 \\\\[4pt]\n",
    "\\text{Gini} &= 1 - 0.25^2 - 0.75^2 = 0.375 \\\\[6pt]\n",
    "\\text{after the split} &= 0.6 \\times 0.5 + 0.4 \\times 0.375 \\\\[4pt]\n",
    "&= 0.30 + 0.15 = 0.45\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: question A leaves a pure group and an almost pure one: 0.16 against 0.45. The tree chooses A.\n",
    "\n",
    "Problem 3. Thresholds of a numerical column\n",
    "\n",
    "Four customers have the ages 22, 30, 41 and 48; the first two stayed, the last two left. Which thresholds does the tree try for `age`, and which one does it choose?\n",
    "\n",
    "Idea. The thresholds lie half way between neighbouring values (Part 3).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\frac{22 + 30}{2} &= 26 \\\\[6pt]\n",
    "\\frac{30 + 41}{2} &= 35.5 \\\\[6pt]\n",
    "\\frac{41 + 48}{2} &= 44.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: \"age > 35.5?\" puts the two customers who stayed on one side and the two who left on the other: two pure groups, Gini 0 after the split. The other two thresholds leave a mixed group.\n",
    "\n",
    "Problem 4. The answer of a leaf\n",
    "\n",
    "A leaf of a trained tree holds 40 training customers, 10 of whom left. What does `predict_proba` give for a new customer in this leaf, and what does `predict` give? Which class would the threshold 0.2 give?\n",
    "\n",
    "Idea. A leaf answers with the shares of its training rows (Part 2) and the threshold of Topic 27.\n",
    "\n",
    "$$\n",
    "\\text{probability of leaving} = \\frac{10}{40} = 0.25\n",
    "$$\n",
    "\n",
    "Why: 0.25 is below 0.5, so `predict` says 0 (stays). With the threshold 0.2 the same customer would be marked as leaving, because 0.25 is at least 0.2.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of missing values and the share of customers who left, rounded to 4 decimals.\n",
    "\n",
    "Idea. The first steps of the workflow (Part 7)."
   ],
   "id": "t29-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.isna().sum().sum())\n",
    "print(round(df[\"churn\"].mean(), 4))"
   ],
   "id": "t29-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: nothing has to be filled, and one customer in five left: the accuracy will not be enough.\n",
    "\n",
    "Problem 6. Drop and encode\n",
    "\n",
    "Drop `customer_id`, encode `gender` as 0 (Female) and 1 (Male), and one-hot encode `country` with `drop_first=True`. Print the number of columns.\n",
    "\n",
    "Idea. Text to numbers; `products_number` stays a number for a tree (Part 6)."
   ],
   "id": "t29-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))"
   ],
   "id": "t29-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 12 columns: eleven features and the target.\n",
    "\n",
    "Problem 7. Split\n",
    "\n",
    "Make `X` and `y` and split them with `test_size=0.25` and `random_state=7`. Print the shapes of `X_train` and `X_test`.\n",
    "\n",
    "Idea. The split comes before anything learns from the rows. No scaling follows: a tree does not need it."
   ],
   "id": "t29-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t29-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 7,500 customers to learn from and 2,500 to judge with.\n",
    "\n",
    "Problem 8. A tree without limits\n",
    "\n",
    "Train a `DecisionTreeClassifier` with `random_state=42`. Print its training accuracy, its test accuracy (rounded to 4 decimals) and its number of leaves.\n",
    "\n",
    "Idea. The full tree of Part 8."
   ],
   "id": "t29-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "tree = DecisionTreeClassifier(random_state=42)\n",
    "tree.fit(X_train, y_train)\n",
    "\n",
    "print(tree.score(X_train, y_train))\n",
    "print(round(tree.score(X_test, y_test), 4))\n",
    "print(tree.get_n_leaves())"
   ],
   "id": "t29-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: perfect on the training data, below the baseline on the test data, and about a thousand leaves: overfitting.\n",
    "\n",
    "Problem 9. The rules of a small tree\n",
    "\n",
    "Train a tree with `max_depth=2` and `random_state=42` and print its rules with `export_text`.\n",
    "\n",
    "Idea. A shallow tree can be read as rules (Part 9)."
   ],
   "id": "t29-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.tree import export_text\n",
    "\n",
    "small = DecisionTreeClassifier(max_depth=2, random_state=42)\n",
    "small.fit(X_train, y_train)\n",
    "\n",
    "print(export_text(small, feature_names=list(X.columns)))"
   ],
   "id": "t29-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: with another split of the data the first question is again about the age, and the second about the number of products and the activity: the story of the data does not depend on the split.\n",
    "\n",
    "Problem 10. Depth against accuracy\n",
    "\n",
    "For the depths 2, 4, 6, 8 and 10, print the depth, the training accuracy and the test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. One hyperparameter changed at a time (Part 10)."
   ],
   "id": "t29-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for depth in [2, 4, 6, 8, 10]:\n",
    "    model = DecisionTreeClassifier(max_depth=depth, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(depth, round(model.score(X_train, y_train), 4), round(model.score(X_test, y_test), 4))"
   ],
   "id": "t29-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the training accuracy keeps rising, the test accuracy rises and then falls: from underfitting to overfitting.\n",
    "\n",
    "Problem 11. Choosing the depth\n",
    "\n",
    "Compare the depths 4, 5, 6 and 7 with a 5-fold cross-validation on the training data, judged by the AUC. Print each depth with its mean AUC, rounded to 4 decimals.\n",
    "\n",
    "Idea. `cross_val_score` with `scoring=\"roc_auc\"` (Part 10)."
   ],
   "id": "t29-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for depth in [4, 5, 6, 7]:\n",
    "    model = DecisionTreeClassifier(max_depth=depth, random_state=42)\n",
    "    scores = cross_val_score(model, X_train, y_train, cv=5, scoring=\"roc_auc\")\n",
    "    print(depth, round(scores.mean(), 4))"
   ],
   "id": "t29-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the depth with the highest mean AUC is chosen, without looking at the test data.\n",
    "\n",
    "Problem 12. The tuned tree\n",
    "\n",
    "Train the tree with `max_depth=5` and `random_state=42`, call it `final`, and print the confusion matrix of its test predictions.\n",
    "\n",
    "Idea. The chosen depth, judged once on the test data (Part 10)."
   ],
   "id": "t29-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "final = DecisionTreeClassifier(max_depth=5, random_state=42)\n",
    "final.fit(X_train, y_train)\n",
    "\n",
    "predicted = final.predict(X_test)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))"
   ],
   "id": "t29-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: read it like a text: TN, FP, FN, TP. The tree finds a part of the leaving customers and gives few false alarms.\n",
    "\n",
    "Problem 13. Its measures\n",
    "\n",
    "Print the precision, the recall, the F1-score and the AUC of `final`, each rounded to 4 decimals.\n",
    "\n",
    "Idea. The measures of Topic 28; the AUC needs the probabilities."
   ],
   "id": "t29-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "leaving = final.predict_proba(X_test)[:, 1]\n",
    "\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))\n",
    "print(round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t29-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a fair precision and a modest recall, and an AUC far above that of a full tree, whose probabilities are only 0 and 1 (Part 8).\n",
    "\n",
    "Problem 14. Balanced classes\n",
    "\n",
    "Train the same tree with `class_weight=\"balanced\"`. Print its recall and its precision, rounded to 4 decimals.\n",
    "\n",
    "Idea. More weight for the rare class (Part 5)."
   ],
   "id": "t29-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = DecisionTreeClassifier(max_depth=5, class_weight=\"balanced\", random_state=42)\n",
    "balanced.fit(X_train, y_train)\n",
    "\n",
    "predicted_balanced = balanced.predict(X_test)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_balanced), 4))\n",
    "print(round(precision_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t29-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the recall rises strongly and the precision falls: the bank finds more of the customers who leave and calls more who would have stayed.\n",
    "\n",
    "Problem 15. Feature importances\n",
    "\n",
    "Print the three most important features of `final` with their importances, rounded to 3 decimals.\n",
    "\n",
    "Idea. `feature_importances_` as a Series, sorted (Part 9)."
   ],
   "id": "t29-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "importances = pd.Series(final.feature_importances_, index=X.columns)\n",
    "\n",
    "print(importances.sort_values(ascending=False).head(3).round(3))"
   ],
   "id": "t29-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the age and the number of products lead again: the tree explains itself in the same words as in the lesson.\n",
    "\n",
    "Problem 16. Draw the small tree\n",
    "\n",
    "Draw the tree `small` of Problem 9 with `plot_tree`, with the names of the features and of the classes.\n",
    "\n",
    "Idea. The picture of the rules (Part 9)."
   ],
   "id": "t29-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.tree import plot_tree\n",
    "\n",
    "plt.figure(figsize=(12, 6))\n",
    "plot_tree(small, feature_names=list(X.columns), class_names=[\"stays\", \"leaves\"], filled=True, fontsize=10)\n",
    "plt.show()"
   ],
   "id": "t29-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: three questions and four leaves, each with its Gini impurity, its customers and its class: a model a bank manager can read.\n",
    "\n",
    "## 16. Summary\n",
    "\n",
    "|  | Formula | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Gini impurity | $1 - p^2 - (1 - p)^2$ | 0 for a pure node, 0.5 for a half-and-half node |\n",
    "| Entropy | $-p \\log_2 p - (1 - p) \\log_2 (1 - p)$ | 0 for a pure node, 1 for a half-and-half node |\n",
    "| A split | $\\frac{n_{\\text{left}}}{n} \\, \\text{impurity}_{\\text{left}} + \\frac{n_{\\text{right}}}{n} \\, \\text{impurity}_{\\text{right}}$ | the lowest value wins |\n",
    "| Information gain | $\\text{entropy before} - \\text{entropy after}$ | the largest gain wins |\n",
    "| Leaf of a classification tree | the share of each class | `predict_proba`; `predict` takes the larger share |\n",
    "| Leaf of a regression tree | the mean of the target | a step function |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `DecisionTreeClassifier(random_state=42)` | a classification tree without limits |\n",
    "| `DecisionTreeClassifier(max_depth=5)` | a tree of at most 5 questions on every path |\n",
    "| `min_samples_leaf`, `max_leaf_nodes`, `ccp_alpha` | other ways to keep a tree small |\n",
    "| `criterion=\"entropy\"` | entropy in the place of Gini |\n",
    "| `class_weight=\"balanced\"` | more weight for the rare class |\n",
    "| `tree.get_depth()`, `tree.get_n_leaves()` | the size of the tree |\n",
    "| `export_text(tree, feature_names=list(X.columns))` | the rules as text |\n",
    "| `plot_tree(tree, feature_names=..., class_names=..., filled=True)` | the tree as a picture |\n",
    "| `tree.feature_importances_` | how much each feature was used |\n",
    "| `cross_val_score(model, X_train, y_train, cv=5, scoring=\"roc_auc\")` | choose a hyperparameter by the AUC |\n",
    "| `DecisionTreeRegressor` | the regression tree |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. A tree predicts with a row of yes-or-no questions; each compares one feature with one threshold.\n",
    "2. It chooses each question greedily: the split with the lowest weighted impurity (Gini or entropy).\n",
    "3. Without limits it overfits: training accuracy 1.0, poor test results, probabilities of only 0 and 1.\n",
    "4. Limit it with `max_depth`, `min_samples_leaf` or `ccp_alpha`, chosen with cross-validation on the training data.\n",
    "5. A tree needs no scaling and is robust to outliers in the features; text must still be encoded.\n",
    "6. Judge it with the measures of Topic 28, and explain it with its rules and its feature importances.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "A single tree is easy to read, but unstable: a few different training rows can change its first question and everything below it. Topic 30, random forests, trains hundreds of trees on different samples of the data and lets them vote: a model that is far more stable and usually more accurate, built from the tree of this lesson.\n",
    "\n",
    "Next: the practice notebook (topic-29-practice.ipynb), then Topic 30: Random Forests and ensemble learning (bagging) - Classification."
   ],
   "id": "t29-081"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
