{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 24: Feature engineering: scaling numerical values\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 12, 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-24-practice.ipynb.\n",
    "\n",
    "Inside a part the cells continue from each other: a cell uses the variables of the cells above it. To start in the middle, run the part from its first cell.\n",
    "\n",
    "This notebook reads the file cars.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. The data and a first score\n",
    "2. Dropping columns that carry no information\n",
    "3. Creating new features\n",
    "4. Selecting features\n",
    "5. Why scale?\n",
    "6. Four ways of scaling\n",
    "7. fit, transform, and the order of the steps\n",
    "8. Every scaler at once, and the scores\n",
    "9. Common mistakes\n",
    "10. Solved problems\n",
    "11. Practice (in topic-24-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Summary"
   ],
   "id": "t24-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: the work on the columns\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, not every column is a feature: an identification number, a name and a column that never changes are dropped. Second, a new feature made with logic, such as the power for the weight, can raise the score more than any change of the model. Third, correlation helps to choose: far from 0 with the target is good, and two features above about 0.9 with each other are one too many. Fourth, the four ways of scaling: min-max (from 0 to 1), standard (mean 0, standard deviation 1), robust (median and quartiles, for outliers) and the logarithm (for a long tail). Fifth, the order: split first, then `fit_transform` on the training data and `transform` on the test data, with one scaler.\n",
    "\n",
    "The fourth lesson of Module 3. In Topic 22 you built a model, and in Topic 23 you learned to judge it fairly on test data. Both lessons took the columns of the data as they came. This lesson is about the columns themselves. A model can only learn from what its features show it, so the work on the features often changes the score more than any change of the model.\n",
    "\n",
    "The lesson has three steps, in the order in which they are done in a project. First, cleaning the list of columns: dropping the ones that carry no information, such as an identification number or a name. Second, creating and selecting features: building new columns from the ones you have, and choosing which columns go into the model, with the help of correlation. Third, scaling: bringing numerical features to a comparable size, with four methods, and doing it without letting the test data leak into the training.\n",
    "\n",
    "Everything is explained on one data file, `cars.csv`, with the tools you know: pandas, `train_test_split` and `LinearRegression`.\n",
    "\n",
    "You need: reading and changing a DataFrame (Topics 10 and 11), the mean, the median, the standard deviation and the quartiles (Topic 18), covariance and correlation (Topic 20), linear regression and gradient descent (Topic 22), and the train/test split (Topic 23).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| feature engineering | the work on the input columns: dropping, creating, selecting and transforming them |\n",
    "| feature creation | building a new column from existing ones: an age from a year, a ratio from two columns |\n",
    "| feature selection | choosing which columns go into the model |\n",
    "| multicollinearity | two or more features that say almost the same |\n",
    "| scaling | changing the numbers of a column to a comparable size, without changing what they say |\n",
    "| min-max scaling | squeezing a column into the range from 0 to 1 |\n",
    "| standard scaling (standardisation) | giving a column the mean 0 and the standard deviation 1: the z-score |\n",
    "| robust scaling | scaling with the median and the quartiles, which outliers hardly move |\n",
    "| log transform | replacing a value by its logarithm, to pull in a long tail of large values |\n",
    "| `fit` | learn the numbers of a scaler (a minimum, a mean) from data |\n",
    "| `transform` | apply the learned numbers to data |\n",
    "| data leakage | information from the test data reaches the training |\n",
    "\n",
    "## 1. The data and a first score\n",
    "\n",
    "### 1.1 The file\n",
    "\n",
    "`cars.csv` describes 240 invented used cars. The target is the price in thousands."
   ],
   "id": "t24-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head(3).T)"
   ],
   "id": "t24-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.head(3).T` shows the first three cars turned on their side (`.T`, as in NumPy): every column is a line, so all ten columns fit.\n",
    "\n",
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `car_id` | the identification number of the car in the list |\n",
    "| `owner_name` | the first name of the owner |\n",
    "| `year` | the year in which the car was built |\n",
    "| `mileage_km` | how far the car has driven, in km |\n",
    "| `engine_cc` | the size of the engine in cubic centimetres |\n",
    "| `horsepower` | the power of the engine |\n",
    "| `weight_kg` | the weight of the car in kg |\n",
    "| `doors` | the number of doors |\n",
    "| `wheels` | the number of wheels |\n",
    "| `price` | the price in thousands: the target |\n",
    "\n",
    "### 1.2 A first model, before any work on the features\n",
    "\n",
    "To see what feature engineering is worth, we need a starting point: a model that uses the numerical columns as they are. The recipe is the one of Topic 23.\n",
    "\n",
    "The cell continues from the one above: `df` is already there."
   ],
   "id": "t24-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df[[\"year\", \"mileage_km\", \"engine_cc\", \"horsepower\", \"weight_kg\", \"doors\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t24-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A test score of 0.879 is the number to beat. Every step of this lesson is judged by what it does to this score.\n",
    "\n",
    "## 2. Dropping columns that carry no information\n",
    "\n",
    "Not every column of a table is a feature. Some columns are there to organise the data, not to describe it. Three kinds are dropped before anything else.\n",
    "\n",
    "### 2.1 An identification number\n",
    "\n",
    "`car_id` runs from 1001 to 1240: every car has its own number. It was given in the order in which the cars were written into the list, and it says nothing about the car. A model can still try to use it. With enough flexibility it would even \"learn\" that car 1017 costs 21.4, which is memorising, not learning: the overfitting of Topic 23. And for a new car, which gets the number 1241, that knowledge is worthless.\n",
    "\n",
    "The same holds for every column that only names a row: an order number, a customer number, a telephone number, a passport number.\n",
    "\n",
    "### 2.2 A name\n",
    "\n",
    "`owner_name` is the first name of the owner. The price of a car does not depend on whether the owner is called Murad or Leyla. It is also text, and a model calculates with numbers: a column of names cannot go into `LinearRegression` at all. (Text columns that do carry information, such as a city or a colour, are turned into numbers by encoding. That is Topic 25.)\n",
    "\n",
    "### 2.3 A column that never changes\n",
    "\n",
    "`wheels` is 4 in every row. A column with a single value cannot explain why one car is more expensive than another: it has no variation, and a model learns from variation.\n",
    "\n",
    "### 2.4 Finding such columns\n",
    "\n",
    "`nunique()` counts the different values of every column:"
   ],
   "id": "t24-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.nunique())"
   ],
   "id": "t24-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `car_id` has 240 different values in 240 rows: one for each row. That is the mark of an identification number.\n",
    "- `wheels` has 1 value: a constant.\n",
    "- `owner_name` has 20 values, and its meaning (a name) tells you that it is not a feature. No number can tell you that: you have to know what a column means.\n",
    "\n",
    "### 2.5 Dropping them\n",
    "\n",
    "Change it and run: add `\"doors\"` to the list and run: one column less."
   ],
   "id": "t24-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"car_id\", \"owner_name\", \"wheels\"])\n",
    "\n",
    "print(df.columns.tolist())"
   ],
   "id": "t24-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6 Why not leave them in?\n",
    "\n",
    "- They can hurt. A column without information gives the model room to find accidental patterns: overfitting (Topic 23).\n",
    "- They cost. Every column makes the model larger and slower and harder to read.\n",
    "- Some cannot be used at all. Text stops the model with an error.\n",
    "\n",
    "The rule: before modelling, go through the columns and ask of each one whether it can sensibly influence the target.\n",
    "\n",
    "## 3. Creating new features\n",
    "\n",
    "### 3.1 Why create features?\n",
    "\n",
    "A linear regression can do two things with its features: multiply each one by a weight, and add the results. It cannot subtract a year from today's date, and it cannot divide one column by another. If the price depends on such a combination, the model cannot find it. But you can calculate the combination yourself and hand it to the model as a new column. That is feature creation: putting your knowledge of the subject into the data.\n",
    "\n",
    "### 3.2 Three features made with logic\n",
    "\n",
    "Think about what really decides the price of a used car.\n",
    "\n",
    "1. The age. A buyer does not think \"this car is from 2015\". The buyer thinks \"this car is 11 years old\". The age is the year turned into the quantity that matters:\n",
    "\n",
    "$$\n",
    "\\text{age} = 2026 - \\text{year}\n",
    "$$\n",
    "\n",
    "2. The power for the weight. 150 horsepower make a small light car fast and a heavy one slow. What a driver feels is the power for every kilogram:\n",
    "\n",
    "$$\n",
    "\\text{power for the weight} = \\frac{\\text{horsepower}}{\\text{weight in kg}}\n",
    "$$\n",
    "\n",
    "3. The use per year. 120,000 km are a lot for a car of 3 years and little for a car of 15. How hard a car was used is the distance for every year:\n",
    "\n",
    "$$\n",
    "\\text{km for every year} = \\frac{\\text{mileage in km}}{\\text{age}}\n",
    "$$\n",
    "\n",
    "In pandas a new column is one line (Topic 11):"
   ],
   "id": "t24-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"age\"] = 2026 - df[\"year\"]\n",
    "df[\"power_to_weight\"] = df[\"horsepower\"] / df[\"weight_kg\"]\n",
    "df[\"km_per_year\"] = df[\"mileage_km\"] / df[\"age\"]\n",
    "\n",
    "print(df[[\"year\", \"age\", \"power_to_weight\", \"km_per_year\"]].head().round(3))"
   ],
   "id": "t24-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 Do they help?\n",
    "\n",
    "A created feature is an idea, and an idea has to be tested. The test is the score on the test data. The model now gets the age in the place of the year, and the two new ratios:\n",
    "\n",
    "Change it and run: take `\"power_to_weight\"` out of the list and run: the test score falls."
   ],
   "id": "t24-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df[[\"age\", \"mileage_km\", \"engine_cc\", \"horsepower\", \"weight_kg\", \"doors\", \"power_to_weight\", \"km_per_year\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t24-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The test score rises from 0.879 to 0.943. The same cars, the same model, the same split: only the features changed.\n",
    "\n",
    "### 3.4 What each new feature did\n",
    "\n",
    "| Change | Test score | Why |\n",
    "| --- | --- | --- |\n",
    "| the six numerical columns as they are | 0.879 | the starting point |\n",
    "| `age` in the place of `year` | 0.879 | no change: `age` is `year` turned round, and a linear model handles that itself |\n",
    "| adding `power_to_weight` | 0.929 | a division: the model could not build it from `horsepower` and `weight_kg` |\n",
    "| adding `km_per_year` too | 0.943 | another division, with a smaller gain |\n",
    "\n",
    "Two lessons are in this table.\n",
    "\n",
    "- A new feature helps when it holds something the model cannot calculate itself. For a linear model that means products, ratios and other curved combinations. A feature that is only a sum or a multiple of existing ones (`age` from `year`) changes nothing in the score. It is still worth making, because the model becomes easier to read: \"every year of age takes away ...\" is clearer than a weight for the year 2015.\n",
    "- Not every idea helps, and you find out only by testing. Keep the features that raise the test score (or the cross-validation score), and drop the ones that do not.\n",
    "\n",
    "### 3.5 How to find ideas\n",
    "\n",
    "| Logic | Example |\n",
    "| --- | --- |\n",
    "| a difference from a reference point | the age from a year; the days since the last purchase |\n",
    "| a ratio of two columns | power for the weight; price for every square metre; income for every member of a family |\n",
    "| a product of two columns | the area from a length and a width; the total from a price and a number of units |\n",
    "| a part of a date | the month, the day of the week (Topic 11) |\n",
    "| a total or a mean of several columns | the total of three exam marks |\n",
    "\n",
    "The question to ask is always: what would a person who knows the subject look at?\n",
    "\n",
    "## 4. Selecting features\n",
    "\n",
    "More features are not always better. A feature that says nothing adds room for overfitting, and two features that say the same confuse the model. Feature selection chooses the columns that go into the model. Its main tool here is the correlation of Topic 20.\n",
    "\n",
    "### 4.1 Covariance and correlation, once more\n",
    "\n",
    "Both measure how two columns move together.\n",
    "\n",
    "- The covariance is the average product of the deviations from the two means. Its sign says whether the columns rise together (positive) or against each other (negative). But its size depends on the units: a column in kilometres gives huge numbers, a column in doors gives small ones, and the two cannot be compared.\n",
    "- The correlation $r$ is the covariance divided by the two standard deviations. It has no units and always lies between $-1$ and 1. That makes it the tool for comparing columns."
   ],
   "id": "t24-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(df[\"mileage_km\"].cov(df[\"price\"]), 1))\n",
    "print(round(df[\"doors\"].cov(df[\"price\"]), 3))\n",
    "\n",
    "print(round(df[\"mileage_km\"].corr(df[\"price\"]), 2))\n",
    "print(round(df[\"doors\"].corr(df[\"price\"]), 2))"
   ],
   "id": "t24-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first covariance is a number in the hundreds of thousands and the second is close to zero, only because kilometres are large numbers and doors are small ones. The correlations tell the real story: the mileage moves clearly against the price, and the doors have nothing to do with it.\n",
    "\n",
    "### 4.2 Step 1: which features move with the target?"
   ],
   "id": "t24-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.corr()[\"price\"].round(2).sort_values())"
   ],
   "id": "t24-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.corr()` is the table of the correlations of all pairs of columns. `[\"price\"]` takes the column of the target, and `sort_values()` puts it in order.\n",
    "\n",
    "- Strong (far from 0, in either direction): `power_to_weight`, `weight_kg`, `horsepower`, `engine_cc`, `mileage_km`. These are candidates.\n",
    "- Close to 0: `doors`. A candidate for dropping.\n",
    "- `year` and `age` have the same strength with opposite signs: they are the same information, and one of them is enough.\n",
    "\n",
    "The created feature `power_to_weight` has the strongest correlation of all: stronger than the two columns it was made from.\n",
    "\n",
    "### 4.3 Step 2: which features say the same? Multicollinearity\n",
    "\n",
    "Two features that are strongly correlated with each other carry almost the same information. This is called multicollinearity. For a linear model it is a problem of its own:\n",
    "\n",
    "- The model cannot decide how to divide the effect between the two. One weight can become large and positive and the other large and negative, and they change strongly from one sample to the next (the variance of Topic 23).\n",
    "- The weights can no longer be read: \"the effect of the horsepower with the engine size held fixed\" means little when the two always move together.\n",
    "- The predictions are usually still fine. Multicollinearity damages the explanation, not the score."
   ],
   "id": "t24-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "features = df.drop(columns=[\"price\", \"year\"])\n",
    "\n",
    "print(features.corr().round(2).to_string())"
   ],
   "id": "t24-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`to_string()` prints the whole table; without it pandas leaves out the middle columns of a wide table. Read it for values close to 1 or $-1$ outside the diagonal:\n",
    "\n",
    "- `engine_cc` and `horsepower`: 0.93. A larger engine has more power: the two columns say almost the same.\n",
    "- `power_to_weight` with `weight_kg` ($-0.71$) and with `horsepower` (0.65), `mileage_km` with `age` and with `km_per_year` (0.65): related, as expected for features made from one another, but far from saying the same.\n",
    "\n",
    "A common rule of thumb: a pair above about 0.9 (or below $-0.9$) is one feature too many.\n",
    "\n",
    "The same table as a picture, the heatmap of Topic 12:"
   ],
   "id": "t24-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.heatmap(features.corr().round(2), annot=True, cmap=\"coolwarm\", vmin=-1, vmax=1)\n",
    "plt.title(\"Correlations between the features\")\n",
    "plt.show()"
   ],
   "id": "t24-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.4 Step 3: the choice\n",
    "\n",
    "- `engine_cc` and `horsepower` say the same. Keep the one that is more strongly correlated with the price: `horsepower` (0.56 against 0.52). Drop `engine_cc`.\n",
    "- `doors` has a correlation of $-0.01$ with the price. Drop it.\n",
    "- `year` is replaced by `age`.\n",
    "\n",
    "Six features remain. Does the score suffer?"
   ],
   "id": "t24-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df[[\"age\", \"mileage_km\", \"horsepower\", \"weight_kg\", \"power_to_weight\", \"km_per_year\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t24-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Eight features gave 0.943, six give 0.942. Two columns less, and nothing lost: the model is simpler, and its weights can be read again. These six features are the ones the rest of the lesson works with.\n",
    "\n",
    "### 4.5 The limits of this method\n",
    "\n",
    "- Correlation sees only straight lines (Topic 20). A feature with a curved relationship to the target can have a correlation near 0 and still be useful.\n",
    "- A feature can be weak alone and useful together with others. The final judge is the score on data the model has not seen: try the model with and without the feature, with the test score or with cross-validation (Topic 23).\n",
    "- A strong correlation is not a cause.\n",
    "\n",
    "## 5. Why scale?\n",
    "\n",
    "### 5.1 Columns of very different sizes"
   ],
   "id": "t24-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(X.describe().loc[[\"min\", \"max\"]].round(2).T)"
   ],
   "id": "t24-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mileage runs into the hundreds of thousands. The power for the weight is always below 1. The largest value of one column is several million times the largest value of another. These sizes say nothing about importance: they come from the units. A distance in kilometres is a large number; the same distance in thousands of kilometres would be a small one.\n",
    "\n",
    "Scaling changes the numbers of every column to a comparable size, without changing what they say: the order of the cars in a column stays the same, and so do the relative distances between them.\n",
    "\n",
    "### 5.2 Three reasons\n",
    "\n",
    "1. The weights become comparable. The weights of the model with the six features:"
   ],
   "id": "t24-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name, weight in zip(X.columns, model.coef_):\n",
    "    print(name, round(weight, 4))"
   ],
   "id": "t24-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The weight of `power_to_weight` is in the hundreds, and the weight of `mileage_km` prints as `-0.0`. That does not mean that the power matters and the mileage does not. A weight is the change for one unit of its feature (Topic 22): one kilometre more changes almost nothing, and \"one unit more\" of `power_to_weight` is far more than the difference between the weakest and the strongest car. Weights of features on different scales cannot be compared. After scaling they can (Part 8).\n",
    "\n",
    "2. Gradient descent needs it. Topic 22 trained a line by walking down the loss with a learning rate. With features of very different sizes, the loss is a valley that is extremely steep in one direction and almost flat in another. A step that is small enough for the steep direction makes no progress in the flat one, and a step that is large enough for the flat direction jumps out of the valley in the steep one.\n",
    "\n",
    "`LinearRegression` does not walk: it uses the exact formulas, so it does not suffer from this. scikit-learn also has a linear regression that is trained by gradient descent, `SGDRegressor`. It is used exactly like `LinearRegression`. On the unscaled cars:"
   ],
   "id": "t24-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import SGDRegressor\n",
    "\n",
    "sgd = SGDRegressor(random_state=0)\n",
    "sgd.fit(X_train, y_train)\n",
    "\n",
    "print(sgd.score(X_test, y_test) < 0)"
   ],
   "id": "t24-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The score is not only below 0: it is a negative number with dozens of digits. The walk ran away, as with a learning rate that is too large in Topic 22. The same model on scaled features works well, as Part 8 shows. Most models of modern machine learning are trained by gradient descent, so for them scaling is not a nicety. It decides whether the training works.\n",
    "\n",
    "3. Distances need it. Many later models compare samples by their distance (k-nearest neighbours, k-means, support vector machines). In a distance, a feature with large numbers decides almost alone: two cars that differ by 20,000 km are \"far apart\", whatever their age and power. Regularization (Topic 26) and principal component analysis depend on the scale in a similar way.\n",
    "\n",
    "### 5.3 Which models need scaling?\n",
    "\n",
    "| Needs scaling | Does not need it |\n",
    "| --- | --- |\n",
    "| models trained by gradient descent (`SGDRegressor`, logistic regression, neural networks) | `LinearRegression` with its exact formulas: the predictions and the score stay the same |\n",
    "| models that use distances (k-nearest neighbours, k-means, support vector machines) | decision trees and the models built from them (random forests, boosting) |\n",
    "| regularized models (Ridge, Lasso), principal component analysis |  |\n",
    "\n",
    "When in doubt, scale: it rarely hurts, and for `LinearRegression` it still makes the weights comparable.\n",
    "\n",
    "## 6. Four ways of scaling\n",
    "\n",
    "All four are shown on the same five values, so that you can see what each one does: `10, 20, 30, 40, 100`. Four values lie close together and one, 100, lies far away: an outlier.\n",
    "\n",
    "### 6.1 Min-max scaling\n",
    "\n",
    "$$\n",
    "x_{\\text{scaled}} = \\frac{x - \\min}{\\max - \\min}\n",
    "$$\n",
    "\n",
    "The smallest value becomes 0, the largest becomes 1, and everything else lies in between.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\min = 10 \\qquad \\max = 100 \\\\[4pt]\n",
    "& \\max - \\min = 90 \\\\[8pt]\n",
    "10:\\quad & \\frac{10 - 10}{90} = 0 \\\\[4pt]\n",
    "20:\\quad & \\frac{20 - 10}{90} = 0.111 \\\\[4pt]\n",
    "30:\\quad & \\frac{30 - 10}{90} = 0.222 \\\\[4pt]\n",
    "40:\\quad & \\frac{40 - 10}{90} = 0.333 \\\\[4pt]\n",
    "100:\\quad & \\frac{100 - 10}{90} = 1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "- For: easy to understand, and a fixed range from 0 to 1. Useful when the values have natural limits (a percentage, the brightness of a pixel).\n",
    "- Against: the minimum and the maximum are the two values most exposed to outliers. Here the single value 100 squeezes the other four into the lowest third of the range.\n",
    "\n",
    "### 6.2 Standard scaling\n",
    "\n",
    "$$\n",
    "x_{\\text{scaled}} = \\frac{x - \\text{mean}}{\\text{standard deviation}}\n",
    "$$\n",
    "\n",
    "This is the z-score of Topic 18: how many standard deviations a value lies above or below the mean. After it the column has the mean 0 and the standard deviation 1.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{mean} = \\frac{10 + 20 + 30 + 40 + 100}{5} = 40 \\\\[6pt]\n",
    "& \\text{squared deviations:} \\\\\n",
    "& 900 + 400 + 100 + 0 + 3600 = 5000 \\\\[6pt]\n",
    "& \\text{standard deviation} = \\sqrt{\\frac{5000}{5}} \\\\[4pt]\n",
    "& \\qquad = \\sqrt{1000} = 31.623\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "10:\\quad & \\frac{10 - 40}{31.623} = -0.949 \\\\[4pt]\n",
    "20:\\quad & \\frac{20 - 40}{31.623} = -0.632 \\\\[4pt]\n",
    "30:\\quad & \\frac{30 - 40}{31.623} = -0.316 \\\\[4pt]\n",
    "40:\\quad & \\frac{40 - 40}{31.623} = 0 \\\\[4pt]\n",
    "100:\\quad & \\frac{100 - 40}{31.623} = 1.897\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "(scikit-learn divides the sum of squares by $n$, the population formula of Topic 18, not by $n - 1$. For scaling the difference does not matter.)\n",
    "\n",
    "- For: the usual first choice. It has no fixed limits, so an outlier is not squeezed against a wall, and it suits models that are trained by gradient descent.\n",
    "- Against: the mean and the standard deviation are themselves moved by outliers (Topic 18): here the value 100 pulls the mean up to 40, above four of the five values.\n",
    "\n",
    "### 6.3 Robust scaling\n",
    "\n",
    "$$\n",
    "x_{\\text{scaled}} = \\frac{x - \\text{median}}{\\text{IQR}} \\qquad \\text{IQR} = Q_3 - Q_1\n",
    "$$\n",
    "\n",
    "It uses the median and the interquartile range of Topic 18, which outliers hardly move.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{median} = 30 \\qquad Q_1 = 20 \\qquad Q_3 = 40 \\\\[4pt]\n",
    "& \\text{IQR} = 40 - 20 = 20 \\\\[8pt]\n",
    "10:\\quad & \\frac{10 - 30}{20} = -1 \\\\[4pt]\n",
    "20:\\quad & \\frac{20 - 30}{20} = -0.5 \\\\[4pt]\n",
    "30:\\quad & \\frac{30 - 30}{20} = 0 \\\\[4pt]\n",
    "40:\\quad & \\frac{40 - 30}{20} = 0.5 \\\\[4pt]\n",
    "100:\\quad & \\frac{100 - 30}{20} = 3.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "- For: the four ordinary values are spread evenly around 0, as if the outlier were not there. The outlier itself stays far away, visibly.\n",
    "- Against: no fixed range.\n",
    "\n",
    "### 6.4 The log transform\n",
    "\n",
    "$$\n",
    "x_{\\text{scaled}} = \\log(x)\n",
    "$$\n",
    "\n",
    "The logarithm is different from the other three. They move and stretch a column evenly; the logarithm changes its shape: it pulls large values in much more than small ones. With the logarithm to the base 10:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "10:\\quad & \\log_{10}(10) = 1 \\\\\n",
    "20:\\quad & \\log_{10}(20) = 1.301 \\\\\n",
    "30:\\quad & \\log_{10}(30) = 1.477 \\\\\n",
    "40:\\quad & \\log_{10}(40) = 1.602 \\\\\n",
    "100:\\quad & \\log_{10}(100) = 2\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The value 100 was ten times the value 10; now it is twice as large. Equal ratios become equal distances: from 10 to 100 is as far as from 100 to 1,000.\n",
    "\n",
    "- For: columns with a long tail of large values: incomes, prices, mileages, numbers of visitors. Many such quantities work in ratios in real life: the difference between 10,000 and 20,000 km matters more than the difference between 210,000 and 220,000 km.\n",
    "- Against: only for positive values (the logarithm of 0 or of a negative number does not exist; for columns with zeros `np.log1p(x)`, the logarithm of $x + 1$, is used). And because it changes the shape, it changes the model: the score of a linear regression can go up or down.\n",
    "\n",
    "### 6.5 The four side by side\n",
    "\n",
    "|  | Min-max | Standard | Robust | Logarithm |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Formula | $\\frac{x - \\min}{\\max - \\min}$ | $\\frac{x - \\text{mean}}{\\text{std}}$ | $\\frac{x - \\text{median}}{\\text{IQR}}$ | $\\log(x)$ |\n",
    "| Result | from 0 to 1 | mean 0, standard deviation 1 | median 0 | a new shape |\n",
    "| Outliers | squeeze all other values | pull the mean and the spread | hardly matter | are pulled in |\n",
    "| Changes the shape of the column | no | no | no | yes |\n",
    "| In scikit-learn | `MinMaxScaler` | `StandardScaler` | `RobustScaler` | `np.log` (NumPy) |\n",
    "| Use it when | a fixed range is needed; no strong outliers | the usual first choice | the column has outliers | the column has a long tail of large positive values |\n",
    "\n",
    "### 6.6 In Python\n",
    "\n",
    "The three scalers of scikit-learn live in `sklearn.preprocessing` and are used in the same way. Here is `MinMaxScaler` on the training data of the cars:"
   ],
   "id": "t24-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "scaler = MinMaxScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "\n",
    "print(X_train_scaled[:3].round(3))\n",
    "print(X_train_scaled.min(axis=0))\n",
    "print(X_train_scaled.max(axis=0))"
   ],
   "id": "t24-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is a NumPy array with the same rows and columns. The first print shows three cars: every number now lies between 0 and 1. The other two prints are the smallest and the largest value of every column (`axis=0`, as in Topic 9): exactly 0 and 1.\n",
    "\n",
    "`StandardScaler` gives every column the mean 0 and the standard deviation 1:"
   ],
   "id": "t24-031"
  },
  {
   "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",
    "\n",
    "print(X_train_scaled[:3].round(3))\n",
    "print(X_train_scaled.mean(axis=0).round(3))\n",
    "print(X_train_scaled.std(axis=0).round(3))"
   ],
   "id": "t24-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The values are now positive and negative: above and below the mean of their column. (A mean printed as `-0.` is zero: a tiny rounding remainder with a minus sign.)\n",
    "\n",
    "`RobustScaler` gives every column the median 0. To see what the three scalers do with an outlier, compare the largest value of the column `mileage_km`, a car with more than 500,000 km, under each of them:"
   ],
   "id": "t24-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler\n",
    "\n",
    "for scaler in [MinMaxScaler(), StandardScaler(), RobustScaler()]:\n",
    "    mileage = scaler.fit_transform(X_train)[:, 1]\n",
    "    print(type(scaler).__name__, round(mileage.min(), 2), round(pd.Series(mileage).median(), 2), round(mileage.max(), 2))"
   ],
   "id": "t24-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the smallest value, the median and the largest value of the scaled mileage (`[:, 1]` is the second column). With min-max the median lies at about 0.2: most cars are pressed into the lower part of the range by a few cars with a very high mileage. With the robust scaler the median is exactly 0 and the ordinary cars lie around it; the extreme car stands out at more than 3.\n",
    "\n",
    "### 6.7 The logarithm on a column with a long tail\n",
    "\n",
    "The mileage is such a column: most cars have between 50,000 and 200,000 km, and a few have 400,000 or more."
   ],
   "id": "t24-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.hist(df[\"mileage_km\"], bins=20)\n",
    "plt.xlabel(\"mileage_km\")\n",
    "plt.ylabel(\"number of cars\")\n",
    "plt.title(\"The mileage: a long tail to the right\")\n",
    "plt.show()"
   ],
   "id": "t24-036"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df[\"log_mileage\"] = np.log(df[\"mileage_km\"])\n",
    "\n",
    "plt.hist(df[\"log_mileage\"], bins=20)\n",
    "plt.xlabel(\"log of mileage_km\")\n",
    "plt.ylabel(\"number of cars\")\n",
    "plt.title(\"After the logarithm: the tail is pulled in\")\n",
    "plt.show()"
   ],
   "id": "t24-037"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The correlation with the price, before and after:"
   ],
   "id": "t24-038"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(df[\"mileage_km\"].corr(df[\"price\"]), 2))\n",
    "print(round(df[\"log_mileage\"].corr(df[\"price\"]), 2))"
   ],
   "id": "t24-039"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`np.log` is the natural logarithm of NumPy; which base is used makes no difference for a model. After the transform the long tail to the right is gone, and the correlation of the column with the price is a little stronger: the price follows the ratio of the mileages, not their difference. Part 8 shows what that does to the score.\n",
    "\n",
    "## 7. fit, transform, and the order of the steps\n",
    "\n",
    "### 7.1 Two actions\n",
    "\n",
    "A scaler works in two steps, and it is important to keep them apart.\n",
    "\n",
    "- `fit` looks at data and learns the numbers the scaler needs: the minimum and the maximum of every column for `MinMaxScaler`, the mean and the standard deviation for `StandardScaler`, the median and the quartiles for `RobustScaler`. It changes nothing.\n",
    "- `transform` applies these learned numbers to data and returns the scaled values. It learns nothing.\n",
    "- `fit_transform` does both, one after the other, on the same data. It is a shortcut."
   ],
   "id": "t24-040"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "scaler = MinMaxScaler()\n",
    "scaler.fit(X_train)\n",
    "\n",
    "for name, low, high in zip(X.columns, scaler.data_min_, scaler.data_max_):\n",
    "    print(name, round(low, 2), round(high, 2))"
   ],
   "id": "t24-041"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After `fit`, the scaler holds the smallest and the largest value of every column of the training data: `data_min_` and `data_max_`. The loop prints them next to the names of the columns. The names end in an underscore, because they were learned from data (Topic 21). This is the same idea as `model.fit`: a model learns its weights, a scaler learns its numbers.\n",
    "\n",
    "### 7.2 The split comes first\n",
    "\n",
    "The order of the steps is the most important rule of this lesson:\n",
    "\n",
    "1. Split the data into a training part and a test part.\n",
    "2. `fit` the scaler on the training data only.\n",
    "3. `transform` the training data and the test data with that one scaler.\n",
    "\n",
    "### 7.3 Why not scale first and split afterwards?\n",
    "\n",
    "It looks simpler to scale the whole table once and split it later. It is wrong, and the reason is the rule of Topic 23: the test data stands for data the model has never seen.\n",
    "\n",
    "When a scaler is fitted on all the rows, its minimum, maximum, mean and standard deviation are calculated from the test rows too. Something about the test data (how large its values are, where its extremes lie) has then flowed into the numbers the training data is scaled with. That is data leakage. The test is no longer a test of unseen data, and its score is a little too flattering.\n",
    "\n",
    "Think of the model in real use. A new car arrives tomorrow. It has to be scaled with numbers that exist today, and those are the numbers of the training data. The test data must be treated exactly like that new car."
   ],
   "id": "t24-042"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(X[\"mileage_km\"].mean(), 1), round(X[\"mileage_km\"].std(), 1))\n",
    "print(round(X_train[\"mileage_km\"].mean(), 1), round(X_train[\"mileage_km\"].std(), 1))"
   ],
   "id": "t24-043"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line is the mean and the standard deviation of the mileage in all 240 cars, the second in the 192 training cars. They differ. A `StandardScaler` fitted on all the rows would use the first pair, and that pair contains the 48 test cars.\n",
    "\n",
    "### 7.4 Train and test: who gets what"
   ],
   "id": "t24-044"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "scaler = MinMaxScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(X_train_scaled.min(axis=0).round(2), X_train_scaled.max(axis=0).round(2))\n",
    "print(X_test_scaled.min(axis=0).round(2), X_test_scaled.max(axis=0).round(2))"
   ],
   "id": "t24-045"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The training data lies exactly between 0 and 1: its own minimum and maximum were used. The test data does not: its smallest values are not all 0, and one of its largest values is above 1 (the fifth column, 1.09), because a test car can have more power for its weight than every training car. That is correct, and it is what happens with every new car in real use. Do not \"repair\" it by fitting the scaler again.\n",
    "\n",
    "| Data | What to call | Why |\n",
    "| --- | --- | --- |\n",
    "| training data | `scaler.fit_transform(X_train)` | learn the numbers and apply them |\n",
    "| test data | `scaler.transform(X_test)` | apply the numbers of the training data |\n",
    "| new data in real use | `scaler.transform(X_new)` | the same |\n",
    "| never | `scaler.fit(X_test)`, `scaler.fit_transform(X_test)`, `scaler.fit(X)` before the split | the test data would shape its own scaling |\n",
    "\n",
    "Only the features are scaled. The target `y` stays as it is.\n",
    "\n",
    "### 7.5 Which steps come before the split?\n",
    "\n",
    "| Step | Before or after the split? | Why |\n",
    "| --- | --- | --- |\n",
    "| dropping columns | before | it uses the meaning of a column, not its values |\n",
    "| creating a feature from the columns of the same row (`age`, `power_to_weight`) | before | every row is calculated from itself alone; nothing is learned from other rows |\n",
    "| the logarithm of a column | before or after | every value is transformed by itself; nothing is learned |\n",
    "| min-max, standard, robust scaling | fit after the split, on the training data | the scaler learns numbers from the rows it sees |\n",
    "\n",
    "The question that decides: does the step learn something from the rows? If it does, it learns from the training rows only.\n",
    "\n",
    "## 8. Every scaler at once, and the scores\n",
    "\n",
    "Now the comparison the lesson has been building up to: the same six features, the same split, four ways of scaling, two models.\n",
    "\n",
    "### 8.1 `LinearRegression`"
   ],
   "id": "t24-046"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler\n",
    "\n",
    "for scaler in [MinMaxScaler(), StandardScaler(), RobustScaler()]:\n",
    "    X_train_scaled = scaler.fit_transform(X_train)\n",
    "    X_test_scaled = scaler.transform(X_test)\n",
    "    model = LinearRegression()\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(type(scaler).__name__, round(model.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t24-047"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three scalers, one score, and it is the score without scaling (0.942). This is not a mistake. Min-max, standard and robust scaling only move and stretch every column, and a linear regression with exact formulas adjusts its weights to any such change: the predictions stay the same. For this model scaling changes the weights, not the score.\n",
    "\n",
    "### 8.2 `SGDRegressor`: the model that walks"
   ],
   "id": "t24-048"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import SGDRegressor\n",
    "from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler\n",
    "\n",
    "for scaler in [MinMaxScaler(), StandardScaler(), RobustScaler()]:\n",
    "    X_train_scaled = scaler.fit_transform(X_train)\n",
    "    X_test_scaled = scaler.transform(X_test)\n",
    "    sgd = SGDRegressor(random_state=0)\n",
    "    sgd.fit(X_train_scaled, y_train)\n",
    "    print(type(scaler).__name__, round(sgd.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t24-049"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Without scaling this model failed completely (Part 5). With any of the three scalers it works, and now the scalers differ a little, because the shape of the valley decides how far the walk gets in its steps. `random_state=0` fixes the random order in which the model visits the rows.\n",
    "\n",
    "### 8.3 The scores side by side\n",
    "\n",
    "| Scaling | `LinearRegression` | `SGDRegressor` |\n",
    "| --- | --- | --- |\n",
    "| none | 0.942 | fails (far below 0) |\n",
    "| min-max | 0.942 | 0.935 |\n",
    "| standard | 0.942 | 0.946 |\n",
    "| robust | 0.942 | 0.946 |\n",
    "\n",
    "### 8.4 Weights that can be compared\n",
    "\n",
    "With standard scaling every feature has the same spread, so one unit means the same for all of them: one standard deviation."
   ],
   "id": "t24-050"
  },
  {
   "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",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "for name, weight in zip(X.columns, model.coef_):\n",
    "    print(name, round(weight, 2))"
   ],
   "id": "t24-051"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the weights tell a story. A car whose power for the weight is one standard deviation above the average costs about 12.6 thousand more; one standard deviation of age takes away almost 6 thousand. The power for the weight is the strongest feature, the age the second. In Part 5 the weight of the mileage printed as `-0.0`; that was only the unit.\n",
    "\n",
    "### 8.5 The logarithm changes the score\n",
    "\n",
    "The logarithm is the one transform that changes the shape of a column, so it is the one that can change the score of a linear regression. The model gets the logarithm of the mileage in the place of the two mileage features:"
   ],
   "id": "t24-052"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "df[\"log_mileage\"] = np.log(df[\"mileage_km\"])\n",
    "\n",
    "X = df[[\"age\", \"log_mileage\", \"horsepower\", \"weight_kg\", \"power_to_weight\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t24-053"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The test score rises from 0.942 to 0.954, with one feature less. For these cars the price falls with the ratio of the mileages: the first 50,000 km cost a car much more of its value than the 50,000 km between 250,000 and 300,000. A straight line through the raw mileage cannot follow that; a straight line through its logarithm can.\n",
    "\n",
    "### 8.6 The road from the first model to the last\n",
    "\n",
    "| Step | Features | Test score |\n",
    "| --- | --- | --- |\n",
    "| the numerical columns as they are (Part 1) | 6 | 0.879 |\n",
    "| created features added (Part 3) | 8 | 0.943 |\n",
    "| after selection (Part 4) | 6 | 0.942 |\n",
    "| the logarithm of the mileage (Part 8) | 5 | 0.954 |\n",
    "\n",
    "The model never changed. It was `LinearRegression` from the first line to the last. Everything was won by the work on the features.\n",
    "\n",
    "## 9. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Leaving an identification number among the features. | It names a row and describes nothing; a model can only memorise it. | Drop it before modelling. |\n",
    "| Dropping a column only because its name looks unimportant. | Whether a column matters is decided by its meaning and by the test score. | Ask whether it can sensibly influence the target; test with and without it. |\n",
    "| Creating a feature from the target (`price_per_kg = price / weight_kg`) and using it as a feature. | The feature contains the answer: data leakage. | Create features only from other features. |\n",
    "| Expecting that `age = 2026 - year` raises the score of a linear model. | It is the same information turned round. | Create ratios and products; keep `age` for readability. |\n",
    "| Keeping two features with a correlation of 0.95. | They say the same; the weights become unstable and unreadable. | Keep one of them. |\n",
    "| Dropping every feature with a low correlation to the target. | Correlation sees only straight lines, and a feature can help together with others. | Use correlation as a first look and the test score as the judge. |\n",
    "| Scaling the whole table and splitting afterwards. | The test rows shape the numbers of the scaler: data leakage. | Split first; `fit` on the training data. |\n",
    "| `scaler.fit_transform(X_test)` | The test data gets its own scaling, different from the one the model was trained with. | `scaler.transform(X_test)` |\n",
    "| A second scaler for the test data. | The same value would become two different numbers in the two parts. | One scaler, fitted once on the training data. |\n",
    "| Scaling the target `y` together with the features. | The predictions would be in scaled units. | Scale the features only. |\n",
    "| \"After min-max scaling the test data must lie between 0 and 1.\" | The limits come from the training data; a test value can lie outside them. | Values slightly below 0 or above 1 are correct. |\n",
    "| Expecting a better score from scaling for `LinearRegression`. | Its predictions do not change with min-max, standard or robust scaling. | Scale for comparable weights, and for the models that need it. |\n",
    "| Training an `SGDRegressor` on unscaled features. | Gradient descent runs away when the features have very different sizes. | Scale first. |\n",
    "| `np.log` on a column with zeros or negative values. | The logarithm does not exist there. | `np.log1p` for columns with zeros; no logarithm for negative values. |\n",
    "| Using min-max scaling on a column with strong outliers. | One extreme value presses all the others into a corner. | `RobustScaler`, or the logarithm for a long tail. |\n",
    "\n",
    "## 10. Solved problems\n",
    "\n",
    "Ten problems. The first three are short calculations by hand; the others are in Python on `cars.csv`, and each one runs on its own (the second cell of Problem 9 continues from its first).\n",
    "\n",
    "Problem 1. Min-max by hand\n",
    "\n",
    "Scale the values `4, 6, 10, 20` with min-max scaling.\n",
    "\n",
    "Idea. $\\frac{x - \\min}{\\max - \\min}$ (Part 6).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\min = 4 \\qquad \\max = 20 \\\\[4pt]\n",
    "& \\max - \\min = 16 \\\\[8pt]\n",
    "4:\\quad & \\frac{4 - 4}{16} = 0 \\\\[4pt]\n",
    "6:\\quad & \\frac{6 - 4}{16} = 0.125 \\\\[4pt]\n",
    "10:\\quad & \\frac{10 - 4}{16} = 0.375 \\\\[4pt]\n",
    "20:\\quad & \\frac{20 - 4}{16} = 1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the smallest value becomes 0 and the largest 1. The order and the relative distances stay: 10 lies three eighths of the way from 4 to 20, before and after.\n",
    "\n",
    "Problem 2. Standard scaling by hand\n",
    "\n",
    "Scale the values `2, 4, 6, 8` with standard scaling.\n",
    "\n",
    "Idea. $\\frac{x - \\text{mean}}{\\text{standard deviation}}$, with the standard deviation that divides by $n$ (Part 6).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{mean} &= \\frac{2 + 4 + 6 + 8}{4} = 5 \\\\[6pt]\n",
    "\\text{squared deviations:}\\quad & 9 + 1 + 1 + 9 = 20 \\\\[6pt]\n",
    "\\text{standard deviation} &= \\sqrt{\\frac{20}{4}} = \\sqrt{5} = 2.236 \\\\[8pt]\n",
    "2:\\quad & \\frac{2 - 5}{2.236} = -1.342 \\\\[4pt]\n",
    "4:\\quad & \\frac{4 - 5}{2.236} = -0.447 \\\\[4pt]\n",
    "6:\\quad & \\frac{6 - 5}{2.236} = 0.447 \\\\[4pt]\n",
    "8:\\quad & \\frac{8 - 5}{2.236} = 1.342\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the scaled values add up to 0 (their mean is 0), and they are symmetric because the original values are. A value of $-1.342$ lies 1.342 standard deviations below the mean.\n",
    "\n",
    "Problem 3. An outlier and two scalers\n",
    "\n",
    "Scale the values `1, 2, 3, 4, 50` with min-max scaling and with robust scaling. What happens to the four small values?\n",
    "\n",
    "Idea. Min-max uses the extremes; the robust scaler uses the median and the quartiles (Part 6).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\textbf{Min-max} \\\\[4pt]\n",
    "& \\min = 1 \\qquad \\max = 50 \\\\[4pt]\n",
    "& \\max - \\min = 49 \\\\[6pt]\n",
    "1:\\quad & 0 \\\\\n",
    "2:\\quad & \\frac{1}{49} = 0.02 \\\\[4pt]\n",
    "3:\\quad & \\frac{2}{49} = 0.041 \\\\[4pt]\n",
    "4:\\quad & \\frac{3}{49} = 0.061 \\\\[4pt]\n",
    "50:\\quad & 1 \\\\[10pt]\n",
    "& \\textbf{Robust} \\\\[4pt]\n",
    "& \\text{median} = 3 \\quad Q_1 = 2 \\quad Q_3 = 4 \\\\[4pt]\n",
    "& \\text{IQR} = 4 - 2 = 2 \\\\[6pt]\n",
    "1:\\quad & \\frac{1 - 3}{2} = -1 \\\\[4pt]\n",
    "2:\\quad & -0.5 \\\\\n",
    "3:\\quad & 0 \\\\\n",
    "4:\\quad & 0.5 \\\\\n",
    "50:\\quad & \\frac{50 - 3}{2} = 23.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: with min-max the four ordinary values are pressed into the first 6 percent of the range: they are almost indistinguishable. With the robust scaler they are spread evenly from $-1$ to 0.5, and the outlier stands far away at 23.5. The outlier is not removed by either method; the robust scaler only stops it from deciding the scale.\n",
    "\n",
    "Problem 4. Columns to drop\n",
    "\n",
    "Find the columns of `cars.csv` that have one value for every row, or a single value in all rows.\n",
    "\n",
    "Idea. `nunique()` counts the different values; compare it with the number of rows (Part 2)."
   ],
   "id": "t24-054"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "\n",
    "counts = df.nunique()\n",
    "print(counts[counts == len(df)].index.tolist())\n",
    "print(counts[counts == 1].index.tolist())"
   ],
   "id": "t24-055"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a column with as many values as rows names the rows: an identification number. A column with one value is a constant. Both carry no information for a model. (`owner_name` must be found by its meaning.)\n",
    "\n",
    "Problem 5. A new feature\n",
    "\n",
    "Create the feature `cc_per_kg`, the engine size for every kilogram of weight, and print its correlation with the price next to the correlations of the two columns it is made from.\n",
    "\n",
    "Idea. A ratio of two columns is one line; `corr` measures how it moves with the target (Parts 3 and 4)."
   ],
   "id": "t24-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "\n",
    "df[\"cc_per_kg\"] = df[\"engine_cc\"] / df[\"weight_kg\"]\n",
    "\n",
    "print(round(df[\"engine_cc\"].corr(df[\"price\"]), 2))\n",
    "print(round(df[\"weight_kg\"].corr(df[\"price\"]), 2))\n",
    "print(round(df[\"cc_per_kg\"].corr(df[\"price\"]), 2))"
   ],
   "id": "t24-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the ratio is more strongly correlated with the price than either of its parts. A large engine in a light car is what the price follows, and that only shows when the two columns are combined.\n",
    "\n",
    "Problem 6. Pairs that say the same\n",
    "\n",
    "Print the correlation between `engine_cc` and `horsepower`, and between `year` and `mileage_km`. Which pair is a case of multicollinearity?\n",
    "\n",
    "Idea. A correlation between two features above about 0.9 or below $-0.9$ (Part 4)."
   ],
   "id": "t24-058"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "\n",
    "print(round(df[\"engine_cc\"].corr(df[\"horsepower\"]), 2))\n",
    "print(round(df[\"year\"].corr(df[\"mileage_km\"]), 2))"
   ],
   "id": "t24-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the engine size and the horsepower have a correlation of 0.93: they carry almost the same information, and one of them is enough. The year and the mileage are related (older cars have driven more), but $-0.65$ leaves each of them plenty to say on its own.\n",
    "\n",
    "Problem 7. Does a feature help?\n",
    "\n",
    "Compare two models with the test score: one with the six numerical columns of the file, and one that also gets `power_to_weight`.\n",
    "\n",
    "Idea. The judge of a created feature is the score on the test data (Part 3)."
   ],
   "id": "t24-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "df[\"power_to_weight\"] = df[\"horsepower\"] / df[\"weight_kg\"]\n",
    "y = df[\"price\"]\n",
    "\n",
    "columns = [\"year\", \"mileage_km\", \"engine_cc\", \"horsepower\", \"weight_kg\", \"doors\"]\n",
    "\n",
    "for features in [columns, columns + [\"power_to_weight\"]]:\n",
    "    X_train, X_test, y_train, y_test = train_test_split(df[features], y, test_size=0.2, random_state=42)\n",
    "    model = LinearRegression()\n",
    "    model.fit(X_train, y_train)\n",
    "    print(len(features), round(model.score(X_test, y_test), 3))"
   ],
   "id": "t24-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the seventh feature is calculated from two columns the model already has, and still the score rises: a linear model can add and weight its columns, but it cannot divide them. The same `random_state` gives the same split for both models, so the comparison is fair.\n",
    "\n",
    "Problem 8. Scale after the split\n",
    "\n",
    "Take the features `mileage_km` and `weight_kg`. Split the data, fit a `StandardScaler` on the training data, and transform both parts. Print the means of the two columns in the scaled training data and in the scaled test data.\n",
    "\n",
    "Idea. `fit_transform` on the training data, `transform` on the test data (Part 7)."
   ],
   "id": "t24-062"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "X = df[[\"mileage_km\", \"weight_kg\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\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.mean(axis=0).round(2))\n",
    "print(X_test_scaled.mean(axis=0).round(2))"
   ],
   "id": "t24-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the means of the training data are 0, because its own means were subtracted. The means of the test data are close to 0 but not exactly 0, because the means of the training data were subtracted from it. That small difference is correct: it is what happens to every new car.\n",
    "\n",
    "Problem 9. A model that needs scaling\n",
    "\n",
    "Train an `SGDRegressor` on `mileage_km`, `horsepower` and `weight_kg`, once without scaling and once with a `StandardScaler`. Print for the first model whether its test score is below 0, and for the second its test score.\n",
    "\n",
    "Idea. Gradient descent runs away on features of very different sizes (Parts 5 and 8)."
   ],
   "id": "t24-064"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.linear_model import SGDRegressor\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "X = df[[\"mileage_km\", \"horsepower\", \"weight_kg\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = SGDRegressor(random_state=0)\n",
    "model.fit(X_train, y_train)\n",
    "print(model.score(X_test, y_test) < 0)"
   ],
   "id": "t24-065"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same data and the same model, after scaling:"
   ],
   "id": "t24-066"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "model = SGDRegressor(random_state=0)\n",
    "model.fit(X_train_scaled, y_train)\n",
    "print(round(model.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t24-067"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the same model and the same data: without scaling the training fails, with scaling it gives a usable score. Nothing about the cars changed, only the size of the numbers.\n",
    "\n",
    "Problem 10. The logarithm of a skewed column\n",
    "\n",
    "Compare two models with the test score: one with `mileage_km` and `power_to_weight`, and one with the logarithm of the mileage in the place of the mileage.\n",
    "\n",
    "Idea. The logarithm changes the shape of a column with a long tail, and with it the model (Parts 6 and 8)."
   ],
   "id": "t24-068"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "df = pd.read_csv(\"cars.csv\")\n",
    "df[\"power_to_weight\"] = df[\"horsepower\"] / df[\"weight_kg\"]\n",
    "df[\"log_mileage\"] = np.log(df[\"mileage_km\"])\n",
    "y = df[\"price\"]\n",
    "\n",
    "for columns in [[\"mileage_km\", \"power_to_weight\"], [\"log_mileage\", \"power_to_weight\"]]:\n",
    "    X_train, X_test, y_train, y_test = train_test_split(df[columns], y, test_size=0.2, random_state=42)\n",
    "    model = LinearRegression()\n",
    "    model.fit(X_train, y_train)\n",
    "    print(columns[0], round(model.score(X_test, y_test), 3))"
   ],
   "id": "t24-069"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the score with the logarithm is clearly higher. The price of these cars follows the ratio of the mileages, and the logarithm turns ratios into the equal steps a straight line needs.\n",
    "\n",
    "## 13. Summary\n",
    "\n",
    "| Step | What is done | Why |\n",
    "| --- | --- | --- |\n",
    "| Drop | identification numbers, names, constants | they carry no information and invite overfitting |\n",
    "| Create | ages, ratios, products, parts of dates | to give the model what it cannot calculate itself |\n",
    "| Select | drop features with no relationship to the target, and one of every pair that says the same | a simpler, more stable model with readable weights |\n",
    "| Split | training data and test data | before anything is learned from the rows |\n",
    "| Scale | `fit` on the training data, `transform` both parts | comparable sizes, without data leakage |\n",
    "| Model | train on the scaled training data, judge on the scaled test data |  |\n",
    "\n",
    "| Scaler | Formula | Use it when |\n",
    "| --- | --- | --- |\n",
    "| `MinMaxScaler` | $\\frac{x - \\min}{\\max - \\min}$ | a range from 0 to 1 is needed and there are no strong outliers |\n",
    "| `StandardScaler` | $\\frac{x - \\text{mean}}{\\text{std}}$ | the usual first choice |\n",
    "| `RobustScaler` | $\\frac{x - \\text{median}}{\\text{IQR}}$ | the column has outliers |\n",
    "| `np.log` | $\\log(x)$ | the column has a long tail of large positive values |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `df.drop(columns=[\"car_id\"])` | removes columns |\n",
    "| `df[\"age\"] = 2026 - df[\"year\"]` | creates a feature |\n",
    "| `df.corr()[\"price\"].sort_values()` | the correlation of every column with the target |\n",
    "| `scaler = StandardScaler()` | creates a scaler |\n",
    "| `X_train_scaled = scaler.fit_transform(X_train)` | learns from the training data and scales it |\n",
    "| `X_test_scaled = scaler.transform(X_test)` | scales the test data with the same numbers |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. Ask of every column whether it can sensibly influence the target. Drop the ones that cannot.\n",
    "2. Create features with knowledge of the subject, and keep the ones that raise the test score.\n",
    "3. Correlation with the target shows candidates; correlation between features shows doubles.\n",
    "4. Split first, then scale.\n",
    "5. `fit_transform` on the training data, `transform` on the test data, one scaler for both.\n",
    "6. Scaling changes the size of the numbers, not what they say. The logarithm also changes the shape.\n",
    "7. Standard scaling is the usual first choice; robust scaling for outliers; the logarithm for long tails.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "Every column of this lesson was a number, and the one text column was dropped. But a column such as the city of a flat or the fuel of a car is text that does carry information. Topic 25, feature engineering with the encoding of categorical variables and the handling of outliers, shows how such columns become numbers, and what to do with the extreme values that this lesson only scaled around.\n",
    "\n",
    "Next: the practice notebook (topic-24-practice.ipynb), then Topic 25: Feature engineering: encoding categorical variables, and handling outliers."
   ],
   "id": "t24-070"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
