{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 30: Random Forests and ensemble learning (bagging) - Classification\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 15, Thursday.\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-30-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 6 to 9 are one project, so start at the first cell of Part 6. The solved problems 5 to 16 are a second project that starts again from reading the file. Some cells train many forests and take a few seconds. A random forest can give slightly different numbers in the last decimals on another computer: that comes from the computer, not from your code.\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 random forest is\n",
    "2. How a random forest works\n",
    "3. How the trees choose their questions\n",
    "4. The hyperparameters of a random forest\n",
    "5. Preprocessing for forests, and for the models still to come\n",
    "6. The project: from the file to the data for the forest\n",
    "7. The random forest\n",
    "8. Tuning the forest\n",
    "9. Bagging: the idea behind the forest, for any model\n",
    "10. The workflow, step by step\n",
    "11. Common mistakes\n",
    "12. Solved problems\n",
    "13. Practice (in topic-30-practice.ipynb)\n",
    "14. Check yourself (on the website)\n",
    "15. Summary"
   ],
   "id": "t30-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: many trees instead of one\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, a random forest trains many decision trees, each on a bootstrap sample (drawn with replacement) and with a few random features at every split, and averages their probabilities. Second, this works because the average of many different, overfitted trees keeps their low bias and loses most of their variance; more trees never cause overfitting. Third, the trees choose their questions with the Gini impurity, as in Topic 29, among the random features. Fourth, the out-of-bag score and the permutation importance are two honest checks that come with the forest. Fifth, bagging is the general idea behind the forest: it works around any model, and it helps unstable models such as deep trees, not stable ones such as logistic regression.\n",
    "\n",
    "The hyperparameters, the correlation of the trees and the relatives of the forest are told around these five ideas.\n",
    "\n",
    "The tenth lesson of Module 3. Topic 29 ended with the weakness of a single decision tree: it is unstable. A few different training rows can change its first question and everything below it, and a tree without limits learns the training data by heart. This lesson turns that weakness into a strength. Instead of one tree, we train many trees, each on a slightly different version of the data, and let them decide together. This is a random forest, one of the most used models for tables of data.\n",
    "\n",
    "The idea behind it has a name of its own: ensemble learning, combining many models into one. The random forest uses the simplest form of it, bagging, and the second half of the lesson shows that bagging is not only for trees: it can be put around any model.\n",
    "\n",
    "The lesson has three steps. On paper: what a random forest is and where it is used, how it builds its trees (bootstrap samples and random features), how it chooses the questions inside each tree, how it decides, and its hyperparameters. Then the project on `Bank Customer Churn Prediction.csv`, the file of Topics 27 to 29: data import, preprocessing, the random forest, its tuning and its measures. Then bagging: the same project continues with bagging around a decision tree and around logistic regression, and the scores of all models are compared.\n",
    "\n",
    "You need: decision trees, the Gini impurity and the hyperparameters of a tree (Topic 29), logistic regression (Topic 27), the measures of Topic 28, cross-validation (Topic 23), scaling and encoding (Topics 24 and 25), and a little probability (Topic 16).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| Ensemble | a model made of several models whose answers are combined |\n",
    "| Random forest | an ensemble of decision trees, each trained on a bootstrap sample and with random features at each split |\n",
    "| Bootstrap sample | a sample of the same size as the training data, drawn with replacement: some rows appear twice or more, some not at all |\n",
    "| Out-of-bag (OOB) rows | the training rows that a bootstrap sample did not draw |\n",
    "| Bagging | bootstrap aggregating: train the same model on many bootstrap samples and combine the answers |\n",
    "| Majority vote | the class that most models predict |\n",
    "| Averaging probabilities | the mean of the probabilities of all models; scikit-learn's forest decides this way |\n",
    "| `max_features` | how many features each split may choose from |\n",
    "| OOB score | the accuracy of the forest on its out-of-bag rows: a free validation score |\n",
    "| Permutation importance | how much the score drops when one feature is shuffled |\n",
    "\n",
    "## 1. What a random forest is\n",
    "\n",
    "### 1.1 Many trees instead of one\n",
    "\n",
    "Ask one person to guess the weight of an ox, and the guess may be far off. Ask 800 people and take the mean of their guesses, and the mean is often closer than almost every single guess. This is the \"wisdom of the crowd\", observed at a country fair more than a hundred years ago. It works when the people make different mistakes: some guess too high, some too low, and the errors cancel out.\n",
    "\n",
    "A random forest uses the same idea with decision trees:\n",
    "\n",
    "- It trains many trees, typically 100 or more.\n",
    "- Each tree sees a slightly different version of the training data and of the features, so the trees make different mistakes.\n",
    "- For a new customer every tree gives its answer, and the forest combines them.\n",
    "\n",
    "One deep tree overfits: it has low bias and very high variance (Topic 23). Averaging many such trees keeps the low bias and lowers the variance. That is the whole trick.\n",
    "\n",
    "### 1.2 Ensembles\n",
    "\n",
    "A model that combines several models is an ensemble. There are several families:\n",
    "\n",
    "| Family | How the models are made | How they are combined | Topic |\n",
    "| --- | --- | --- | --- |\n",
    "| Bagging | the same model on many bootstrap samples, in parallel | vote or average | this topic |\n",
    "| Random forest | bagging of trees, plus random features at every split | average of the probabilities | this topic |\n",
    "| Boosting | models trained one after another, each one correcting the mistakes of the ones before | a weighted sum | Topics 37 to 40 |\n",
    "| Voting | a few different models (a tree, a logistic regression, ...) | vote or average | Topics 35 and 36 |\n",
    "\n",
    "This lesson is about the first two.\n",
    "\n",
    "### 1.3 Where random forests are used\n",
    "\n",
    "- Banking and insurance: churn (the project of this lesson), credit risk, fraud detection.\n",
    "- Medicine: predicting a disease from many measurements, finding which measurements matter most.\n",
    "- Business: which customers will buy, how many products will be sold.\n",
    "- Science: classifying land from satellite images, finding genes linked to a disease.\n",
    "- As a strong first model: for a table of data, a random forest with its default settings is often a good model before any tuning. Many practitioners train it first, to see what is possible.\n",
    "\n",
    "### 1.4 Strengths and weaknesses\n",
    "\n",
    "| Strengths | Weaknesses |\n",
    "| --- | --- |\n",
    "| Usually much more accurate than one tree | No longer readable as a few rules: 100 trees |\n",
    "| Overfits far less than one deep tree | Slower to train and to predict than one tree, and bigger in memory |\n",
    "| Works well with default settings | Its feature importances can mislead (Part 7 shows how) |\n",
    "| No scaling needed, robust to outliers | Like every tree, it cannot predict beyond the values of the training data (regression) |\n",
    "| A free validation score: the OOB score | On some data, boosting (Topics 37 to 40) is more accurate |\n",
    "\n",
    "## 2. How a random forest works\n",
    "\n",
    "A random forest is built in three steps.\n",
    "\n",
    "The picture of the three steps is on the lesson page: the training data, 100 bootstrap samples, a tree with random features on each, and the forest that averages their probabilities.\n",
    "\n",
    "### 2.1 Step 1: a bootstrap sample for every tree\n",
    "\n",
    "Each tree gets its own bootstrap sample: as many rows as the training data has, drawn with replacement. Drawing with replacement means: a row is drawn, written down, and put back, so it can be drawn again.\n",
    "\n",
    "Take the ten customers A to J of Topic 29. One bootstrap sample of size 10 might be:\n",
    "\n",
    "| Draw | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |\n",
    "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
    "| Customer | C | A | F | C | J | F | D | I | F | H |\n",
    "\n",
    "- C appears twice and F three times.\n",
    "- B, E and G were not drawn at all. They are the out-of-bag rows of this tree.\n",
    "\n",
    "How many rows are left out? In one draw a given customer is missed with the probability 9 out of 10. In ten independent draws:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{probability of being left out} \\\\[4pt]\n",
    "&= 0.9^{10} = 0.349\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For large data the share approaches $\\frac{1}{e} = 0.368$. So every tree is trained on about 63 percent of the different rows, some of them several times, and about 37 percent of the rows are out of bag for it. Every tree sees a different mix, and every tree becomes a little different.\n",
    "\n",
    "### 2.2 Step 2: a tree with random features at every split\n",
    "\n",
    "Each tree is grown as in Topic 29, with one change. At every split the tree does not try all features. It draws a few features at random and chooses the best question among them only. In scikit-learn the default for classification is the square root of the number of features:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{features tried at a split} \\\\[4pt]\n",
    "&= \\sqrt{11} = 3.317, \\ \\text{rounded down: } 3\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "So at each node of each tree, 3 of the 11 bank features are drawn, and the best question is chosen among those 3.\n",
    "\n",
    "Why throw information away? Because otherwise all trees would look alike. In the bank data the age is the strongest feature (Topic 29): if every tree could choose it, every tree would start with the age, and 100 similar trees make the same mistakes. Hiding the strongest feature from some splits forces the trees to try other questions. The trees become less correlated, and the average of trees that disagree removes more of the variance.\n",
    "\n",
    "By default the trees of a random forest are grown without limits: deep, overfitted trees. That is intended. Each tree has a low bias and a high variance, and the averaging takes care of the variance.\n",
    "\n",
    "### 2.3 Step 3: the decision\n",
    "\n",
    "For a new customer every tree gives its answer. scikit-learn's forest takes the mean of the probabilities of all trees, and predicts the class with the larger mean.\n",
    "\n",
    "Three trees and one customer:\n",
    "\n",
    "| Tree | Probability of leaving | Its own class |\n",
    "| --- | --- | --- |\n",
    "| Tree 1 | 0.8 | leaves |\n",
    "| Tree 2 | 0.3 | stays |\n",
    "| Tree 3 | 0.6 | leaves |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{probability of the forest} \\\\[4pt]\n",
    "&= \\frac{0.8 + 0.3 + 0.6}{3} = \\frac{1.7}{3} = 0.567\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "0.567 is above 0.5: the forest predicts \"leaves\". A majority vote gives the same answer here: two of the three trees say \"leaves\". The two ways usually agree, but not always; scikit-learn uses the mean of the probabilities. When the trees are grown to pure leaves, every tree gives 0 or 1, and the mean of the probabilities is simply the share of the trees that vote \"leaves\". A forest of 100 deep trees in which 4 trees say \"leaves\" gives the probability 0.04.\n",
    "\n",
    "For a regression forest the answer is the mean of the predictions of the trees.\n",
    "\n",
    "### 2.4 Why many trees are better than one\n",
    "\n",
    "Suppose each tree is right for 70 percent of the customers, and the trees make their mistakes independently of each other. Three trees decide by majority. The majority is right when all three are right, or when exactly two are right:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{all three right:}\\quad & 0.7^3 = 0.343 \\\\[6pt]\n",
    "\\text{exactly two right:}\\quad & 3 \\times 0.7^2 \\times 0.3 \\\\[4pt]\n",
    "& = 3 \\times 0.49 \\times 0.3 = 0.441 \\\\[6pt]\n",
    "\\text{majority right:}\\quad & 0.343 + 0.441 = 0.784\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Three trees of 70 percent together reach 78.4 percent. With five trees:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& 0.7^5 + 5 \\times 0.7^4 \\times 0.3 \\\\[4pt]\n",
    "& \\quad + 10 \\times 0.7^3 \\times 0.3^2 \\\\[4pt]\n",
    "&= 0.168 + 0.360 + 0.309 = 0.837\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The picture is on the lesson page: for trees that are each right with the probability 0.7 (or 0.6), the majority of 1, 3, 5, ... 51 independent trees is right more and more often, close to 1 for 0.7.\n",
    "\n",
    "The more independent trees, the closer the majority comes to always being right. Real trees are not independent: they learn from the same data and make some of the same mistakes. That is why the forest does everything it can to make them different (bootstrap samples, random features), and why its gain is real but smaller than this picture.\n",
    "\n",
    "### 2.5 Why averaging lowers the variance\n",
    "\n",
    "The picture above assumed independent trees. A formula from statistics says what happens when they are not. Suppose every tree's prediction for a customer has the variance $\\sigma^2$ (how much it would change with another training sample), and every two trees are correlated with the correlation $\\rho$ (Topic 20). The variance of the average of $n$ trees is:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{variance of the average} \\\\[4pt]\n",
    "&= \\rho \\, \\sigma^2 + \\frac{(1 - \\rho) \\, \\sigma^2}{n}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Take $\\sigma^2 = 1$ and 100 trees:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\rho = 0:\\quad & 0 + \\frac{1}{100} = 0.01 \\\\[6pt]\n",
    "\\rho = 0.3:\\quad & 0.3 + \\frac{0.7}{100} = 0.307 \\\\[6pt]\n",
    "\\rho = 1:\\quad & 1 + \\frac{0}{100} = 1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Three lessons are in this formula:\n",
    "\n",
    "- More trees shrink only the second part, $\\frac{(1 - \\rho)\\,\\sigma^2}{n}$. With 100 trees it is already tiny, which is why the scores flatten after some hundred trees.\n",
    "- The first part, $\\rho \\times \\sigma^2$, does not shrink with more trees. Only less correlated trees make it smaller. This is the job of the bootstrap samples and, above all, of the random features.\n",
    "- If all trees were the same ($\\rho = 1$), a forest would be exactly as good as one tree.\n",
    "\n",
    "Part 9 measures the correlation of the trees on the bank data: about 0.3 for the random forest, more for plain bagged trees.\n",
    "\n",
    "### 2.6 Bias and variance of a forest\n",
    "\n",
    "In the language of Topic 23:\n",
    "\n",
    "- Bias: a forest has about the bias of one deep tree, which is low. (A little higher, because each tree sees only a bootstrap sample and a few features at each split.)\n",
    "- Variance: much lower than that of one tree, by the formula above.\n",
    "\n",
    "So a forest keeps what is good about deep trees (they can learn complicated patterns) and removes most of what is bad (they change with every training sample).\n",
    "\n",
    "## 3. How the trees choose their questions\n",
    "\n",
    "### 3.1 The same scores as one tree\n",
    "\n",
    "Inside a forest every tree is an ordinary decision tree (Topic 29). At each node it measures how mixed the classes are with the Gini impurity (the default, `criterion=\"gini\"`) or the entropy (`criterion=\"entropy\"`), and takes the split with the lowest weighted impurity:\n",
    "\n",
    "$$\n",
    "\\text{Gini} = 1 - p^2 - (1 - p)^2\n",
    "$$\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",
    "Only two things differ from a single tree: the rows of a tree are its bootstrap sample, and the candidates at each split are the few random features.\n",
    "\n",
    "### 3.2 An example with the ten customers\n",
    "\n",
    "Topic 29 computed the Gini after each question for the ten customers:\n",
    "\n",
    "| Question | Gini after the split |\n",
    "| --- | --- |\n",
    "| Over 50? | 0.317 |\n",
    "| Active member? | 0.40 |\n",
    "| Two or more products? | 0.45 |\n",
    "\n",
    "A single tree tries all three and chooses \"Over 50?\". Now let each split of a forest see only 2 of the 3 questions:\n",
    "\n",
    "- A tree that draws \"Over 50?\" and \"Two or more products?\" chooses \"Over 50?\" (0.317 against 0.45).\n",
    "- A tree that draws \"Over 50?\" and \"Active member?\" also chooses \"Over 50?\".\n",
    "- A tree that draws \"Active member?\" and \"Two or more products?\" cannot see the age. It chooses \"Active member?\" (0.40 against 0.45) and grows a different tree.\n",
    "\n",
    "The strongest question still wins most of the time, but not always. Over 100 trees this gives a variety of trees that all make sense.\n",
    "\n",
    "### 3.3 Feature importance in a forest\n",
    "\n",
    "The feature importance of a forest is the importance of Topic 29 (how much a feature lowered the impurity), averaged over all trees. It is quick, because it comes from training. But it has a known weakness: features with many different values, such as a salary in euros, offer many thresholds, and deep trees use them to split off small groups of training rows, even when they say nothing about the target. Such features get too much importance.\n",
    "\n",
    "A second measure checks this on the test data: the permutation importance. Shuffle one column of the test data, so that its values no longer belong to their customers, and measure how much the score falls. A feature the model really uses makes the score fall; a useless feature changes nothing. Part 7 compares the two on the bank data.\n",
    "\n",
    "## 4. The hyperparameters of a random forest\n",
    "\n",
    "`RandomForestClassifier` has the hyperparameters of a decision tree (Topic 29), which now apply to every tree, and a few of its own.\n",
    "\n",
    "### 4.1 The forest's own hyperparameters\n",
    "\n",
    "| Hyperparameter | Default | Role |\n",
    "| --- | --- | --- |\n",
    "| `n_estimators` | `100` | the number of trees. More trees: a more stable average, never more overfitting, but slower. The gain flattens after some hundred trees. |\n",
    "| `max_features` | `\"sqrt\"` | how many features each split may choose from: `\"sqrt\"` (the square root of the number of features), `\"log2\"`, a number, a share such as `0.5`, or `None` (all features: then the forest is bagging of trees). Smaller: more different trees. |\n",
    "| `bootstrap` | `True` | whether every tree gets a bootstrap sample. With `False` every tree sees all rows, and only the random features make the trees differ. |\n",
    "| `max_samples` | `None` | the size of each bootstrap sample (a number or a share). `None`: as many rows as the training data. |\n",
    "| `oob_score` | `False` | with `True` the forest scores itself on its out-of-bag rows: `oob_score_`. |\n",
    "| `n_jobs` | `None` | how many processor cores train the trees at the same time; `-1` uses all of them. The trees do not depend on each other, so they can be trained in parallel. |\n",
    "| `random_state` | `None` | the seed for all random choices (samples and features): the same forest at every run. |\n",
    "| `class_weight` | `None` | `\"balanced\"` gives the rare class more weight, as in Topics 27 and 29; `\"balanced_subsample\"` does the same inside each bootstrap sample. |\n",
    "\n",
    "### 4.2 The hyperparameters of every tree\n",
    "\n",
    "| Hyperparameter | Default | Role in a forest |\n",
    "| --- | --- | --- |\n",
    "| `criterion` | `\"gini\"` | the impurity measure of every tree: `\"gini\"` or `\"entropy\"` |\n",
    "| `max_depth` | `None` | the depth of every tree. The default grows full trees; a limit makes every tree simpler and the forest faster. |\n",
    "| `min_samples_split` | `2` | the smallest node that may still be split |\n",
    "| `min_samples_leaf` | `1` | the smallest leaf; larger leaves give smoother probabilities |\n",
    "| `max_leaf_nodes` | `None` | the largest number of leaves of every tree |\n",
    "| `min_impurity_decrease` | `0.0` | a split must lower the impurity at least this much |\n",
    "| `ccp_alpha` | `0.0` | cost-complexity pruning of every tree |\n",
    "\n",
    "### 4.3 Which ones matter most\n",
    "\n",
    "- `n_estimators`: more is better until the curve flattens; it is limited by time, not by overfitting. 100 to 500 is common.\n",
    "- `max_features`: the heart of the random forest. Smaller values make the trees more different; `None` turns the forest into bagging of trees.\n",
    "- `max_depth` and `min_samples_leaf`: the trees of a forest may overfit alone, but a limit can still help the forest a little, makes it faster, and smooths its probabilities.\n",
    "- `class_weight`: when the recall of the rare class matters (Topic 28).\n",
    "\n",
    "They are chosen as before: with cross-validation on the training data (Topic 23), or with the OOB score. Searching several hyperparameters at once is the subject of Topic 42.\n",
    "\n",
    "### 4.4 Is a random forest safe from overfitting?\n",
    "\n",
    "It is often said that a random forest \"cannot overfit\". That is half true:\n",
    "\n",
    "- Adding trees never makes it overfit. More trees only lower the second part of the variance formula. The test score with 1,000 trees is not worse than with 100; it only took longer.\n",
    "- The trees themselves can still learn noise. With full trees every leaf holds a single training row or a few, and the forest knows its training customers by heart: a training accuracy of 1.0 against 0.867 on the test data (Part 7). The gap is real overfitting. It is harmless as long as the test score is good, but it means that a forest must never be judged on its training data.\n",
    "- Its probabilities can be too sure. Deep trees give 0 or 1, and on noisy data the forest's probabilities become rough. Larger leaves (`min_samples_leaf`) or a limited depth (`max_depth`) smooth them, and on the bank data they raise the AUC (Part 8).\n",
    "\n",
    "So a forest is robust: hard to spoil by its main setting, and good with the defaults. It is not immune: its trees are tuned with `max_depth`, `min_samples_leaf` and `max_features`, and it is judged on the OOB rows or the test data.\n",
    "\n",
    "### 4.5 Random forests for regression\n",
    "\n",
    "Everything in this lesson also works for a number as the target, and Topic 31 is about it: `RandomForestRegressor` (and `BaggingRegressor`) average the predictions of their trees, and each tree chooses its questions by the squared error (Topic 29). The hyperparameters are the same; the default `max_features` of the regressor is `1.0` (all features).\n",
    "\n",
    "## 5. Preprocessing for forests, and for the models still to come\n",
    "\n",
    "Topic 29 explained why trees need less preprocessing than other models. A forest is made of trees, so the same holds:\n",
    "\n",
    "- Scaling: not needed. Every tree only asks whether a value is above a threshold.\n",
    "- Encoding: still needed. scikit-learn's forests accept only numbers. A number whose effect is not in order, such as `products_number`, can stay a number.\n",
    "- Outliers in the features: no harm, for the same reason as in a tree.\n",
    "- Missing values: recent versions of scikit-learn let forests work with them, as single trees can; in this course they are still looked at and filled on purpose (Topic 11).\n",
    "- Unbalanced classes: `class_weight=\"balanced\"` or `\"balanced_subsample\"`; Topic 41 goes further.\n",
    "\n",
    "Bagging is different: it can be put around any model, and then the model inside decides what preprocessing is needed. Bagging around logistic regression needs scaled features, because logistic regression needs them (Topic 27). Part 9 does exactly that.\n",
    "\n",
    "| Model (topic) | Scaling | Encoding of text | Outliers in the features |\n",
    "| --- | --- | --- | --- |\n",
    "| Linear and logistic regression (22, 26, 27) | needed | needed | sensitive |\n",
    "| Decision tree (29) | not needed | needed | robust |\n",
    "| Random forest, bagged trees (30, 31) | not needed | needed | robust |\n",
    "| Bagging around another model (30, 31) | as the model inside | as the model inside | as the model inside |\n",
    "| k-nearest neighbours (32, 33) | essential: distances | needed | sensitive |\n",
    "| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive |\n",
    "| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust |\n",
    "| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive |\n",
    "\n",
    "Topic 42 will put the preprocessing and the model into one object, so that the right steps always run in the right order.\n",
    "\n",
    "## 6. The project: from the file to the data for the forest\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",
    "### 6.1 Step 1: read and look"
   ],
   "id": "t30-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": "t30-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10,000 rows and 12 columns: 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",
    "### 6.2 Step 2: check"
   ],
   "id": "t30-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": "t30-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No missing values, no repeated rows. Two text columns: `country` and `gender`.\n",
    "\n",
    "### 6.3 Step 3: drop what carries no information"
   ],
   "id": "t30-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t30-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An identification number says nothing about a customer. A forest of deep trees would even use it to separate single training customers: noise.\n",
    "\n",
    "### 6.4 Step 4: the target"
   ],
   "id": "t30-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"churn\"].value_counts())\n",
    "print(round(df[\"churn\"].mean(), 4))"
   ],
   "id": "t30-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "About 20 percent of the customers left: the classes are unbalanced, and the measures of Topic 28 will judge the models.\n",
    "\n",
    "### 6.5 Step 5: outliers"
   ],
   "id": "t30-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": "t30-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "359 customers are older than the upper limit of the IQR rule (Topic 25). They are real customers, and the trees of a forest only compare the age with thresholds. They stay.\n",
    "\n",
    "### 6.6 Step 6: encode"
   ],
   "id": "t30-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": "t30-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`gender` becomes 0 and 1, `country` gets one-hot encoding, and `products_number` stays a number: the trees split it where they need to (Topic 29).\n",
    "\n",
    "### 6.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": "t30-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": "t30-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "8,000 customers for training and 2,000 for the test, the same customers as in Topics 27 to 29, so all results can be compared.\n",
    "\n",
    "### 6.8 Step 8: no scaling\n",
    "\n",
    "A forest needs no scaling. The features stay as they are. (Part 9 will scale them for logistic regression, which needs it.)\n",
    "\n",
    "## 7. The random forest\n",
    "\n",
    "### 7.1 Train and judge\n",
    "\n",
    "Change it and run: write `RandomForestClassifier(n_estimators=10, random_state=42)` and run: ten trees are already far better than one tree."
   ],
   "id": "t30-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "forest = RandomForestClassifier(random_state=42)\n",
    "forest.fit(X_train, y_train)\n",
    "\n",
    "print(forest.score(X_train, y_train))\n",
    "print(round(forest.score(X_test, y_test), 4))"
   ],
   "id": "t30-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`RandomForestClassifier` lives in `sklearn.ensemble`, the part of scikit-learn for ensembles. With its default settings (100 full trees) the forest is right for every training customer, like a single full tree, but on the test data it reaches 0.867: far above the full tree of Topic 29 (0.7845) and above the tuned tree (0.8575).\n",
    "\n",
    "A training accuracy of 1.0 is no alarm for a forest: its trees are meant to be deep. What counts is the test score.\n",
    "\n",
    "### 7.2 Inside the forest"
   ],
   "id": "t30-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(forest.estimators_))\n",
    "print([tree.get_depth() for tree in forest.estimators_[:5]])"
   ],
   "id": "t30-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`estimators_` is the list of the 100 trained trees, each an ordinary `DecisionTreeClassifier`. The first five are between 21 and 26 levels deep: full trees, each different because of its bootstrap sample and its random features.\n",
    "\n",
    "### 7.3 How the forest decides for one customer\n",
    "\n",
    "Change it and run: change `iloc[[0]]` to `iloc[[5]]` and count the votes for another customer."
   ],
   "id": "t30-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer = X_test.iloc[[0]]\n",
    "\n",
    "votes = [tree.predict(customer.values)[0] for tree in forest.estimators_]\n",
    "\n",
    "print(sum(votes))\n",
    "print(forest.predict_proba(customer))\n",
    "print(forest.predict(customer))"
   ],
   "id": "t30-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The list `votes` holds the answer of each of the 100 trees for the first test customer (`.values` passes the plain numbers: the trees inside the forest were trained without the column names). 4 of the 100 trees say \"leaves\". Each full tree gives the probability 0 or 1, so the mean of the probabilities is 4 out of 100: `predict_proba` says 0.04, and the forest predicts 0, \"stays\".\n",
    "\n",
    "### 7.4 The measures of Topic 28"
   ],
   "id": "t30-021"
  },
  {
   "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 = forest.predict(X_test)\n",
    "leaving = forest.predict_proba(X_test)[:, 1]\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))\n",
    "print(round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t30-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Measure | Full tree (Topic 29) | Tree with `max_depth=5` (Topic 29) | Random forest |\n",
    "| --- | --- | --- | --- |\n",
    "| Accuracy | 0.7845 | 0.8575 | 0.867 |\n",
    "| Precision | 0.4562 | 0.7647 | 0.7613 |\n",
    "| Recall | 0.5038 | 0.3969 | 0.4707 |\n",
    "| F1-score | 0.4788 | 0.5226 | 0.5818 |\n",
    "| AUC | 0.6785 | 0.8328 | 0.856 |\n",
    "\n",
    "The forest wins on almost every measure. The full trees inside it overfit one by one, but their average does not: its AUC is 0.856 against 0.6785 for one full tree. Averaging 100 probabilities of 0 or 1 gives 101 possible probabilities, so the forest can rank the customers, which a single full tree could not.\n",
    "\n",
    "### 7.5 Feature importances"
   ],
   "id": "t30-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "importances = pd.Series(forest.feature_importances_, index=X.columns)\n",
    "\n",
    "print(importances.sort_values(ascending=False).round(3))"
   ],
   "id": "t30-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The age leads again. But the estimated salary and the credit score come next, before the number of products and the activity, which decided the tree of Topic 29. Is the salary really so important?\n",
    "\n",
    "Change it and run: change `n_repeats=5` to `n_repeats=10` and run: the order of the features stays the same."
   ],
   "id": "t30-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.inspection import permutation_importance\n",
    "\n",
    "result = permutation_importance(forest, X_test, y_test, n_repeats=5, random_state=42)\n",
    "permuted = pd.Series(result.importances_mean, index=X.columns)\n",
    "\n",
    "print(permuted.sort_values(ascending=False).round(4))"
   ],
   "id": "t30-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`permutation_importance` shuffles each column of the test data 5 times (`n_repeats=5`) and reports how much the accuracy falls on average. The picture changes: the age, the number of products and the activity matter most, and the estimated salary is at the bottom with a value just below 0, which means shuffling it does not hurt at all. Its high impurity importance came from the many thresholds a column of euros offers: the deep trees used it to split off small groups of training customers."
   ],
   "id": "t30-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "permuted.sort_values().plot(kind=\"barh\")\n",
    "plt.title(\"Permutation importance of the forest on the test data\")\n",
    "plt.xlabel(\"drop of the accuracy when the column is shuffled\")\n",
    "plt.show()"
   ],
   "id": "t30-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Rule: the impurity importance is a quick first look; to decide which features a forest really uses, check it with the permutation importance on the test data.\n",
    "\n",
    "## 8. Tuning the forest\n",
    "\n",
    "### 8.1 `n_estimators`: how many trees?"
   ],
   "id": "t30-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in [1, 5, 10, 50, 100, 200]:\n",
    "    model = RandomForestClassifier(n_estimators=n, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    leaving = model.predict_proba(X_test)[:, 1]\n",
    "    print(n, round(model.score(X_test, y_test), 4), round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t30-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the number of trees, the test accuracy and the test AUC.\n",
    "\n",
    "- One tree is about as good as the single full tree of Topic 29, a little worse even, because it saw only a bootstrap sample.\n",
    "- From 1 to 50 trees the scores rise steeply, then they flatten: 100 and 200 trees give almost the same.\n",
    "- More trees never make the forest overfit; they only cost time."
   ],
   "id": "t30-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "sizes = [1, 2, 5, 10, 20, 50, 100, 200]\n",
    "aucs = []\n",
    "\n",
    "for n in sizes:\n",
    "    model = RandomForestClassifier(n_estimators=n, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    aucs.append(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]))\n",
    "\n",
    "plt.plot(sizes, aucs, marker=\"o\")\n",
    "plt.xscale(\"log\")\n",
    "plt.xlabel(\"n_estimators (number of trees)\")\n",
    "plt.ylabel(\"test AUC\")\n",
    "plt.title(\"More trees: a rising, then flat curve\")\n",
    "plt.show()"
   ],
   "id": "t30-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`plt.xscale(\"log\")` spaces 1, 10 and 100 evenly on the horizontal axis, so that the small numbers of trees are not squeezed together.\n",
    "\n",
    "### 8.2 The out-of-bag score: a free validation\n",
    "\n",
    "Every tree has its out-of-bag rows, about a third of the training data, which it never saw. With `oob_score=True` the forest predicts each training customer only with the trees for which he was out of bag, and reports the accuracy of these predictions:\n",
    "\n",
    "Change it and run: add `n_estimators=300` and run: the OOB score comes closer to the test score."
   ],
   "id": "t30-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "oob_forest = RandomForestClassifier(oob_score=True, random_state=42)\n",
    "oob_forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(oob_forest.oob_score_, 4))\n",
    "print(round(oob_forest.score(X_test, y_test), 4))"
   ],
   "id": "t30-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The OOB accuracy, 0.8574, is close to the test accuracy, 0.867, and it was measured without the test data and without cross-validation. It comes for free with bagging.\n",
    "\n",
    "### 8.3 `max_depth`, chosen with cross-validation"
   ],
   "id": "t30-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for depth in [8, 10, 12]:\n",
    "    model = RandomForestClassifier(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": "t30-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the depth of every tree and the mean AUC of five folds on the training data. This cell trains $3 \\times 5 = 15$ forests of 100 trees each, so it takes a few seconds. A depth of 10 gives the highest mean AUC.\n",
    "\n",
    "### 8.4 `min_samples_leaf` and `max_features`"
   ],
   "id": "t30-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for leaf in [1, 5, 10, 20]:\n",
    "    model = RandomForestClassifier(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, round(model.score(X_test, y_test), 4), round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t30-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Larger leaves lower the accuracy a little and raise the AUC: the probabilities become smoother, and the customers are ranked better."
   ],
   "id": "t30-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for features in [\"sqrt\", 0.5, None]:\n",
    "    model = RandomForestClassifier(max_features=features, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    leaving = model.predict_proba(X_test)[:, 1]\n",
    "    print(features, round(model.score(X_test, y_test), 4), round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t30-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `max_features=None` every split sees all 11 features: the forest becomes plain bagging of trees, and both scores fall. The random features make the difference between bagging and a random forest, and here they help.\n",
    "\n",
    "### 8.5 The tuned forest\n",
    "\n",
    "Change it and run: change `max_depth=10` to `max_depth=8` and run."
   ],
   "id": "t30-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned = RandomForestClassifier(max_depth=10, random_state=42)\n",
    "tuned.fit(X_train, y_train)\n",
    "\n",
    "predicted = tuned.predict(X_test)\n",
    "leaving = tuned.predict_proba(X_test)[:, 1]\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "print(round(tuned.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": "t30-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The tuned forest has the highest AUC of the lesson, 0.871: of all models so far it ranks the customers best. Its accuracy and F1-score are close to those of the default forest.\n",
    "\n",
    "### 8.6 More recall: `class_weight`"
   ],
   "id": "t30-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = RandomForestClassifier(max_depth=10, 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))\n",
    "print(round(f1_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t30-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The recall rises from about 0.45 to 0.67, the precision falls, and the F1-score rises. For a bank that wants to find the customers who are about to leave (Topic 28), this is the more useful forest.\n",
    "\n",
    "## 9. Bagging: the idea behind the forest, for any model\n",
    "\n",
    "### 9.1 A random forest is bagging plus random features\n",
    "\n",
    "Bagging (bootstrap aggregating) is the first two steps of Part 2 without the random features:\n",
    "\n",
    "1. Draw many bootstrap samples of the training data.\n",
    "2. Train the same kind of model on each sample.\n",
    "3. Combine the answers: the mean of the probabilities (or a majority vote) for a classifier, the mean of the predictions for a regression.\n",
    "\n",
    "A random forest is bagging of decision trees, plus one extra: random features at every split. So:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{random forest} \\\\[4pt]\n",
    "&= \\text{bagging of decision trees} \\\\[4pt]\n",
    "&\\quad + \\text{random features at every split}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Bagging helps a model that is unstable, a model with a high variance: one that changes a lot when the training data changes a little. A full decision tree is the perfect example. A stable model, one that gives almost the same answer on every bootstrap sample, gains little: averaging 100 almost equal models gives the same model again. Logistic regression is such a model.\n",
    "\n",
    "In scikit-learn bagging is `BaggingClassifier` (and `BaggingRegressor`) from `sklearn.ensemble`. Its main hyperparameters:\n",
    "\n",
    "| Hyperparameter | Default | Role |\n",
    "| --- | --- | --- |\n",
    "| `estimator` | a decision tree | the model inside, which is trained on every sample |\n",
    "| `n_estimators` | `10` | how many models (and bootstrap samples) |\n",
    "| `max_samples` | `1.0` | the size of each sample, as a share or a number of rows |\n",
    "| `max_features` | `1.0` | the share of the features each model gets (one random set per model, not per split) |\n",
    "| `bootstrap` | `True` | draw the rows with replacement |\n",
    "| `oob_score` | `False` | the out-of-bag accuracy, as in the forest |\n",
    "| `random_state` | `None` | the seed for the samples |\n",
    "\n",
    "### 9.2 Why bootstrap samples, and not simply parts of the data?\n",
    "\n",
    "Another way to get different training sets would be to cut the 8,000 training customers into 100 parts of 80. But a tree trained on 80 customers is a weak tree: its bias is high. A bootstrap sample has as many rows as the data, so every model is about as strong as one trained on all the data, and still a little different. That is the trick of the bootstrap: different samples without smaller samples.\n",
    "\n",
    "(Drawing smaller samples without replacement also exists; it is called pasting, `BaggingClassifier(bootstrap=False, max_samples=0.5)`. Bagging with the bootstrap is the common choice.)\n",
    "\n",
    "The project continues on the same data.\n",
    "\n",
    "### 9.3 Bagging around a full decision tree"
   ],
   "id": "t30-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "full_tree = DecisionTreeClassifier(random_state=42)\n",
    "full_tree.fit(X_train, y_train)\n",
    "\n",
    "bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)\n",
    "bagged_trees.fit(X_train, y_train)\n",
    "\n",
    "print(round(full_tree.score(X_test, y_test), 4), round(bagged_trees.score(X_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, full_tree.predict_proba(X_test)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t30-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`estimator=DecisionTreeClassifier()` is the model inside. One full tree: accuracy 0.7845 and AUC 0.6785. A hundred bagged full trees: accuracy 0.8585 and AUC 0.8507. Bagging alone repairs most of the overfitting. The random forest (0.867 and 0.856) adds a little more with its random features.\n",
    "\n",
    "### 9.4 Why the forest beats bagging: less correlated trees\n",
    "\n",
    "The variance formula of Part 2 says that the forest gains over plain bagging by making its trees less correlated. This can be measured. Each tree of a forest (or of a bagging) gives a probability for every test customer; `np.corrcoef` gives the correlation of every pair of trees:"
   ],
   "id": "t30-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "forest_probs = np.array([tree.predict_proba(X_test.values)[:, 1] for tree in forest.estimators_])\n",
    "bagged_probs = np.array([tree.predict_proba(X_test.values)[:, 1] for tree in bagged_trees.estimators_])\n",
    "\n",
    "print(forest_probs.shape)"
   ],
   "id": "t30-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`forest_probs` is a table with one row for each of the 100 trees and one column for each of the 2,000 test customers."
   ],
   "id": "t30-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "forest_corr = np.corrcoef(forest_probs)\n",
    "bagged_corr = np.corrcoef(bagged_probs)\n",
    "\n",
    "print(round((forest_corr.sum() - 100) / (100 * 99), 3))\n",
    "print(round((bagged_corr.sum() - 100) / (100 * 99), 3))"
   ],
   "id": "t30-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`np.corrcoef` gives a $100 \\times 100$ table of the correlations of every pair of trees. Its diagonal holds the 100 correlations of a tree with itself, all 1; the rest are the $100 \\times 99$ pairs, so $\\frac{\\text{sum} - 100}{100 \\times 99}$ is their mean.\n",
    "\n",
    "The trees of the random forest are correlated with about 0.315, the bagged trees with about 0.378. The random features made the trees less alike, and by the formula of Part 2 the average of less alike trees has a smaller variance. That is the difference between the two models in one number.\n",
    "\n",
    "### 9.5 Bagging around a shallow tree\n",
    "\n",
    "Change it and run: change both `max_depth=5` to `max_depth=3` and run: the shallower tree gains even more from bagging."
   ],
   "id": "t30-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shallow = DecisionTreeClassifier(max_depth=5, random_state=42)\n",
    "shallow.fit(X_train, y_train)\n",
    "\n",
    "bagged_shallow = BaggingClassifier(estimator=DecisionTreeClassifier(max_depth=5), n_estimators=100, random_state=42)\n",
    "bagged_shallow.fit(X_train, y_train)\n",
    "\n",
    "print(round(shallow.score(X_test, y_test), 4), round(bagged_shallow.score(X_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, shallow.predict_proba(X_test)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, bagged_shallow.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t30-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The tuned tree of Topic 29 gains too: a little accuracy, and clearly more AUC, from 0.8328 to 0.8578. A tree of depth 5 is already more stable than a full tree, so the gain is smaller, but the averaged probabilities are much finer than the 32 probabilities of one tree.\n",
    "\n",
    "### 9.6 Bagging around logistic regression\n",
    "\n",
    "Bagging works around any classifier. Logistic regression needs scaled features (Topic 27), so the data is scaled first, with the scaler fitted on the training data:"
   ],
   "id": "t30-053"
  },
  {
   "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",
    "print(X_train_scaled.shape, X_test_scaled.shape)"
   ],
   "id": "t30-054"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "logistic = LogisticRegression()\n",
    "logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "bagged_logistic = BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)\n",
    "bagged_logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(logistic.score(X_test_scaled, y_test), 4), round(bagged_logistic.score(X_test_scaled, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, logistic.predict_proba(X_test_scaled)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, bagged_logistic.predict_proba(X_test_scaled)[:, 1]), 4))"
   ],
   "id": "t30-055"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The 100 bagged logistic regressions give almost exactly the scores of one logistic regression: 0.811 against 0.8115, and an AUC of 0.7789 against 0.7787. Each bootstrap sample gives nearly the same weights, so their average is the same model again. Bagging cures variance, and logistic regression has little of it. (This logistic regression uses the eleven features with `products_number` as a number, as the first model of Topic 27; its one-hot encoding would help it, not bagging.)\n",
    "\n",
    "### 9.7 A relative: extremely randomized trees\n",
    "\n",
    "The random forest makes its trees different with bootstrap samples and random features. Extremely randomized trees go one step further: at each split they also draw the threshold at random for each candidate feature, instead of searching for the best one, and by default they train every tree on all rows, without a bootstrap. The trees become even more different, and faster to train."
   ],
   "id": "t30-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import ExtraTreesClassifier\n",
    "\n",
    "extra = ExtraTreesClassifier(random_state=42)\n",
    "extra.fit(X_train, y_train)\n",
    "\n",
    "print(round(extra.score(X_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, extra.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t30-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On the bank data the extremely randomized trees are about as good as the random forest. It is one more model of the same family worth trying; it is used exactly as `RandomForestClassifier`, with the same hyperparameters.\n",
    "\n",
    "### 9.8 The scores of every model"
   ],
   "id": "t30-058"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = [\n",
    "    (\"full tree\", full_tree, X_test),\n",
    "    (\"tree, max_depth=5\", shallow, X_test),\n",
    "    (\"bagged full trees\", bagged_trees, X_test),\n",
    "    (\"bagged trees, max_depth=5\", bagged_shallow, X_test),\n",
    "    (\"random forest\", forest, X_test),\n",
    "    (\"tuned random forest\", tuned, X_test),\n",
    "    (\"logistic regression\", logistic, X_test_scaled),\n",
    "    (\"bagged logistic regression\", bagged_logistic, X_test_scaled),\n",
    "]\n",
    "\n",
    "for name, model, X_part in models:\n",
    "    predicted = model.predict(X_part)\n",
    "    leaving = model.predict_proba(X_part)[:, 1]\n",
    "    print(name, round(f1_score(y_test, predicted), 4), round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t30-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a model, its F1-score and its AUC on the same 2,000 test customers. The list holds, for each model, its name, the model and the test data it needs: the scaled data for logistic regression, the plain data for the trees."
   ],
   "id": "t30-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "names = [name for name, model, X_part in models]\n",
    "aucs = [roc_auc_score(y_test, model.predict_proba(X_part)[:, 1]) for name, model, X_part in models]\n",
    "\n",
    "plt.barh(names, aucs)\n",
    "plt.xlim(0.6, 0.9)\n",
    "plt.xlabel(\"test AUC\")\n",
    "plt.title(\"Single models, bagged models and random forests\")\n",
    "plt.show()"
   ],
   "id": "t30-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What the comparison shows:\n",
    "\n",
    "- Bagging lifts the unstable full tree from the worst model to one of the best.\n",
    "- Bagging helps the shallow tree too, less strongly.\n",
    "- Bagging does nothing for the stable logistic regression.\n",
    "- The random forest, bagging plus random features, is the best of all, and the tuned forest leads.\n",
    "\n",
    "## 10. 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 | real customers, kept |\n",
    "| 6. Encode | text to numbers | `gender` 0 and 1, `country` one-hot, `products_number` a number |\n",
    "| 7. Split | training and test data | 8,000 and 2,000 |\n",
    "| 8. Scale | only for the models that need it | not for the forest; for logistic regression and its bagging |\n",
    "| 9. Model | the random forest | default: accuracy 0.867, AUC 0.856 |\n",
    "| 10. Look inside | trees, votes, importances | permutation importance: age, products, activity |\n",
    "| 11. Tune | `n_estimators`, `max_depth` (cross-validation), OOB score | `max_depth=10`: AUC 0.871 |\n",
    "| 12. Model again | bagging around other models | trees gain, logistic regression does not |\n",
    "| 13. Judge | the scores of every model on the same test data | the forest leads |\n",
    "\n",
    "## 11. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Worrying about a training accuracy of 1.0 in a forest. | Its trees are meant to be deep; the averaging handles the variance. | Judge the forest on the test data or with the OOB score. |\n",
    "| Thinking more trees cause overfitting. | More trees only make the average more stable. | Raise `n_estimators` until the scores flatten. |\n",
    "| Thinking a random forest cannot overfit. | Its full trees know the training rows by heart; only more trees are harmless. | Judge on OOB or test data; tune `max_depth` and `min_samples_leaf`. |\n",
    "| Scaling the features for a forest. | It changes nothing. | Scale only for models that need it. |\n",
    "| Trusting the impurity importances alone. | They favour features with many values, such as a salary. | Check with `permutation_importance` on the test data. |\n",
    "| Thinking `max_features=None` is \"the best, it uses everything\". | It removes what makes a forest different from bagging. | Keep `\"sqrt\"` or tune it. |\n",
    "| Expecting bagging to improve every model. | It cures variance; a stable model gains nothing. | Bag unstable models, such as deep trees. |\n",
    "| Bagging logistic regression on unscaled data. | The model inside still needs its preprocessing. | Scale first, as for one logistic regression. |\n",
    "| Forgetting `random_state`. | The bootstrap samples and the features change at every run. | Fix `random_state`. |\n",
    "| Confusing the bootstrap sample with a smaller sample. | It has as many rows as the data; it is drawn with replacement. | About 63 percent of the rows are in it, some several times. |\n",
    "| Choosing `max_depth` with the test data. | The test data then helps to build the model. | Cross-validation or the OOB score. |\n",
    "| Thinking a random forest can be read like one tree. | It is 100 trees. | Use importances to explain it, one tree at a time only for a look. |\n",
    "\n",
    "## 12. Solved problems\n",
    "\n",
    "The first four problems 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. A bootstrap sample\n",
    "\n",
    "From the five customers A, B, C, D, E a bootstrap sample of size 5 is drawn: B, D, B, E, B. (a) Which customers are out of bag? (b) What is the probability that a given customer is left out of a bootstrap sample of size 5?\n",
    "\n",
    "Idea. Drawing with replacement; a customer is missed in one draw with the probability 4 out of 5 (Part 2).\n",
    "\n",
    "$$\n",
    "\\text{probability of being left out} = 0.8^5 = 0.328\n",
    "$$\n",
    "\n",
    "Why: A and C were not drawn: they are out of bag. B was drawn three times. About a third of the rows is left out of every bootstrap sample.\n",
    "\n",
    "Problem 2. The decision of a forest\n",
    "\n",
    "A forest of four trees gives a customer the probabilities of leaving 0.9, 0.4, 0.7 and 0.2. What does the forest predict?\n",
    "\n",
    "Idea. scikit-learn's forest takes the mean of the probabilities (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{probability of the forest} \\\\[4pt]\n",
    "&= \\frac{0.9 + 0.4 + 0.7 + 0.2}{4} = \\frac{2.2}{4} = 0.55\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: 0.55 is above 0.5: the forest predicts \"leaves\". A majority vote would have a tie here (two trees above 0.5, two below); the mean of the probabilities decides.\n",
    "\n",
    "Problem 3. The majority of three\n",
    "\n",
    "Three independent trees are each right with the probability 0.8. How often is their majority right?\n",
    "\n",
    "Idea. The majority is right when all three or exactly two are right (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{all three right:}\\quad & 0.8^3 = 0.512 \\\\[6pt]\n",
    "\\text{exactly two right:}\\quad & 3 \\times 0.8^2 \\times 0.2 \\\\[4pt]\n",
    "& = 3 \\times 0.64 \\times 0.2 = 0.384 \\\\[6pt]\n",
    "\\text{majority right:}\\quad & 0.512 + 0.384 = 0.896\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: three trees of 80 percent make a majority of almost 90 percent, if their mistakes are independent. Random forests make their trees as different as they can for this reason.\n",
    "\n",
    "Problem 4. Features at a split\n",
    "\n",
    "A data set has 25 features. How many features does each split of a `RandomForestClassifier` try with the default `max_features=\"sqrt\"`? And with `max_features=None`?\n",
    "\n",
    "Idea. The square root of the number of features (Part 2).\n",
    "\n",
    "$$\n",
    "\\sqrt{25} = 5\n",
    "$$\n",
    "\n",
    "Why: 5 random features per split by default. With `None` every split tries all 25, and the forest becomes bagging of trees.\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 6)."
   ],
   "id": "t30-062"
  },
  {
   "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": "t30-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: nothing to fill, and one customer in five left.\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 trees (Part 6)."
   ],
   "id": "t30-064"
  },
  {
   "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": "t30-065"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: eleven features and the target. No scaling follows: a forest does not need it.\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 any model learns from the rows."
   ],
   "id": "t30-066"
  },
  {
   "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": "t30-067"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 7,500 customers to learn from and 2,500 to judge with.\n",
    "\n",
    "Problem 8. A random forest\n",
    "\n",
    "Train a `RandomForestClassifier` with `random_state=42`. Print its training accuracy and its test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. The default forest of Part 7."
   ],
   "id": "t30-068"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "forest = RandomForestClassifier(random_state=42)\n",
    "forest.fit(X_train, y_train)\n",
    "\n",
    "print(forest.score(X_train, y_train))\n",
    "print(round(forest.score(X_test, y_test), 4))"
   ],
   "id": "t30-069"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: perfect on the training data, as its full trees are, and clearly better on the test data than a single tree.\n",
    "\n",
    "Problem 9. Its measures\n",
    "\n",
    "Print the confusion matrix, the recall, the F1-score and the AUC of the forest, the last three rounded to 4 decimals.\n",
    "\n",
    "Idea. The measures of Topic 28; the AUC needs the probabilities."
   ],
   "id": "t30-070"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "predicted = forest.predict(X_test)\n",
    "leaving = forest.predict_proba(X_test)[:, 1]\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\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": "t30-071"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the forest finds almost half of the leaving customers with few false alarms, and its AUC lies far above that of a single full tree.\n",
    "\n",
    "Problem 10. The votes for one customer\n",
    "\n",
    "Count how many of the forest's trees say \"leaves\" for the first test customer, and print `predict_proba` for him.\n",
    "\n",
    "Idea. `estimators_` holds the trees; full trees give 0 or 1, so the mean of the probabilities is the share of the votes (Part 7)."
   ],
   "id": "t30-072"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer = X_test.iloc[[0]]\n",
    "\n",
    "votes = [tree.predict(customer.values)[0] for tree in forest.estimators_]\n",
    "\n",
    "print(sum(votes))\n",
    "print(forest.predict_proba(customer))"
   ],
   "id": "t30-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the number of votes divided by 100 is the second number of `predict_proba`.\n",
    "\n",
    "Problem 11. More trees\n",
    "\n",
    "For 10, 50 and 100 trees, print the number of trees and the test AUC, rounded to 4 decimals.\n",
    "\n",
    "Idea. `n_estimators` (Part 8)."
   ],
   "id": "t30-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in [10, 50, 100]:\n",
    "    model = RandomForestClassifier(n_estimators=n, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(n, round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t30-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the AUC rises steeply from 10 to 50 trees; from 50 to 100 it stays about the same and can move a little up or down. The curve flattens.\n",
    "\n",
    "Problem 12. The OOB score\n",
    "\n",
    "Train a forest with `oob_score=True` and `random_state=42`. Print its OOB score and its test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. The out-of-bag rows give a validation score without the test data (Part 8)."
   ],
   "id": "t30-076"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "oob_forest = RandomForestClassifier(oob_score=True, random_state=42)\n",
    "oob_forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(oob_forest.oob_score_, 4))\n",
    "print(round(oob_forest.score(X_test, y_test), 4))"
   ],
   "id": "t30-077"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the two numbers are close: the OOB score is an honest estimate.\n",
    "\n",
    "Problem 13. The tuned forest\n",
    "\n",
    "Train a forest with `max_depth=10` and `random_state=42`, called `tuned`. Print its test accuracy and its test AUC, rounded to 4 decimals.\n",
    "\n",
    "Idea. The depth chosen in the lesson (Part 8)."
   ],
   "id": "t30-078"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned = RandomForestClassifier(max_depth=10, random_state=42)\n",
    "tuned.fit(X_train, y_train)\n",
    "\n",
    "print(round(tuned.score(X_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t30-079"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: limiting the depth of every tree smooths the probabilities and raises the AUC a little.\n",
    "\n",
    "Problem 14. Permutation importance\n",
    "\n",
    "Compute the permutation importance of `tuned` on the test data with `n_repeats=5` and `random_state=42`. Print the three most important features, rounded to 4 decimals.\n",
    "\n",
    "Idea. Shuffle each column and measure the drop of the accuracy (Part 7)."
   ],
   "id": "t30-080"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.inspection import permutation_importance\n",
    "\n",
    "result = permutation_importance(tuned, X_test, y_test, n_repeats=5, random_state=42)\n",
    "permuted = pd.Series(result.importances_mean, index=X.columns)\n",
    "\n",
    "print(permuted.sort_values(ascending=False).head(3).round(4))"
   ],
   "id": "t30-081"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the same three features as in the lesson: the age, the number of products and the activity.\n",
    "\n",
    "Problem 15. Bagged trees\n",
    "\n",
    "Train a single full `DecisionTreeClassifier` with `random_state=42`, and a `BaggingClassifier` of 100 full trees with `random_state=42`. Print the test AUC of each, rounded to 4 decimals.\n",
    "\n",
    "Idea. Bagging around an unstable model (Part 9)."
   ],
   "id": "t30-082"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "\n",
    "full_tree = DecisionTreeClassifier(random_state=42)\n",
    "full_tree.fit(X_train, y_train)\n",
    "\n",
    "bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)\n",
    "bagged_trees.fit(X_train, y_train)\n",
    "\n",
    "print(round(roc_auc_score(y_test, full_tree.predict_proba(X_test)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t30-083"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: one full tree ranks badly; a hundred bagged full trees rank almost as well as the forest.\n",
    "\n",
    "Problem 16. Bagged logistic regression\n",
    "\n",
    "Scale the features with a `StandardScaler` fitted on the training data. Train a `LogisticRegression` and a `BaggingClassifier` of 100 logistic regressions with `random_state=42`. Print the test AUC of each, rounded to 4 decimals.\n",
    "\n",
    "Idea. Bagging around a stable model, which needs scaled data (Part 9)."
   ],
   "id": "t30-084"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "logistic = LogisticRegression()\n",
    "logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "bagged_logistic = BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)\n",
    "bagged_logistic.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(roc_auc_score(y_test, logistic.predict_proba(X_test_scaled)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, bagged_logistic.predict_proba(X_test_scaled)[:, 1]), 4))"
   ],
   "id": "t30-085"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: almost the same number twice: bagging cannot improve a model that hardly changes from sample to sample.\n",
    "\n",
    "## 15. Summary\n",
    "\n",
    "|  | Formula or rule | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Bootstrap sample | $n$ rows drawn with replacement | about 63 percent of the rows, some several times |\n",
    "| Left out of one sample | $\\left(1 - \\tfrac{1}{n}\\right)^{n}$, about $\\frac{1}{e} = 0.368$ | the out-of-bag rows |\n",
    "| Features per split | $\\sqrt{p}$ by default | random, for every split |\n",
    "| The forest's probability | the mean of the trees' probabilities | the class with the larger mean |\n",
    "| Majority of three, each right with $p$ | $p^3 + 3 \\times p^2 \\times (1 - p)$ | higher than $p$ if $p > 0.5$ and the mistakes are independent |\n",
    "| Variance of an average of $n$ models | $\\rho \\, \\sigma^2 + \\frac{(1 - \\rho)\\,\\sigma^2}{n}$ | more models shrink only the second part; less correlation shrinks the first |\n",
    "| Random forest | bagging of trees + random features | less correlated trees, less variance |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `RandomForestClassifier(random_state=42)` | a forest of 100 full trees |\n",
    "| `n_estimators`, `max_features`, `max_depth`, `min_samples_leaf` | the most used hyperparameters |\n",
    "| `oob_score=True`, then `oob_score_` | the out-of-bag accuracy |\n",
    "| `class_weight=\"balanced\"` | more weight for the rare class |\n",
    "| `forest.estimators_` | the list of the trees |\n",
    "| `forest.feature_importances_` | the impurity importance, averaged over the trees |\n",
    "| `permutation_importance(model, X_test, y_test, n_repeats=5)` | the drop of the score when a column is shuffled |\n",
    "| `BaggingClassifier(estimator=..., n_estimators=100)` | bagging around any model |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. A random forest is many deep trees, each on a bootstrap sample and with random features at every split; it averages their probabilities.\n",
    "2. Each tree chooses its questions with the Gini impurity or the entropy, among a few random features.\n",
    "3. More trees never overfit; they only cost time. Tune `max_features`, `max_depth` and `min_samples_leaf`.\n",
    "4. The OOB score is a free validation; the test data judges the finished model.\n",
    "5. Check the impurity importances with the permutation importance.\n",
    "6. Bagging works around any model and cures variance: it helps deep trees a lot and stable models hardly at all.\n",
    "7. No scaling for forests and bagged trees; the model inside a bagging decides its own preprocessing.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "The forests of this lesson predicted a class. Topic 31 uses the same ideas, random forests and bagging, for a number as the target, with the measures of regression. Then Topic 32 brings a model that works in a completely different way: k-nearest neighbours, which looks at the most similar customers. It needs distances, so scaling becomes essential again. Naive Bayes, which calculates probabilities with Bayes' rule (Topic 16), follows in Topic 34.\n",
    "\n",
    "Next: the practice notebook (topic-30-practice.ipynb), then Topic 31: Random Forests and ensemble learning (bagging) - Regression."
   ],
   "id": "t30-086"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
