{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 31: Random Forests and ensemble learning (bagging) - Regression\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 16, 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-31-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 that starts from the raw file, 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 several 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 car_prices.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. From a class to a number\n",
    "2. How a regression tree chooses its questions\n",
    "3. How a regression forest predicts\n",
    "4. The hyperparameters of RandomForestRegressor\n",
    "5. Measures and preprocessing\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 around any regression model\n",
    "10. The workflow, step by step\n",
    "11. Common mistakes\n",
    "12. Solved problems\n",
    "13. Practice (in topic-31-practice.ipynb)\n",
    "14. Check yourself (on the website)\n",
    "15. Summary"
   ],
   "id": "t31-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: from a class to a number\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, a regression forest is built exactly like the forest of Topic 30 (bootstrap samples, random features, deep trees), but its trees choose their questions with the squared error, their leaves predict means, and the forest predicts the mean of its trees. Second, a forest can never predict a value outside the range of its training values. Third, a regression model is judged with R², MAE and RMSE, and the out-of-bag R² chooses the hyperparameters without the test data. Fourth, the default `RandomForestRegressor` uses all features at every split, so it is plain bagging of trees: `max_features` is the first thing to tune. Fifth, real data needs real preprocessing before any model: repeated rows, impossible values, missing values, outliers and categories are all handled here, from the raw file on.\n",
    "\n",
    "The ideas that are exactly the same as in Topic 30 are only recalled, with the place where Topic 30 explains them.\n",
    "\n",
    "The eleventh lesson of Module 3. Topic 30 built random forests and bagging for a class: will a customer leave the bank or not? This lesson uses the same two methods for a number: the price of a car. Most of the ideas are exactly the same, and Topic 30 explains them in full; this lesson repeats them in one or two sentences and points to the place in Topic 30. The time goes to what is new when the target is a number:\n",
    "\n",
    "- how a regression tree chooses its questions (the squared error instead of the Gini impurity), and what its leaves predict;\n",
    "- how a regression forest makes its prediction (the mean of the trees), and what it cannot do (predict a price higher than every training price);\n",
    "- the measures of regression from Topic 22: R², MAE and RMSE;\n",
    "- the default `max_features` of `RandomForestRegressor`, which makes the default forest plain bagging of trees;\n",
    "- a new data file with real problems: repeated rows, impossible values, missing values and a column with hundreds of categories.\n",
    "\n",
    "The lesson has three steps, as Topic 30. On paper: what changes from classification to regression, how a regression tree chooses its splits (worked by hand), how the forest predicts, the hyperparameters and the measures. Then the project on `car_prices.csv`: 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 linear regression, and the scores of all models are compared.\n",
    "\n",
    "You need: random forests and bagging (Topic 30), decision trees (Topic 29), linear regression and the measures R², MAE and RMSE (Topic 22), the train/test split and cross-validation (Topic 23), encoding (Topic 25), and the cleaning of Topic 11 (missing values and repeated rows).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| Regression forest | a random forest whose target is a number; it predicts the mean of its trees |\n",
    "| Regression tree | a decision tree whose leaves predict a number: the mean of the training rows in the leaf |\n",
    "| Squared error of a node | the mean of the squared distances of the prices in a node from their mean (the variance of the node) |\n",
    "| R² | the share of the variance of the target that the model explains; 1 is perfect, 0 is as good as always predicting the mean |\n",
    "| MAE | mean absolute error: the typical error, in the unit of the target (manats) |\n",
    "| RMSE | root mean squared error: also in manats, but large errors count more |\n",
    "| OOB R² | the R² of the forest on its out-of-bag rows: a free validation score |\n",
    "| Extrapolation | predicting outside the range of the training data; a forest cannot do it |\n",
    "| `BaggingRegressor` | bagging around any regression model |\n",
    "\n",
    "## 1. From a class to a number\n",
    "\n",
    "### 1.1 What stays the same\n",
    "\n",
    "Everything that makes a random forest a random forest is the same as in Topic 30:\n",
    "\n",
    "| Idea | In short | Where in Topic 30 |\n",
    "| --- | --- | --- |\n",
    "| Bootstrap sample | every tree gets as many rows as the training data, drawn with replacement | Part 2, Step 1 |\n",
    "| Out-of-bag rows | about 37 percent of the rows are not in a tree's sample | Part 2, Step 1 |\n",
    "| Random features | at every split a tree chooses among a few random features (`max_features`) | Part 2, Step 2 |\n",
    "| Deep trees | the trees are grown without limits by default; the averaging takes care of their variance | Part 2, Step 2 |\n",
    "| Why many trees help | different trees make different mistakes, and the mistakes cancel in the average | Part 2 |\n",
    "| Variance of an average | $\\rho \\, \\sigma^2 + \\frac{(1 - \\rho)\\,\\sigma^2}{n}$: more trees shrink the second part, less correlated trees the first | Part 2 |\n",
    "| More trees never overfit | they only make the average more stable, and cost time | Part 4 |\n",
    "| Bagging | the same model on many bootstrap samples, the answers combined; it works around any model | Part 9 |\n",
    "| Bagging cures variance | it helps unstable models (deep trees) and hardly changes stable ones | Part 9 |\n",
    "| Extremely randomized trees | random thresholds as well as random features | Part 9 |\n",
    "\n",
    "If one of these is not clear, read its place in Topic 30 first: this lesson uses all of them.\n",
    "\n",
    "### 1.2 What changes\n",
    "\n",
    "|  | Classification (Topic 30) | Regression (this topic) |\n",
    "| --- | --- | --- |\n",
    "| Target | a class: leaves (1) or stays (0) | a number: the price of a car in manats (AZN) |\n",
    "| A tree chooses its split by | the Gini impurity or the entropy | the squared error |\n",
    "| A leaf predicts | the share of each class in the leaf | the mean of the target in the leaf |\n",
    "| The forest predicts | the mean of the trees' probabilities | the mean of the trees' predictions |\n",
    "| Measures | accuracy, precision, recall, F1, AUC (Topic 28) | R², MAE, RMSE (Topic 22) |\n",
    "| Default `max_features` | `\"sqrt\"`: the square root of the number of features | `1.0`: all features |\n",
    "| `oob_score_` holds | the out-of-bag accuracy | the out-of-bag R² |\n",
    "| `class_weight` | for unbalanced classes | does not exist: there are no classes |\n",
    "| In scikit-learn | `RandomForestClassifier`, `BaggingClassifier` | `RandomForestRegressor`, `BaggingRegressor` |\n",
    "\n",
    "### 1.3 Where regression forests are used\n",
    "\n",
    "- Prices: cars (the project of this lesson), flats and houses, insurance premiums.\n",
    "- Demand: how many products a shop will sell next week, how many taxis a city needs at 8 a.m.\n",
    "- Energy: the electricity a building will use tomorrow, the power of a wind farm.\n",
    "- Medicine: how many days a patient will stay in hospital.\n",
    "- Science: the yield of a field from soil and weather measurements.\n",
    "- As a strong first model: as for classes, a random forest with its default settings is a good first try for any table of data with a numerical target.\n",
    "\n",
    "## 2. How a regression tree chooses its questions\n",
    "\n",
    "### 2.1 The squared error of a node\n",
    "\n",
    "A regression tree asks the same kind of questions as the trees of Topic 29 (\"year ≤ 2015.5?\"), but it needs a different measure of a good split. There are no classes to be pure. Instead, a good group is a group of cars whose prices are close to each other.\n",
    "\n",
    "The tree measures this with the squared error of a node: the mean of the squared distances of the prices from their mean.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{squared error of a node} \\\\[4pt]\n",
    "&= \\text{mean of } (\\text{price} - \\text{mean price})^2\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "This is the variance of the prices in the node (Topic 18). A node with similar prices has a small squared error; a node that mixes cheap and expensive cars has a large one.\n",
    "\n",
    "A leaf predicts the mean of the prices of its training cars. The mean is the one number with the smallest squared error to a group of numbers, so the leaf's prediction and the tree's measure fit together.\n",
    "\n",
    "Like a classification tree, the tree tries every feature and every threshold, and takes the split with the lowest weighted squared error of the two groups:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{error after the split} \\\\[4pt]\n",
    "&= \\frac{n_{\\text{left}}}{n} \\times \\text{error}_{\\text{left}} \\\\[4pt]\n",
    "&\\quad + \\frac{n_{\\text{right}}}{n} \\times \\text{error}_{\\text{right}}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 2.2 An example with six cars\n",
    "\n",
    "Six cars, their years and their prices in thousands of manats:\n",
    "\n",
    "| Car | A | B | C | D | E | F |\n",
    "| --- | --- | --- | --- | --- | --- | --- |\n",
    "| Year | 2008 | 2011 | 2014 | 2017 | 2019 | 2022 |\n",
    "| Price (thousand AZN) | 8 | 10 | 12 | 24 | 28 | 32 |\n",
    "\n",
    "Before any split, the node holds all six cars:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{mean} &= \\frac{8 + 10 + 12 + 24 + 28 + 32}{6} \\\\[4pt]\n",
    "&= \\frac{114}{6} = 19 \\\\[8pt]\n",
    "\\text{squared error} &= \\frac{11^2 + 9^2 + 7^2 + 5^2 + 9^2 + 13^2}{6} \\\\[4pt]\n",
    "&= \\frac{526}{6} = 87.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The candidate thresholds lie halfway between neighbouring years, as in Topic 29: 2009.5, 2012.5, 2015.5, 2018 and 2020.5. The threshold 2015.5 puts A, B, C on the left and D, E, F on the right:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{left mean} &= \\frac{8 + 10 + 12}{3} = 10 \\\\[6pt]\n",
    "\\text{left error} &= \\frac{2^2 + 0^2 + 2^2}{3} = \\frac{8}{3} = 2.667 \\\\[10pt]\n",
    "\\text{right mean} &= \\frac{24 + 28 + 32}{3} = 28 \\\\[6pt]\n",
    "\\text{right error} &= \\frac{4^2 + 0^2 + 4^2}{3} = \\frac{32}{3} = 10.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{error after the split} \\\\[4pt]\n",
    "&= \\tfrac{3}{6} \\times 2.667 + \\tfrac{3}{6} \\times 10.667 \\\\[4pt]\n",
    "&= 1.333 + 5.333 = 6.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The threshold 2012.5 puts only A and B on the left:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{left mean} &= \\frac{8 + 10}{2} = 9 \\\\[6pt]\n",
    "\\text{left error} &= \\frac{1^2 + 1^2}{2} = 1 \\\\[10pt]\n",
    "\\text{right mean} &= \\frac{12 + 24 + 28 + 32}{4} = 24 \\\\[6pt]\n",
    "\\text{right error} &= \\frac{12^2 + 0^2 + 4^2 + 8^2}{4} \\\\[4pt]\n",
    "&= \\frac{224}{4} = 56\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{error after the split} \\\\[4pt]\n",
    "&= \\tfrac{2}{6} \\times 1 + \\tfrac{4}{6} \\times 56 \\\\[4pt]\n",
    "&= 0.333 + 37.333 = 37.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "All five thresholds:\n",
    "\n",
    "| Threshold | Left | Right | Error after the split |\n",
    "| --- | --- | --- | --- |\n",
    "| year ≤ 2009.5 | A | B, C, D, E, F | 63.467 |\n",
    "| year ≤ 2012.5 | A, B | C, D, E, F | 37.667 |\n",
    "| year ≤ 2015.5 | A, B, C | D, E, F | 6.667 |\n",
    "| year ≤ 2018 | A, B, C, D | E, F | 27.167 |\n",
    "| year ≤ 2020.5 | A, B, C, D, E | F | 53.867 |\n",
    "\n",
    "The tree chooses year ≤ 2015.5: it lowers the squared error from 87.667 to 6.667. Its two leaves predict the means: 10 thousand manats for an older car, 28 thousand for a newer one. (`DecisionTreeRegressor(max_depth=1)` finds exactly this split and these two values.)\n",
    "\n",
    "The picture is on the lesson page: the six cars as points (year against price), the dashed line at year 2015.5, and the two leaves as flat lines at their means, 10 on the left and 28 on the right.\n",
    "\n",
    "### 2.3 The other criteria\n",
    "\n",
    "`DecisionTreeRegressor` and `RandomForestRegressor` take the measure as `criterion`:\n",
    "\n",
    "| `criterion` | The node's error | The leaf predicts |\n",
    "| --- | --- | --- |\n",
    "| `\"squared_error\"` (default) | the mean squared distance from the mean | the mean |\n",
    "| `\"absolute_error\"` | the mean absolute distance from the median | the median; less moved by a few very expensive cars, but much slower |\n",
    "| `\"friedman_mse\"` | the squared error with a correction used by boosting (Topics 37 to 40) | the mean |\n",
    "| `\"poisson\"` | a measure for counts (numbers of sales, of visits) | the mean |\n",
    "\n",
    "The default is the right choice almost always, and this lesson keeps it.\n",
    "\n",
    "### 2.4 A full tree learns every price by heart\n",
    "\n",
    "A tree without limits keeps splitting until each leaf holds a single car, or cars with exactly the same features. Then a leaf \"predicts\" the price of one training car: the tree reproduces the training prices almost perfectly and has a training R² close to 1. On new cars it does much worse: one full tree overfits, exactly as in Topic 29. The project shows it with numbers (Part 9).\n",
    "\n",
    "## 3. How a regression forest predicts\n",
    "\n",
    "### 3.1 Three steps\n",
    "\n",
    "The forest is built exactly as in Topic 30; only the last step differs.\n",
    "\n",
    "The picture of the three steps is on the lesson page: the training data, 100 bootstrap samples, a tree on each that predicts a price, and the forest that takes the mean of the predictions.\n",
    "\n",
    "1. Every tree gets its own bootstrap sample of the training cars.\n",
    "2. Every tree is grown with the squared error, choosing at each split among `max_features` features.\n",
    "3. For a new car, every tree gives a price, and the forest predicts their mean.\n",
    "\n",
    "Three trees and one car:\n",
    "\n",
    "| Tree | Its prediction |\n",
    "| --- | --- |\n",
    "| Tree 1 | 18,500 AZN |\n",
    "| Tree 2 | 21,000 AZN |\n",
    "| Tree 3 | 22,600 AZN |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{prediction of the forest} \\\\[4pt]\n",
    "&= \\frac{18{,}500 + 21{,}000 + 22{,}600}{3} \\\\[4pt]\n",
    "&= \\frac{62{,}100}{3} = 20{,}700 \\text{ AZN}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "There is no vote and no threshold of 0.5: the mean of the numbers is the answer. A forest of 100 trees takes the mean of 100 prices.\n",
    "\n",
    "### 3.2 Why the mean of many trees is better\n",
    "\n",
    "Each full tree predicts the price of one or a few training cars that look like the new car: a rough guess with a large variance. Another bootstrap sample would give another guess. The mean of 100 such guesses varies much less. The formula of Topic 30 (Part 2) says how much less:\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",
    "With 100 trees the second part is tiny; the first part, the correlation $\\rho$ of the trees, is what is left, and only more different trees make it smaller. Part 8 measures $\\rho$ on the cars.\n",
    "\n",
    "### 3.3 What a forest cannot do: predict outside the training prices\n",
    "\n",
    "Every leaf predicts a mean of training prices. A mean of prices is never higher than the highest of them and never lower than the lowest. So:\n",
    "\n",
    "- No tree can predict a price higher than the most expensive training car, or lower than the cheapest.\n",
    "- The forest's prediction is a mean of such predictions, so the forest cannot either.\n",
    "\n",
    "A forest that has seen cars up to 160,000 AZN will never predict 200,000 AZN, even for a brand-new luxury car. And a car newer than all training cars gets about the price of the newest training cars. Linear regression is different: its line goes on, for better or worse.\n",
    "\n",
    "The picture is on the lesson page: 300 cars of the file (year against price), one tree with a few steps, the forest of 100 such trees with many smaller steps, and the straight line of linear regression. After the newest year of the data the tree and the forest stay flat; the line keeps rising.\n",
    "\n",
    "The picture uses only the year of 300 cars of the file. One tree predicts with a few steps; the forest of 100 such trees is a finer staircase, because every tree puts its steps in slightly different places. After the newest training year both are flat. The line of linear regression continues to rise.\n",
    "\n",
    "For car prices this is rarely a problem: new cars are rarely far outside the data. For targets that grow over time (sales that grow every year, prices with inflation) it matters, and a model that can extrapolate, or a target without the trend, is needed.\n",
    "\n",
    "## 4. The hyperparameters of `RandomForestRegressor`\n",
    "\n",
    "`RandomForestRegressor` has the hyperparameters of `RandomForestClassifier` (Topic 30, Part 4), with these differences:\n",
    "\n",
    "| Hyperparameter | Default | Role in a regression forest |\n",
    "| --- | --- | --- |\n",
    "| `n_estimators` | `100` | the number of trees. More trees: a more stable mean, never more overfitting, but slower. |\n",
    "| `criterion` | `\"squared_error\"` | the measure of every tree (Part 2) |\n",
    "| `max_features` | `1.0` | the share of the features each split may choose from. The default `1.0` means all features: then the forest is plain bagging of trees. `0.33` (a third), `0.5`, `\"sqrt\"` or a number make it a real random forest. |\n",
    "| `max_depth` | `None` | the depth of every tree; the default grows full trees |\n",
    "| `min_samples_split` | `2` | the smallest node that may still be split |\n",
    "| `min_samples_leaf` | `1` | the smallest leaf: its prediction is the mean of at least this many cars |\n",
    "| `bootstrap` | `True` | every tree gets a bootstrap sample |\n",
    "| `max_samples` | `None` | the size of each bootstrap sample; `None`: as many rows as the training data |\n",
    "| `oob_score` | `False` | with `True` the forest computes its R² on the 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 |\n",
    "| `random_state` | `None` | the seed for all random choices |\n",
    "\n",
    "There is no `class_weight`: a number has no classes to weight.\n",
    "\n",
    "### 4.1 The default `max_features` of a regression forest\n",
    "\n",
    "For classes, scikit-learn's default is `\"sqrt\"`, the random forest of Topic 30. For a number the default is `1.0`, every feature at every split. So `RandomForestRegressor()` with its default settings is bagging of full trees: only the bootstrap samples make its trees differ. The project shows that it gives practically the same scores as `BaggingRegressor` around a tree (Part 9).\n",
    "\n",
    "Why this default? On many regression data sets bagged trees are already good, and the random features add less than for classes. But they often still help. Leo Breiman, who invented random forests, suggested a third of the features for regression. Treat `max_features` as the first hyperparameter to tune: try `1.0`, `0.5`, `0.33` and `\"sqrt\"`, and compare them with the out-of-bag R² or with cross-validation.\n",
    "\n",
    "### 4.2 Is a regression forest safe from overfitting?\n",
    "\n",
    "Topic 30 (Part 4) answered this for classes, and the answer is the same for numbers:\n",
    "\n",
    "- More trees never make it overfit. They only make the mean steadier (Part 8 shows the curve).\n",
    "- Its full trees do learn the training prices by heart. The project's forest has an R² of 0.98 on the training cars and 0.865 on the test cars. The gap is real overfitting of the single trees, made harmless by the averaging; it means that a forest must never be judged on its training data.\n",
    "- The settings of the trees can still help or hurt: `max_features`, `min_samples_leaf` and `max_depth` are tuned with the out-of-bag R² or with cross-validation.\n",
    "\n",
    "So a regression forest is robust, not immune: hard to spoil with its main setting, good with the defaults, and judged on data it has not seen.\n",
    "\n",
    "### 4.3 Which ones matter most\n",
    "\n",
    "- `max_features`: as above, the first one to try.\n",
    "- `n_estimators`: more is better until the scores flatten; limited by time only.\n",
    "- `min_samples_leaf` and `max_depth`: they make every tree simpler. In Topic 30 larger leaves made the probabilities smoother and raised the AUC. For prices, a leaf of one car is often best: every limit makes the predicted prices coarser. The project checks it.\n",
    "\n",
    "They are chosen with the out-of-bag R² or with cross-validation on the training data (Topic 23), never with the test data. Searching several hyperparameters at once is the subject of Topic 42.\n",
    "\n",
    "## 5. Measures and preprocessing\n",
    "\n",
    "### 5.1 The measures of regression\n",
    "\n",
    "A regression model is judged by how far its predictions are from the true values. Topic 22 introduced the three common measures. With $n$ cars, true prices $y$, predicted prices $\\hat{y}$ and the mean price $\\bar{y}$:\n",
    "\n",
    "$$\n",
    "\\text{MAE} = \\frac{1}{n} \\sum |y - \\hat{y}|\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\text{RMSE} = \\sqrt{\\frac{1}{n} \\sum (y - \\hat{y})^2}\n",
    "$$\n",
    "\n",
    "$$\n",
    "R^2 = 1 - \\frac{\\sum (y - \\hat{y})^2}{\\sum (y - \\bar{y})^2}\n",
    "$$\n",
    "\n",
    "Four cars, prices in thousands of manats:\n",
    "\n",
    "| Car | True price $y$ | Predicted $\\hat{y}$ | Error $y - \\hat{y}$ |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | 20 | 22 | $-2$ |\n",
    "| 2 | 15 | 14 | 1 |\n",
    "| 3 | 30 | 27 | 3 |\n",
    "| 4 | 25 | 25 | 0 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{MAE} &= \\frac{2 + 1 + 3 + 0}{4} = \\frac{6}{4} = 1.5 \\\\[6pt]\n",
    "\\text{MSE} &= \\frac{4 + 1 + 9 + 0}{4} = \\frac{14}{4} = 3.5 \\\\[6pt]\n",
    "\\text{RMSE} &= \\sqrt{3.5} = 1.871\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\bar{y} &= \\frac{20 + 15 + 30 + 25}{4} = \\frac{90}{4} = 22.5 \\\\[8pt]\n",
    "\\textstyle\\sum (y - \\bar{y})^2 &= 2.5^2 + 7.5^2 + 7.5^2 + 2.5^2 \\\\[4pt]\n",
    "&= 6.25 + 56.25 + 56.25 + 6.25 \\\\[4pt]\n",
    "&= 125 \\\\[8pt]\n",
    "R^2 &= 1 - \\frac{14}{125} = 1 - 0.112 = 0.888\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "| Measure | Unit | What it says | When to look at it |\n",
    "| --- | --- | --- | --- |\n",
    "| MAE | manats | the typical error of a prediction | to tell a buyer how far off the price usually is |\n",
    "| RMSE | manats | like the MAE, but large errors count much more; always at least the MAE | when a few large mistakes are costly |\n",
    "| R² | none | the share of the variance of the prices that the model explains | to compare models on the same data; 1 is perfect |\n",
    "\n",
    "When the RMSE is much larger than the MAE, a few cars have very large errors. For car prices this is typical: an error of 10 percent on a car of 150,000 AZN is 15,000 AZN.\n",
    "\n",
    "### 5.2 Preprocessing for a regression forest, and for the models still to come\n",
    "\n",
    "Topic 29 (Part 5) and Topic 30 (Part 5) explained why trees and forests need less preprocessing. For regression it is the same, with two points that matter more now:\n",
    "\n",
    "- Scaling: not needed. Every tree only compares a value with a threshold.\n",
    "- Encoding: still needed. scikit-learn's forests accept only numbers.\n",
    "- Outliers in the features: no harm, for the same reason.\n",
    "- Outliers in the target: these do matter. The squared error and the means of the leaves are pulled by very high prices. Check whether they are real (a luxury car) or mistakes (a price typed with an extra zero). Real ones stay.\n",
    "- Impossible values: a year 0 or a mileage of three million kilometres is a mistake in the data, not an outlier. Such rows are removed or the values are set to missing.\n",
    "- Missing values: recent versions of scikit-learn let trees and forests work with them; in this course they are filled on purpose (Topic 11), with values computed from the training data only (Topic 23).\n",
    "- Repeated rows: the same row in the training and in the test data lets a forest of deep trees \"remember\" its price. They are dropped before the split (Part 6 shows why).\n",
    "- A column with hundreds of categories (here the car model, 816 values): one-hot encoding would add hundreds of columns of mostly zeros. It is dropped, or its rare values are grouped.\n",
    "\n",
    "Bagging puts its own rule on top: the model inside decides its preprocessing. Plain linear regression needs encoded and filled data. It does not need scaling: Topic 24 showed that `LinearRegression` gives the same predictions with scaled and unscaled features (Ridge and Lasso, Topic 26, do need it).\n",
    "\n",
    "| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |\n",
    "| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |\n",
    "| Decision tree (29) | not needed | needed | robust | fill (recent scikit-learn can handle them) |\n",
    "| Random forest, bagged trees (30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |\n",
    "| Bagging around another model (30, 31) | as the model inside | as the model inside | as the model inside | as the model inside |\n",
    "| k-nearest neighbours (32, 33) | essential: distances | needed | sensitive | fill |\n",
    "| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive | fill |\n",
    "| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost, LightGBM and CatBoost handle them |\n",
    "| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |\n",
    "\n",
    "## 6. The project: from the file to the data for the forest\n",
    "\n",
    "Now the data: `car_prices.csv`, 10,000 adverts of cars for sale in Azerbaijan, taken at random from a larger file of adverts. Each row is one advert: the brand and model, the year, the engine, the mileage, the gearbox, the body, the colour, and more. The column `price_azn` is the price in manats: the target.\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",
    "The file is not cleaned. It was cut from a much larger file of adverts in only three ways: 10,000 adverts were drawn at random (so that the Python of a browser can work with them), the Azerbaijani words of the adverts were translated into English, and everything about the sellers (names, phone numbers, descriptions, links) was left out. Nothing else was done: the repeated adverts, the missing values, the impossible values, the outliers and the text columns are all still in the file, exactly as the adverts had them. Every preprocessing step happens in this lesson, from the first line of code.\n",
    "\n",
    "### 6.1 Step 1: read and look"
   ],
   "id": "t31-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"car_prices.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head())"
   ],
   "id": "t31-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10,000 rows and 19 columns. The features:\n",
    "\n",
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `brand`, `model` | the make and the model of the car |\n",
    "| `year` | the year it was made |\n",
    "| `engine_l`, `horsepower` | the engine volume in litres and the power in horsepower |\n",
    "| `fuel`, `gearbox`, `drive`, `body`, `colour` | the kind of fuel, the gearbox, the driven wheels, the body type, the colour |\n",
    "| `mileage_km` | the kilometres driven |\n",
    "| `seats`, `owners` | the number of seats and of previous owners |\n",
    "| `is_new`, `damaged`, `painted` | 1 for a new car, for a car with accident damage, for a car with repainted parts |\n",
    "| `market` | the market the car was first sold in (official dealer, Europe, America, Korea, ...) |\n",
    "| `city` | where the car is sold |\n",
    "| `price_azn` | the price in manats (AZN): the target |\n",
    "\n",
    "### 6.2 Step 2: check"
   ],
   "id": "t31-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum())\n",
    "print(df.duplicated().sum())"
   ],
   "id": "t31-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Four columns have missing values: `horsepower`, `seats`, `owners` and `market`. And 691 rows are exact copies of another row: the same car, advertised twice.\n",
    "\n",
    "### 6.3 Step 3: drop the repeated rows\n",
    "\n",
    "Change it and run: remove the line `df = df.drop_duplicates()` and run the cell `check` again in your head: the 691 copies would stay in the data."
   ],
   "id": "t31-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop_duplicates()\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t31-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`drop_duplicates()` keeps the first of each group of equal rows (Topic 11). This step matters more than it looks. If an advert is in the data twice, the split may put one copy into the training data and the other into the test data. A forest of deep trees has learned the training copy's price exactly, so it \"predicts\" the test copy perfectly, and the test score looks better than it is. On this file, the same steps without `drop_duplicates()` give a test R² of 0.907 instead of 0.865: the difference is a lie told by the repeated adverts.\n",
    "\n",
    "### 6.4 Step 4: impossible values"
   ],
   "id": "t31-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"year\", \"engine_l\", \"mileage_km\", \"price_azn\"]].describe().round(1))"
   ],
   "id": "t31-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`describe()` shows the smallest and the largest value of each column. Two things are impossible: a car made in the year 0, and a mileage of more than three million kilometres (a car that drove 200 kilometres every day for 40 years would reach 2.9 million). These are mistakes in the adverts. An engine of 0 litres is not a mistake:"
   ],
   "id": "t31-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.loc[df[\"engine_l\"] == 0, \"fuel\"].value_counts())"
   ],
   "id": "t31-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Electric cars have no engine volume, so 0 is right for them.\n",
    "\n",
    "### 6.5 Step 5: remove the impossible rows\n",
    "\n",
    "Change it and run: change `1950` to `1990` and run: old cars are removed too, which is a decision about the data, not a repair."
   ],
   "id": "t31-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df[(df[\"year\"] >= 1950) & (df[\"mileage_km\"] <= 1_000_000)]\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t31-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rows with a year before 1950 or more than a million kilometres are removed. (`1_000_000` is the number one million; Python allows `_` between digits to make it readable.) Removing them is better than keeping them: a forest would learn that \"year 0\" is a group of cars of its own.\n",
    "\n",
    "### 6.6 Step 6: drop the column with too many categories"
   ],
   "id": "t31-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"model\"].nunique())\n",
    "\n",
    "df = df.drop(columns=[\"model\"])"
   ],
   "id": "t31-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "816 different models. One-hot encoding would add 815 columns, most of them with a single car or a few. The brand, the year, the engine and the body already say much of what the model says, so the column is dropped. (Topic 25 showed other ways for such columns; dropping is the simple one.)\n",
    "\n",
    "### 6.7 Step 7: the target"
   ],
   "id": "t31-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"price_azn\"].describe().round(0))"
   ],
   "id": "t31-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The prices go from 1,200 to 160,000 AZN; half of the cars cost less than 21,600 AZN (the median), and the mean, 23,399 AZN, is higher: a few expensive cars pull it up."
   ],
   "id": "t31-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df[\"price_azn\"].plot(kind=\"hist\", bins=50)\n",
    "plt.xlabel(\"price (AZN)\")\n",
    "plt.title(\"Most cars are cheap, a few are very expensive\")\n",
    "plt.show()"
   ],
   "id": "t31-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = df[\"price_azn\"].quantile(0.25)\n",
    "q3 = df[\"price_azn\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((df[\"price_azn\"] > upper).sum())"
   ],
   "id": "t31-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The IQR rule (Topic 25) finds 256 cars above its upper limit of 54,500 AZN. They are real expensive cars, not mistakes, and a model for this market must price them too: they stay. They are why the RMSE of the models will be much larger than their MAE.\n",
    "\n",
    "The features have outliers too:"
   ],
   "id": "t31-020"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for column in [\"mileage_km\", \"engine_l\", \"horsepower\"]:\n",
    "    q1 = df[column].quantile(0.25)\n",
    "    q3 = df[column].quantile(0.75)\n",
    "    upper = q3 + 1.5 * (q3 - q1)\n",
    "    print(column, upper, (df[column] > upper).sum())"
   ],
   "id": "t31-021"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hundreds of cars with a long mileage, a large engine or a strong motor. After the impossible rows of Step 5 they are real cars (SUVs, trucks, sports cars, old taxis), and a forest is not disturbed by them: its trees only ask whether a value is above a threshold, so a very large value simply falls on the \"above\" side (Part 5). They stay. For linear regression, which is sensitive to outliers in the features (Part 5), they would be worth a second look; Part 9 uses it only for a comparison.\n",
    "\n",
    "### 6.8 Step 8: group the rare brands\n",
    "\n",
    "Change it and run: change `50` to `100` and run: fewer brand values are left."
   ],
   "id": "t31-022"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counts = df[\"brand\"].value_counts()\n",
    "rare = counts[counts < 50].index\n",
    "\n",
    "df.loc[df[\"brand\"].isin(rare), \"brand\"] = \"other\"\n",
    "\n",
    "print(df[\"brand\"].nunique())"
   ],
   "id": "t31-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many brands have only a few cars. `counts[counts < 50].index` lists the brands with fewer than 50 cars, and they all become `\"other\"`. 19 brand values are left: enough to tell a Mercedes from a Lada, without a column for every rare brand.\n",
    "\n",
    "### 6.9 Step 9: missing text"
   ],
   "id": "t31-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"market\"] = df[\"market\"].fillna(\"unknown\")\n",
    "\n",
    "print(df[\"market\"].value_counts())"
   ],
   "id": "t31-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a third of the cars the advert does not say where the car was first sold. \"Not said\" can itself mean something, so it becomes a category of its own, `\"unknown\"`. This uses nothing from the other rows, so it can be done before the split.\n",
    "\n",
    "### 6.10 Step 10: encode"
   ],
   "id": "t31-026"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_columns = [\"brand\", \"fuel\", \"gearbox\", \"drive\", \"body\", \"colour\", \"market\", \"city\"]\n",
    "\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t31-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The eight text columns become one-hot columns (Topic 25). `is_new`, `damaged` and `painted` are already 0 and 1. 83 features and the target.\n",
    "\n",
    "### 6.11 Step 11: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: about 2,780 cars become test data."
   ],
   "id": "t31-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"price_azn\"])\n",
    "y = df[\"price_azn\"]\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": "t31-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "7,407 cars for training and 1,852 for the test.\n",
    "\n",
    "### 6.12 Step 12: fill the missing numbers with the training medians"
   ],
   "id": "t31-030"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()\n",
    "\n",
    "X_train = X_train.fillna(medians)\n",
    "X_test = X_test.fillna(medians)\n",
    "\n",
    "print(medians)\n",
    "print(X_train.isna().sum().sum(), X_test.isna().sum().sum())"
   ],
   "id": "t31-031"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fillna(medians)` fills each column with its own median. The medians come from the training cars only, and the same numbers fill the test cars: the test data must not help to build the model, not even through a median (Topic 23). That is why this step comes after the split. The median and not the mean: the mean of the horsepower is pulled up by a few very strong cars.\n",
    "\n",
    "### 6.13 Step 13: no scaling\n",
    "\n",
    "A forest needs no scaling, and neither does plain linear regression for its predictions (Part 5; Part 9 checks it on the cars). The features stay as they are.\n",
    "\n",
    "## 7. The random forest\n",
    "\n",
    "### 7.1 Train and judge\n",
    "\n",
    "Change it and run: write `RandomForestRegressor(n_estimators=10, random_state=42)` and run: ten trees are already far better than one tree."
   ],
   "id": "t31-032"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestRegressor\n",
    "\n",
    "forest = RandomForestRegressor(random_state=42)\n",
    "forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(forest.score(X_train, y_train), 4))\n",
    "print(round(forest.score(X_test, y_test), 4))"
   ],
   "id": "t31-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`RandomForestRegressor` lives in `sklearn.ensemble`, next to the classifier. For a regression model `score` gives the R². On the training cars it is 0.98: the full trees know their prices. On the test cars it is 0.865: the forest explains about 86 percent of the variance of prices it has never seen.\n",
    "\n",
    "### 7.2 The measures of regression"
   ],
   "id": "t31-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error\n",
    "\n",
    "predicted = forest.predict(X_test)\n",
    "\n",
    "print(round(r2_score(y_test, predicted), 4))\n",
    "print(round(mean_absolute_error(y_test, predicted)))\n",
    "print(round(root_mean_squared_error(y_test, predicted)))"
   ],
   "id": "t31-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`r2_score` gives the same number as `score`. The MAE says that a predicted price is typically about 2,750 AZN away from the true price. The RMSE is almost twice as large: a few cars, mostly expensive ones, have large errors. `round(x)` without a number of decimals gives a whole number, which is enough for manats.\n",
    "\n",
    "### 7.3 Inside the forest"
   ],
   "id": "t31-036"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(forest.estimators_))\n",
    "print([tree.get_depth() for tree in forest.estimators_[:5]])\n",
    "print(forest.estimators_[0].get_n_leaves())"
   ],
   "id": "t31-037"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "100 trees, each an ordinary `DecisionTreeRegressor`, more than 30 levels deep. The first tree has 4,373 leaves: a bootstrap sample of 7,407 cars holds about 4,700 different cars, and most of them end in a leaf of their own.\n",
    "\n",
    "### 7.4 How the forest predicts one car\n",
    "\n",
    "Change it and run: change `iloc[[0]]` to `iloc[[5]]` and look at the predictions of the trees for another car."
   ],
   "id": "t31-038"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "car = X_test.iloc[[0]]\n",
    "\n",
    "prices = [tree.predict(car.values)[0] for tree in forest.estimators_]\n",
    "\n",
    "print(min(prices), max(prices))\n",
    "print(round(sum(prices) / len(prices), 1))\n",
    "print(forest.predict(car))\n",
    "print(y_test.iloc[0])"
   ],
   "id": "t31-039"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The list `prices` holds the prediction of each of the 100 trees for the first test car (`.values` passes the plain numbers: the trees inside the forest were trained without the column names). The trees disagree a lot: their predictions lie between 9,800 and 47,500 AZN. Their mean is exactly what `forest.predict` gives, and it is much closer to the true price than the worst trees.\n",
    "\n",
    "### 7.5 How sure is the forest about a car?\n",
    "\n",
    "The 100 predictions of the trees say more than their mean. When the trees agree, the forest is sure about the price; when they disagree, it is not. The standard deviation of the trees' predictions (Topic 18) measures how much they disagree:"
   ],
   "id": "t31-040"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(round(np.std(prices)))"
   ],
   "id": "t31-041"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the first test car the trees' predictions spread by about 7,460 AZN around their mean: the forest is unsure about this car, and indeed its prediction is far from the true price. For a common car the trees agree much more. This spread is a rough measure of how much to trust one prediction; it is not an exact interval.\n",
    "\n",
    "### 7.6 True against predicted prices"
   ],
   "id": "t31-042"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.scatter(y_test, predicted, s=6, alpha=0.5)\n",
    "plt.plot([0, 160000], [0, 160000], color=\"gray\")\n",
    "plt.xlabel(\"true price (AZN)\")\n",
    "plt.ylabel(\"predicted price (AZN)\")\n",
    "plt.title(\"Random forest: predicted against true prices\")\n",
    "plt.show()"
   ],
   "id": "t31-043"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A perfect model would put every car on the grey line. The cheap and middle cars lie close to it; the expensive cars spread out more, and most of them lie below the line: the forest is too careful with them.\n",
    "\n",
    "### 7.7 The forest cannot go beyond the training prices"
   ],
   "id": "t31-044"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(y_train.max())\n",
    "print(round(predicted.max()))\n",
    "print((predicted > y_train.max()).sum())"
   ],
   "id": "t31-045"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The most expensive training car costs 160,000 AZN; the highest prediction for a test car is far below it, and no prediction is above it. This is Part 3 in numbers: a mean of training prices cannot leave their range, and averaging pulls the predictions of rare expensive cars down towards the middle.\n",
    "\n",
    "### 7.8 Feature importances"
   ],
   "id": "t31-046"
  },
  {
   "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).head(8).round(3))"
   ],
   "id": "t31-047"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a regression forest the importance of a feature is how much it lowered the squared error, summed over all splits and averaged over the trees. The year and the engine volume lead: a newer car and a larger engine mean a higher price. The horsepower and the mileage come next."
   ],
   "id": "t31-048"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "importances.sort_values().tail(8).plot(kind=\"barh\")\n",
    "plt.title(\"The eight most important features of the forest\")\n",
    "plt.xlabel(\"importance (decrease of the squared error)\")\n",
    "plt.show()"
   ],
   "id": "t31-049"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The warning of Topic 30 holds here too: the impurity importance favours features with many values, such as the mileage. The permutation importance of Topic 30 works for regression in the same way, with the R² instead of the accuracy; with 83 columns it takes long, so it is left out here.\n",
    "\n",
    "## 8. Tuning the forest\n",
    "\n",
    "### 8.1 `n_estimators`: how many trees?\n",
    "\n",
    "The forest's prediction is the mean of its trees. So the forest of the first $n$ trees can be computed from the trees we already have, without training new forests. First, the predictions of every tree for every test car:"
   ],
   "id": "t31-050"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "tree_predictions = np.array([tree.predict(X_test.values) for tree in forest.estimators_])\n",
    "\n",
    "print(tree_predictions.shape)\n",
    "print(np.allclose(tree_predictions.mean(axis=0), predicted))"
   ],
   "id": "t31-051"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`tree_predictions` is a table with one row for each of the 100 trees and one column for each of the 1,852 test cars. The mean of each column (`axis=0`) is exactly the forest's prediction: `np.allclose` checks that the two arrays are equal up to tiny rounding."
   ],
   "id": "t31-052"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in [1, 5, 10, 20, 50, 100]:\n",
    "    mean_of_n = tree_predictions[:n].mean(axis=0)\n",
    "    print(n, round(r2_score(y_test, mean_of_n), 4))"
   ],
   "id": "t31-053"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`tree_predictions[:n]` takes the first $n$ trees. (This is the same as a forest with `n_estimators=n` and the same `random_state`, because scikit-learn draws the seeds of the trees one after another.) One tree reaches an R² of 0.72; from 1 to 20 trees the R² rises steeply, and after 50 trees it hardly moves."
   ],
   "id": "t31-054"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "sizes = list(range(1, 101))\n",
    "scores = [r2_score(y_test, tree_predictions[:n].mean(axis=0)) for n in sizes]\n",
    "\n",
    "plt.plot(sizes, scores)\n",
    "plt.xlabel(\"number of trees\")\n",
    "plt.ylabel(\"test R²\")\n",
    "plt.title(\"More trees: a rising, then flat curve\")\n",
    "plt.show()"
   ],
   "id": "t31-055"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.2 The out-of-bag R²: a free validation\n",
    "\n",
    "Change it and run: add `max_features=0.33` and run: the OOB R² of the tuned setting."
   ],
   "id": "t31-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "oob_forest = RandomForestRegressor(oob_score=True, random_state=42)\n",
    "oob_forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(oob_forest.oob_score_, 4))"
   ],
   "id": "t31-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `oob_score=True` the forest predicts each training car with the trees for which it was out of bag (about 37 of the 100) and computes the R² of these predictions. It is a little lower than the test R², because each car is predicted by about 37 trees instead of 100, but it is measured without the test data. That makes it the right tool for choosing hyperparameters.\n",
    "\n",
    "### 8.3 `max_features`, chosen with the OOB R²\n",
    "\n",
    "The default forest used `max_features=1.0` (OOB R² above). Now three smaller values:"
   ],
   "id": "t31-058"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for share in [0.5, 0.33, \"sqrt\"]:\n",
    "    model = RandomForestRegressor(max_features=share, oob_score=True, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(share, round(model.oob_score_, 4))"
   ],
   "id": "t31-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each line shows the value of `max_features` and the OOB R². A third of the features (`0.33`, 27 of the 83 at every split) gives the highest OOB R², just above `0.5`; both beat the default `1.0`. `\"sqrt\"`, the default for classes, gives each split only 9 features and is too few here: the year and the engine are missing from too many splits. A smaller `max_features` also makes the forest faster, because each split tries fewer features.\n",
    "\n",
    "### 8.4 `min_samples_leaf`"
   ],
   "id": "t31-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for leaf in [1, 2, 5]:\n",
    "    model = RandomForestRegressor(max_features=0.33, min_samples_leaf=leaf, oob_score=True, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(leaf, round(model.oob_score_, 4))"
   ],
   "id": "t31-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Larger leaves make the OOB R² fall. For prices, a leaf of a single car is best: each limit replaces the price of the most similar car by a mean over several less similar cars. (In Topic 30 larger leaves helped the AUC of the bank forest: what helps depends on the data, and the OOB score or cross-validation decides.)\n",
    "\n",
    "### 8.5 The tuned forest\n",
    "\n",
    "Change it and run: change `max_features=0.33` to `max_features=0.5` and run."
   ],
   "id": "t31-062"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned = RandomForestRegressor(max_features=0.33, random_state=42)\n",
    "tuned.fit(X_train, y_train)\n",
    "\n",
    "tuned_predicted = tuned.predict(X_test)\n",
    "\n",
    "print(round(r2_score(y_test, tuned_predicted), 4))\n",
    "print(round(mean_absolute_error(y_test, tuned_predicted)))\n",
    "print(round(root_mean_squared_error(y_test, tuned_predicted)))"
   ],
   "id": "t31-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On the test cars, chosen without them, the tuned forest is better on all three measures than the default forest: a higher R², a smaller MAE and a smaller RMSE.\n",
    "\n",
    "### 8.6 Why it is better: less correlated trees\n",
    "\n",
    "The variance formula says that a forest gains by making its trees less alike. As in Topic 30, the correlation of every pair of trees can be measured from their predictions:"
   ],
   "id": "t31-064"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned_predictions = np.array([tree.predict(X_test.values) for tree in tuned.estimators_])\n",
    "\n",
    "default_corr = np.corrcoef(tree_predictions)\n",
    "tuned_corr = np.corrcoef(tuned_predictions)\n",
    "\n",
    "print(round((default_corr.sum() - 100) / (100 * 99), 3))\n",
    "print(round((tuned_corr.sum() - 100) / (100 * 99), 3))"
   ],
   "id": "t31-065"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`np.corrcoef` gives a $100 \\times 100$ table of the correlations of every pair of trees; without the 100 ones on its diagonal, $\\frac{\\text{sum} - 100}{100 \\times 99}$ is the mean over the pairs. The trees of the default forest, which all see every feature, are correlated with about 0.87; with a third of the features at each split, about 0.82. The prices of cars are dominated by the year and the engine, so all trees stay quite alike; the random features make them a little less so, and that is enough to lower the variance of their mean.\n",
    "\n",
    "## 9. Bagging around any regression model\n",
    "\n",
    "### 9.1 Bagging for regression\n",
    "\n",
    "Bagging is the same as in Topic 30 (Part 9): draw many bootstrap samples, train the same model on each, and combine. For a number the answers are combined by their mean. In scikit-learn it is `BaggingRegressor` from `sklearn.ensemble`, with the hyperparameters of `BaggingClassifier`:\n",
    "\n",
    "| Hyperparameter | Default | Role |\n",
    "| --- | --- | --- |\n",
    "| `estimator` | a decision tree | the model inside, 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 R² |\n",
    "| `random_state` | `None` | the seed for the samples |\n",
    "\n",
    "### 9.2 Bagging around a full decision tree"
   ],
   "id": "t31-066"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingRegressor\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "\n",
    "full_tree = DecisionTreeRegressor(random_state=42)\n",
    "full_tree.fit(X_train, y_train)\n",
    "\n",
    "bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42)\n",
    "bagged_trees.fit(X_train, y_train)\n",
    "\n",
    "print(round(full_tree.score(X_train, y_train), 4), round(full_tree.score(X_test, y_test), 4))\n",
    "print(round(bagged_trees.score(X_test, y_test), 4))\n",
    "print(round(forest.score(X_test, y_test), 4))"
   ],
   "id": "t31-067"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One full tree: an R² of almost 1 on the training cars and about 0.80 on the test cars, the overfitting of Part 2. A hundred bagged full trees: about 0.865 on the test cars. The third line is the default random forest: practically the same score as the bagged trees, because with `max_features=1.0` it is bagging of trees. (The two are not equal to the last digit: they draw their random numbers differently.) The tuned forest beats both with its random features.\n",
    "\n",
    "### 9.3 Bagging around a shallow tree\n",
    "\n",
    "Change it and run: change both `max_depth=8` to `max_depth=4` and run: the bias of the shallower tree grows."
   ],
   "id": "t31-068"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shallow = DecisionTreeRegressor(max_depth=8, random_state=42)\n",
    "shallow.fit(X_train, y_train)\n",
    "\n",
    "bagged_shallow = BaggingRegressor(estimator=DecisionTreeRegressor(max_depth=8), 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))"
   ],
   "id": "t31-069"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A tree of depth 8 has at most 256 leaves, so it can predict at most 256 different prices. Bagging 100 of them gives a much finer set of prices and a clearly higher R². Still, it stays below the bagged full trees: a depth of 8 is too little for the variety of cars, and averaging cannot remove bias.\n",
    "\n",
    "### 9.4 Bagging around linear regression\n",
    "\n",
    "Bagging works around any regression model. Plain linear regression (Topic 22) needs the encoded and filled data we have. Does it need scaling? Topic 24 said no: scaling changes its weights, not its predictions. A quick check on the cars, with a `StandardScaler` fitted on the training data:"
   ],
   "id": "t31-070"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "plain = LinearRegression().fit(X_train, y_train)\n",
    "scaled = LinearRegression().fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(plain.score(X_test, y_test), 4), round(scaled.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t31-071"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same R² with and without scaling, so the project goes on without it: one set of data serves every model of this part."
   ],
   "id": "t31-072"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "linear = LinearRegression()\n",
    "linear.fit(X_train, y_train)\n",
    "\n",
    "bagged_linear = BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)\n",
    "bagged_linear.fit(X_train, y_train)\n",
    "\n",
    "print(round(linear.score(X_test, y_test), 4), round(bagged_linear.score(X_test, y_test), 4))"
   ],
   "id": "t31-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same R² twice, about 0.71. Every bootstrap sample of 7,407 cars gives almost the same weights, so the mean of 100 linear regressions is the same linear regression again. Bagging cures variance, and linear regression has little of it. Its problem is bias: a price is not a straight-line sum of the features (the price falls fast in the first years of a car and slowly later), and no averaging changes that. The trees can follow such curves; that is why all tree models beat it here.\n",
    "\n",
    "### 9.5 A relative: extremely randomized trees"
   ],
   "id": "t31-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import ExtraTreesRegressor\n",
    "\n",
    "extra = ExtraTreesRegressor(random_state=42)\n",
    "extra.fit(X_train, y_train)\n",
    "\n",
    "print(round(extra.score(X_test, y_test), 4))"
   ],
   "id": "t31-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Extremely randomized trees (Topic 30, Part 9) draw the thresholds at random too, and train every tree on all rows. On the cars they are about as good as the tuned forest, without any tuning. It is one more model of the same family worth trying.\n",
    "\n",
    "### 9.6 The scores of every model"
   ],
   "id": "t31-076"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = [\n",
    "    (\"full tree\", full_tree),\n",
    "    (\"tree, max_depth=8\", shallow),\n",
    "    (\"bagged full trees\", bagged_trees),\n",
    "    (\"bagged trees, max_depth=8\", bagged_shallow),\n",
    "    (\"random forest\", forest),\n",
    "    (\"tuned random forest\", tuned),\n",
    "    (\"extremely randomized trees\", extra),\n",
    "    (\"linear regression\", linear),\n",
    "    (\"bagged linear regression\", bagged_linear),\n",
    "]\n",
    "\n",
    "for name, model in models:\n",
    "    model_predicted = model.predict(X_test)\n",
    "    r2 = round(r2_score(y_test, model_predicted), 4)\n",
    "    mae = round(mean_absolute_error(y_test, model_predicted))\n",
    "    rmse = round(root_mean_squared_error(y_test, model_predicted))\n",
    "    print(name, r2, mae, rmse)"
   ],
   "id": "t31-077"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a model, its R², its MAE and its RMSE on the same 1,852 test cars. No model needs other test data here: nothing was scaled."
   ],
   "id": "t31-078"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "names = [name for name, model in models]\n",
    "r2s = [r2_score(y_test, model.predict(X_test)) for name, model in models]\n",
    "\n",
    "plt.barh(names, r2s)\n",
    "plt.xlim(0.6, 0.9)\n",
    "plt.xlabel(\"test R²\")\n",
    "plt.title(\"Single models, bagged models and forests\")\n",
    "plt.show()"
   ],
   "id": "t31-079"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What the comparison shows:\n",
    "\n",
    "- Bagging lifts the unstable full tree from about 0.80 to about 0.865.\n",
    "- Bagging helps the shallow tree too, but its bias stays.\n",
    "- Bagging does nothing for the stable linear regression.\n",
    "- The default random forest is bagging of trees and scores the same; the tuned forest, with a third of the features at every split, is the best, together with the extremely randomized trees.\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 adverts, 19 columns |\n",
    "| 2. Check | missing values, repeated rows | four columns with gaps, 691 repeated rows |\n",
    "| 3. Repeated rows | drop them before the split | 9,309 rows left |\n",
    "| 4. Impossible values | find them with `describe()` | year 0, three million kilometres; engine 0 is right for electric cars |\n",
    "| 5. Remove | the rows with impossible values | 9,259 rows left |\n",
    "| 6. Too many categories | drop or group | `model` (816 values) dropped |\n",
    "| 7. Target | its distribution and its outliers | real expensive cars, kept |\n",
    "| 8. Rare categories | group them | brands with fewer than 50 cars become `\"other\"` |\n",
    "| 9. Missing text | a category of its own | `market`: `\"unknown\"` |\n",
    "| 10. Encode | text to numbers | one-hot: 83 features |\n",
    "| 11. Split | training and test data | 7,407 and 1,852 |\n",
    "| 12. Missing numbers | fill with the training medians, after the split | `horsepower`, `seats`, `owners` |\n",
    "| 13. Scale | only for the models that need it | not for the forest, not for plain linear regression |\n",
    "| 14. Model | the random forest | default: test R² 0.865 |\n",
    "| 15. Look inside | trees, one car, importances, the range of the predictions | year and engine lead; no prediction above the training prices |\n",
    "| 16. Tune | `n_estimators`, `max_features` and `min_samples_leaf` with the OOB R² | `max_features=0.33` |\n",
    "| 17. Model again | bagging around other models | trees gain, linear regression does not |\n",
    "| 18. Judge | R², MAE and RMSE of every model on the same test data | the tuned forest and the extremely randomized trees lead |\n",
    "\n",
    "## 11. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Keeping repeated rows. | The same car in the training and the test data makes the test score too good. | `drop_duplicates()` before the split. |\n",
    "| Filling missing values with medians of all the data. | The test data then helps to build the model. | Compute the medians on the training data, after the split. |\n",
    "| Treating a year 0 as an outlier to keep. | It is a mistake in the data, not a rare car. | Remove such rows or set the value to missing. |\n",
    "| One-hot encoding a column with hundreds of categories. | Hundreds of columns, most with one or two cars. | Drop it, or group its rare values. |\n",
    "| Thinking `RandomForestRegressor()` uses random features. | Its default `max_features=1.0` is plain bagging of trees. | Tune `max_features`: try `0.33`, `0.5`, `\"sqrt\"`. |\n",
    "| Expecting a forest to predict above the highest training price. | Every leaf predicts a mean of training prices. | Know the range; use a model that extrapolates when needed. |\n",
    "| Judging a forest on its training R². | Its full trees know the training prices by heart. | The test R² or the OOB R². |\n",
    "| Reading the RMSE as the typical error. | Large errors count much more in it. | The MAE is the typical error; the RMSE shows the large ones. |\n",
    "| Choosing `max_features` with the test data. | The test data then helps to build the model. | The OOB R² or cross-validation. |\n",
    "| Expecting bagging to improve linear regression. | It cures variance; linear regression has little. | Bag unstable models, such as deep trees. |\n",
    "| Scaling the features for a forest. | It changes nothing. | Scale only for models that need it. |\n",
    "| Using accuracy or recall for prices. | They are measures for classes. | R², MAE, RMSE. |\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 `car_prices.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. The best split\n",
    "\n",
    "Four cars have the mileages 20, 60, 120 and 180 thousand km and the prices 30, 26, 14 and 10 thousand AZN. (a) What is the squared error of the node with all four cars? (b) Which threshold of the mileage gives the lowest error after the split, and what do its two leaves predict?\n",
    "\n",
    "Idea. The squared error of a node and the weighted error after a split (Part 2). The thresholds lie halfway: 40, 90 and 150.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{mean} &= \\frac{30 + 26 + 14 + 10}{4} = \\frac{80}{4} = 20 \\\\[8pt]\n",
    "\\text{squared error} &= \\frac{10^2 + 6^2 + 6^2 + 10^2}{4} \\\\[4pt]\n",
    "&= \\frac{272}{4} = 68\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For the threshold 90:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{left mean} &= \\frac{30 + 26}{2} = 28 \\\\[6pt]\n",
    "\\text{left error} &= \\frac{2^2 + 2^2}{2} = 4 \\\\[10pt]\n",
    "\\text{right mean} &= \\frac{14 + 10}{2} = 12 \\\\[6pt]\n",
    "\\text{right error} &= \\frac{2^2 + 2^2}{2} = 4 \\\\[10pt]\n",
    "\\text{after the split} &= \\tfrac{2}{4} \\times 4 + \\tfrac{2}{4} \\times 4 = 4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For the threshold 40:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{left error} &= 0 \\quad (\\text{one car}) \\\\[6pt]\n",
    "\\text{right mean} &= \\frac{26 + 14 + 10}{3} = 16.667 \\\\[6pt]\n",
    "\\text{right error} &= 46.222 \\\\[10pt]\n",
    "\\text{after the split} &= \\tfrac{1}{4} \\times 0 + \\tfrac{3}{4} \\times 46.222 \\\\[4pt]\n",
    "&= 34.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the threshold 150 gives 34.667 as well (by symmetry). The tree chooses mileage ≤ 90, which lowers the error from 68 to 4; its leaves predict 28 thousand AZN for the cars with less mileage and 12 thousand for the others.\n",
    "\n",
    "Problem 2. The prediction of a forest\n",
    "\n",
    "A forest of four trees predicts the prices 15,200, 16,800, 14,900 and 17,100 AZN for a car. (a) What does the forest predict? (b) The most expensive training car cost 90,000 AZN. Can this forest ever predict 95,000 AZN?\n",
    "\n",
    "Idea. The mean of the trees' predictions; every leaf is a mean of training prices (Part 3).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{prediction} \\\\[4pt]\n",
    "&= \\frac{15{,}200 + 16{,}800 + 14{,}900 + 17{,}100}{4} \\\\[4pt]\n",
    "&= \\frac{64{,}000}{4} = 16{,}000 \\text{ AZN}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: (a) 16,000 AZN. (b) No: no leaf can predict more than 90,000 AZN, and a mean of such predictions cannot either.\n",
    "\n",
    "Problem 3. The three measures\n",
    "\n",
    "Three cars cost 10, 20 and 30 thousand AZN; a model predicts 12, 18 and 33. Compute the MAE, the RMSE and the R².\n",
    "\n",
    "Idea. The formulas of Part 5. The errors $y - \\hat{y}$ are $-2$, $2$ and $-3$.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{MAE} &= \\frac{2 + 2 + 3}{3} = \\frac{7}{3} = 2.333 \\\\[8pt]\n",
    "\\text{RMSE} &= \\sqrt{\\frac{4 + 4 + 9}{3}} = \\sqrt{5.667} = 2.381\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\bar{y} &= \\frac{10 + 20 + 30}{3} = 20 \\\\[8pt]\n",
    "\\textstyle\\sum (y - \\bar{y})^2 &= 10^2 + 0^2 + 10^2 = 200 \\\\[8pt]\n",
    "R^2 &= 1 - \\frac{17}{200} = 1 - 0.085 = 0.915\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the typical error is 2,333 AZN; the RMSE is a little larger, because the error of 3 counts more when squared; the model explains 91.5 percent of the variance of the three prices.\n",
    "\n",
    "Problem 4. Features at a split\n",
    "\n",
    "The car data has 83 features. How many features does each split of a `RandomForestRegressor` try (a) with the default settings, (b) with `max_features=0.33`, (c) with `max_features=\"sqrt\"`?\n",
    "\n",
    "Idea. A share is multiplied by the number of features and rounded down; `\"sqrt\"` takes the square root, rounded down (Part 4).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "0.33 \\times 83 &= 27.39, \\ \\text{rounded down: } 27 \\\\[6pt]\n",
    "\\sqrt{83} &= 9.11, \\ \\text{rounded down: } 9\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: (a) all 83: the default `1.0` is bagging of trees; (b) 27; (c) 9.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of repeated rows, and the number of missing values in each column.\n",
    "\n",
    "Idea. The first steps of the workflow (Part 6)."
   ],
   "id": "t31-080"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"car_prices.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.duplicated().sum())\n",
    "print(df.isna().sum())"
   ],
   "id": "t31-081"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 691 repeated adverts to drop, and four columns with gaps to fill.\n",
    "\n",
    "Problem 6. Repeated and impossible rows\n",
    "\n",
    "Drop the repeated rows, then keep only the cars made in 1950 or later and with at most 1,000,000 km. Print the shape.\n",
    "\n",
    "Idea. Repeated rows make the test score too good; impossible values are mistakes (Part 6)."
   ],
   "id": "t31-082"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop_duplicates()\n",
    "df = df[(df[\"year\"] >= 1950) & (df[\"mileage_km\"] <= 1_000_000)]\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t31-083"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 741 rows fewer than the file: 691 copies and 50 impossible adverts.\n",
    "\n",
    "Problem 7. Categories\n",
    "\n",
    "Drop the column `model`, group the brands with fewer than 50 cars as `\"other\"`, and fill the missing `market` with `\"unknown\"`. Print the number of brand values and the number of cars with an unknown market.\n",
    "\n",
    "Idea. Too many categories and missing text (Part 6)."
   ],
   "id": "t31-084"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"model\"])\n",
    "\n",
    "counts = df[\"brand\"].value_counts()\n",
    "rare = counts[counts < 50].index\n",
    "df.loc[df[\"brand\"].isin(rare), \"brand\"] = \"other\"\n",
    "\n",
    "df[\"market\"] = df[\"market\"].fillna(\"unknown\")\n",
    "\n",
    "print(df[\"brand\"].nunique())\n",
    "print((df[\"market\"] == \"unknown\").sum())"
   ],
   "id": "t31-085"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 19 brand values instead of more than a hundred, and the unknown market becomes a category of its own.\n",
    "\n",
    "Problem 8. Encode and split\n",
    "\n",
    "One-hot encode the eight text columns with `drop_first=True` and `dtype=int`. 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. Text to numbers, then the split (Part 6)."
   ],
   "id": "t31-086"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "text_columns = [\"brand\", \"fuel\", \"gearbox\", \"drive\", \"body\", \"colour\", \"market\", \"city\"]\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "X = df.drop(columns=[\"price_azn\"])\n",
    "y = df[\"price_azn\"]\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": "t31-087"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 83 features; a quarter of the cars is kept for the test.\n",
    "\n",
    "Problem 9. Fill the missing numbers\n",
    "\n",
    "Fill `horsepower`, `seats` and `owners` in both parts with the medians of the training data. Print the medians and the number of missing values left in `X_train` and `X_test`.\n",
    "\n",
    "Idea. Medians from the training data only, after the split (Part 6)."
   ],
   "id": "t31-088"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()\n",
    "\n",
    "X_train = X_train.fillna(medians)\n",
    "X_test = X_test.fillna(medians)\n",
    "\n",
    "print(medians)\n",
    "print(X_train.isna().sum().sum(), X_test.isna().sum().sum())"
   ],
   "id": "t31-089"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: no gaps are left, and the test cars were filled with numbers they did not help to compute.\n",
    "\n",
    "Problem 10. A random forest\n",
    "\n",
    "Train a `RandomForestRegressor` with `random_state=42`. Print its training R² and its test R², rounded to 4 decimals.\n",
    "\n",
    "Idea. The default forest of Part 7; `score` gives the R²."
   ],
   "id": "t31-090"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import RandomForestRegressor\n",
    "\n",
    "forest = RandomForestRegressor(random_state=42)\n",
    "forest.fit(X_train, y_train)\n",
    "\n",
    "print(round(forest.score(X_train, y_train), 4))\n",
    "print(round(forest.score(X_test, y_test), 4))"
   ],
   "id": "t31-091"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: almost perfect on the training cars, as its full trees are; the test R² is the honest score.\n",
    "\n",
    "Problem 11. Its errors in manats\n",
    "\n",
    "Print the MAE and the RMSE of the forest on the test data, as whole numbers.\n",
    "\n",
    "Idea. The measures of regression (Part 5)."
   ],
   "id": "t31-092"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error\n",
    "\n",
    "predicted = forest.predict(X_test)\n",
    "\n",
    "print(round(mean_absolute_error(y_test, predicted)))\n",
    "print(round(root_mean_squared_error(y_test, predicted)))"
   ],
   "id": "t31-093"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the typical error is under 3,000 AZN, and the RMSE, about twice as large, shows that a few cars have large errors.\n",
    "\n",
    "Problem 12. The trees for one car\n",
    "\n",
    "For the first test car, compute the prediction of every tree of the forest. Print the mean of the 100 predictions rounded to 1 decimal, and the forest's own prediction.\n",
    "\n",
    "Idea. The forest predicts the mean of its trees (Part 7)."
   ],
   "id": "t31-094"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "car = X_test.iloc[[0]]\n",
    "\n",
    "prices = [tree.predict(car.values)[0] for tree in forest.estimators_]\n",
    "\n",
    "print(round(sum(prices) / len(prices), 1))\n",
    "print(forest.predict(car))"
   ],
   "id": "t31-095"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the same number twice: the forest is the mean of its trees.\n",
    "\n",
    "Problem 13. The OOB R² of three forests\n",
    "\n",
    "For `max_features` equal to `1.0`, `0.33` and `\"sqrt\"`, train a forest with `oob_score=True` and `random_state=42`, and print the value and the OOB R² rounded to 4 decimals.\n",
    "\n",
    "Idea. The out-of-bag R² chooses a hyperparameter without the test data (Part 8)."
   ],
   "id": "t31-096"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for share in [1.0, 0.33, \"sqrt\"]:\n",
    "    model = RandomForestRegressor(max_features=share, oob_score=True, random_state=42)\n",
    "    model.fit(X_train, y_train)\n",
    "    print(share, round(model.oob_score_, 4))"
   ],
   "id": "t31-097"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: with this split `1.0` and `0.33` are almost equal, and `\"sqrt\"` is clearly worse: the best value depends on the data, and the OOB score shows it at no cost.\n",
    "\n",
    "Problem 14. The tuned forest\n",
    "\n",
    "Train a forest with `max_features=0.33` and `random_state=42`, called `tuned`. Print its test R² rounded to 4 decimals, its MAE and its RMSE as whole numbers.\n",
    "\n",
    "Idea. The setting chosen in the lesson (Part 8)."
   ],
   "id": "t31-098"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned = RandomForestRegressor(max_features=0.33, random_state=42)\n",
    "tuned.fit(X_train, y_train)\n",
    "\n",
    "tuned_predicted = tuned.predict(X_test)\n",
    "\n",
    "print(round(r2_score(y_test, tuned_predicted), 4))\n",
    "print(round(mean_absolute_error(y_test, tuned_predicted)))\n",
    "print(round(root_mean_squared_error(y_test, tuned_predicted)))"
   ],
   "id": "t31-099"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a higher R² and a smaller RMSE than the default forest on this split too (the MAE is about the same), even though its OOB R² was a little lower than that of `1.0`: the OOB R² is an estimate, and values this close may change order on the test data. Both ways of judging agree that `\"sqrt\"` is too few.\n",
    "\n",
    "Problem 15. Bagged trees\n",
    "\n",
    "Train a single full `DecisionTreeRegressor` with `random_state=42` and a `BaggingRegressor` of 100 full trees with `random_state=42`. Print the test R² of each, rounded to 4 decimals.\n",
    "\n",
    "Idea. Bagging around an unstable model (Part 9)."
   ],
   "id": "t31-100"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingRegressor\n",
    "from sklearn.tree import DecisionTreeRegressor\n",
    "\n",
    "full_tree = DecisionTreeRegressor(random_state=42)\n",
    "full_tree.fit(X_train, y_train)\n",
    "\n",
    "bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), 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))\n",
    "print(round(bagged_trees.score(X_test, y_test), 4))"
   ],
   "id": "t31-101"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: one full tree is far behind; the bagged trees score like the default forest, which is bagging of trees.\n",
    "\n",
    "Problem 16. Bagged linear regression\n",
    "\n",
    "Train a `LinearRegression` and a `BaggingRegressor` of 100 linear regressions with `random_state=42`. Print the test R² of each, rounded to 4 decimals.\n",
    "\n",
    "Idea. Bagging around a stable model; plain linear regression needs no scaling (Part 9)."
   ],
   "id": "t31-102"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import BaggingRegressor\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "linear = LinearRegression()\n",
    "linear.fit(X_train, y_train)\n",
    "\n",
    "bagged_linear = BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)\n",
    "bagged_linear.fit(X_train, y_train)\n",
    "\n",
    "print(round(linear.score(X_test, y_test), 4))\n",
    "print(round(bagged_linear.score(X_test, y_test), 4))"
   ],
   "id": "t31-103"
  },
  {
   "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",
    "| Squared error of a node | mean of $(y - \\bar{y})^2$ | how far the values of a node lie from their mean |\n",
    "| Error after a split | $\\tfrac{n_{\\text{left}}}{n} \\times \\text{error}_{\\text{left}} + \\tfrac{n_{\\text{right}}}{n} \\times \\text{error}_{\\text{right}}$ | the tree takes the split with the smallest value |\n",
    "| A leaf predicts | the mean of its training values | never outside the training range |\n",
    "| The forest predicts | the mean of the trees' predictions | no vote, no threshold |\n",
    "| MAE | mean of $\\lvert y - \\hat{y} \\rvert$ | the typical error, in manats |\n",
    "| RMSE | $\\sqrt{\\text{mean of } (y - \\hat{y})^2}$ | large errors count more; at least the MAE |\n",
    "| R² | $1 - \\frac{\\sum (y - \\hat{y})^2}{\\sum (y - \\bar{y})^2}$ | the share of the variance explained |\n",
    "| Default `max_features` | `1.0` for regression | the default regression forest is bagging of trees |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `RandomForestRegressor(random_state=42)` | a forest of 100 full regression trees |\n",
    "| `max_features=0.33` | a third of the features at every split: a real random forest |\n",
    "| `oob_score=True`, then `oob_score_` | the out-of-bag R² |\n",
    "| `forest.score(X_test, y_test)` | the test R² |\n",
    "| `r2_score`, `mean_absolute_error`, `root_mean_squared_error` | the measures of regression |\n",
    "| `forest.estimators_` | the list of the trees |\n",
    "| `BaggingRegressor(estimator=..., n_estimators=100)` | bagging around any regression model |\n",
    "| `df.drop_duplicates()` | drop the repeated rows, before the split |\n",
    "| `X_train.fillna(medians)` | fill with the training medians, after the split |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. A regression tree chooses the split with the lowest weighted squared error; its leaves predict means.\n",
    "2. A regression forest predicts the mean of its trees, and never leaves the range of the training values.\n",
    "3. The default `RandomForestRegressor` is bagging of trees; tune `max_features` with the OOB R² or cross-validation.\n",
    "4. Judge regression models with R², MAE and RMSE on the test data; the OOB R² chooses the hyperparameters.\n",
    "5. Drop repeated rows before the split, remove impossible values, and fill the missing values with the training medians after it.\n",
    "6. Bagging works around any model and cures variance: it helps deep trees a lot and linear regression not 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",
    "Random forests and bagging train their trees independently and average them. Topic 32 brings a model that works in a completely different way: k-nearest neighbours, which predicts a class from the most similar rows; Topic 33 uses it for numbers. It needs distances, so scaling becomes essential again. Topic 34 is Naive Bayes, which calculates probabilities with Bayes' rule (Topic 16). Later, Topics 37 to 40 train trees one after another, each correcting the errors of the ones before: boosting.\n",
    "\n",
    "Next: the practice notebook (topic-31-practice.ipynb), then Topic 32: k-Nearest Neighbors - Classification."
   ],
   "id": "t31-104"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
