{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 25: Feature engineering: encoding categorical variables, and handling outliers\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 13, 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-25-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 1 to 9 are one run from the top to the bottom, so start at the first cell. Part 10 and every solved problem start again from reading the file.\n",
    "\n",
    "This notebook reads the file laptops.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\n",
    "2. First, the columns that carry no information\n",
    "3. Outliers: what they are and why they matter\n",
    "4. Finding outliers: the IQR rule and the z-score\n",
    "5. What to do with outliers\n",
    "6. Categorical variables: why they are encoded\n",
    "7. Label encoding: one number for every category\n",
    "8. One-hot encoding: one column for every category\n",
    "9. Many categories: target encoding and frequency encoding\n",
    "10. The whole road, from the file to the test score\n",
    "11. Common mistakes\n",
    "12. Solved problems\n",
    "13. Practice (in topic-25-practice.ipynb)\n",
    "14. Check yourself (on the website)\n",
    "15. Summary"
   ],
   "id": "t25-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: extreme values and text columns\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, an outlier is a value far from the others, and it is either a mistake or a real extreme value: a rule finds it, you decide which kind it is. Second, the two rules: the IQR rule (the usual first choice) and the z-score (for bell-shaped columns with many rows). Third, what to do: mistakes are repaired or removed in the whole table before the split; real extreme values usually stay, and they always stay in the test data. Fourth, a text column with information is not dropped but encoded: 0 and 1 for two values, numbers in order for ordered categories, one-hot columns for a few categories without order, target encoding for many. Fifth, the order of all steps: whatever learns from the rows comes after the split and learns from the training data only.\n",
    "\n",
    "The fifth lesson of Module 3, and the second one on feature engineering. Topic 24 worked on numerical columns: dropping the ones without information, creating and selecting features, and scaling. Two things were left open there. The data had a few extreme values that were only \"scaled around\", and the one text column was simply dropped. This lesson closes both gaps.\n",
    "\n",
    "It has two halves. The first is about outliers: values that lie far away from the rest. You will learn how to find them with two rules (the IQR rule and the z-score), and, more important, what to do with them: whether to remove them at all, before or after the split, in the training data or in the test data, in the target or in the features, in every column or in selected ones. The second half is about encoding: turning text columns such as a brand or a condition into numbers a model can calculate with. There are several ways to do it, and the right one depends on the kind of column.\n",
    "\n",
    "At the end everything of Topics 24 and 25 is put together in one recipe, from reading the file to the test score.\n",
    "\n",
    "Everything is done on one data file, `laptops.csv`, with the tools you know.\n",
    "\n",
    "You need: pandas (Topics 10 and 11), the quartiles, the interquartile range and the z-score (Topic 18), linear regression (Topic 22), the train/test split (Topic 23), and dropping, selecting and scaling features (Topic 24).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| outlier | a value that lies far away from the other values of its column |\n",
    "| IQR rule | a value is an outlier when it lies more than 1.5 IQR below the first or above the third quartile |\n",
    "| z-score | how many standard deviations a value lies from the mean |\n",
    "| removing (trimming) | deleting the rows with outliers |\n",
    "| capping | replacing a value beyond a limit by the limit itself |\n",
    "| categorical variable | a column whose values are groups, not amounts: a brand, a colour, a condition |\n",
    "| nominal | categories without an order: brand, type, city |\n",
    "| ordinal | categories with an order: used, good, like new, new |\n",
    "| encoding | turning categories into numbers |\n",
    "| label (ordinal) encoding | one whole number for every category |\n",
    "| one-hot (dummy) encoding | one column of 0 and 1 for every category |\n",
    "| target encoding | every category is replaced by the mean of the target in that category |\n",
    "| frequency encoding | every category is replaced by how often it appears |\n",
    "| cardinality | the number of different categories of a column |\n",
    "\n",
    "## 1. The data\n",
    "\n",
    "`laptops.csv` describes 300 invented laptops that a shop sells, new and used. The target is the price in manat."
   ],
   "id": "t25-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head(3).T)"
   ],
   "id": "t25-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every code block of this lesson is a cell that continues from the cells above it, like a notebook: `df` stays in memory.\n",
    "\n",
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `laptop_id` | the identification number of the laptop in the list |\n",
    "| `seller_name` | the first name of the person who sold it to the shop |\n",
    "| `currency` | the currency of the price |\n",
    "| `brand` | the maker (12 invented brands) |\n",
    "| `type` | what the laptop is built for: `office`, `gaming` or `ultrabook` |\n",
    "| `condition` | `used`, `good`, `like new` or `new` |\n",
    "| `touchscreen` | `yes` or `no` |\n",
    "| `ram_gb` | the memory in gigabytes |\n",
    "| `storage_gb` | the size of the disk in gigabytes |\n",
    "| `screen_inch` | the size of the screen in inches |\n",
    "| `screen_cm` | the size of the screen in centimetres |\n",
    "| `weight_kg` | the weight in kilograms |\n",
    "| `usb_ports` | the number of USB ports |\n",
    "| `age_months` | the age in months (0 for a new laptop) |\n",
    "| `price` | the price in manat: the target |\n",
    "\n",
    "Six columns are text, not numbers:"
   ],
   "id": "t25-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.select_dtypes(exclude=\"number\").columns.tolist())"
   ],
   "id": "t25-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`select_dtypes(exclude=\"number\")` keeps the columns that are not numbers. A model cannot use them as they are. Three of them will be dropped, and the other three, with `touchscreen`, are the subject of the second half of the lesson.\n",
    "\n",
    "## 2. First, the columns that carry no information\n",
    "\n",
    "This is the first step of Topic 24, and it comes first here too."
   ],
   "id": "t25-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.nunique())"
   ],
   "id": "t25-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `laptop_id` has 300 values in 300 rows: an identification number.\n",
    "- `currency` has 1 value: a constant.\n",
    "- `seller_name` is a name. It has 20 values, like a real feature could have, so only its meaning tells you that it says nothing about the laptop."
   ],
   "id": "t25-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"laptop_id\", \"seller_name\", \"currency\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t25-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The other text columns stay. A brand, a type and a condition do say something about a laptop, and so they must not be dropped: they must be turned into numbers. That is the difference between a column without information and a column whose information is not a number yet.\n",
    "\n",
    "## 3. Outliers: what they are and why they matter\n",
    "\n",
    "### 3.1 A look at two columns"
   ],
   "id": "t25-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"weight_kg\", \"price\"]].describe().round(1))"
   ],
   "id": "t25-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read the two columns from the top to the bottom. Three quarters of the laptops weigh 2.3 kg or less, and the heaviest one weighs 2,770 kg. Three quarters cost about 1,810 manat or less, and the most expensive one costs 25,860. Something is wrong at the upper end of both columns.\n",
    "\n",
    "An outlier is a value that lies far away from the other values of its column.\n",
    "\n",
    "### 3.2 Two kinds of outliers\n",
    "\n",
    "This is the most important idea of the first half of the lesson: an outlier is not automatically a mistake.\n",
    "\n",
    "|  | A mistake | A real extreme value |\n",
    "| --- | --- | --- |\n",
    "| What it is | a value that is wrong: a typing error, a wrong unit, a broken sensor | a value that is true, only rare |\n",
    "| Example | a laptop that weighs 2,770 kg (the weight was typed in grams) | a laptop with 32 GB of memory and a disk of 2,048 GB that costs 3,290 |\n",
    "| Does it describe the real world? | no | yes |\n",
    "| What to do | repair it, or remove the row | think first; very often keep it |\n",
    "\n",
    "A rule can find values that lie far away. It cannot tell you which of the two kinds a value is. That decision needs a person who knows what the column means.\n",
    "\n",
    "### 3.3 Why outliers matter\n",
    "\n",
    "1. They pull the mean and the standard deviation. The mean and the median of the weight:"
   ],
   "id": "t25-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(df[\"weight_kg\"].mean(), 2))\n",
    "print(df[\"weight_kg\"].median())"
   ],
   "id": "t25-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The median says that a typical laptop weighs 1.91 kg. The mean says about 42 kg: a handful of wrong values are enough to make it useless (Topic 18). Everything that is built on the mean and the standard deviation suffers with it, and that includes standard scaling (Topic 24).\n",
    "\n",
    "2. They pull the model. A linear regression minimises the squared errors (Topic 22). A point that lies far away has a huge squared error, so the line turns towards it and gives up the fit for many ordinary points.\n",
    "\n",
    "A first model shows how bad it can get. It uses the numerical columns as they are. (`screen_cm` is left out: it repeats `screen_inch`. Part 10 comes back to it.)"
   ],
   "id": "t25-013"
  },
  {
   "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",
    "numbers = [\"ram_gb\", \"storage_gb\", \"screen_inch\", \"weight_kg\", \"usb_ports\", \"age_months\"]\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(train[numbers], train[\"price\"])\n",
    "\n",
    "print(round(model.score(train[numbers], train[\"price\"]), 3))\n",
    "print(round(model.score(test[numbers], test[\"price\"]), 3))"
   ],
   "id": "t25-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two things are new in this cell, and both will be used all through the lesson.\n",
    "\n",
    "- `train_test_split(df, ...)` gets one table and returns two: the training rows and the test rows, each with all its columns. It is the same split as in Topic 23, only the features and the target stay together in one table. That is practical when rows have to be removed or columns have to be added later.\n",
    "- The features are then `train[numbers]`, and the target is `train[\"price\"]`.\n",
    "\n",
    "The scores: 0.05 on the training data and a negative score on the test data. A negative $R^2$ means that the model predicts worse than a model that always answers with the mean price (Topic 22). With these outliers in the data the model is useless.\n",
    "\n",
    "3. They disturb scaling. Topic 24 showed it: with min-max scaling one extreme value presses all the others into a corner.\n",
    "\n",
    "We will need the recipe of this cell many times. To keep the cells short, it goes into a small function (Topic 3):"
   ],
   "id": "t25-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def scores(train, test, columns):\n",
    "    model = LinearRegression()\n",
    "    model.fit(train[columns], train[\"price\"])\n",
    "    print(round(model.score(train[columns], train[\"price\"]), 3))\n",
    "    print(round(model.score(test[columns], test[\"price\"]), 3))\n",
    "\n",
    "scores(train, test, numbers)"
   ],
   "id": "t25-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same two numbers: the function does exactly what the cell above did.\n",
    "\n",
    "## 4. Finding outliers: the IQR rule and the z-score\n",
    "\n",
    "### 4.1 Look first\n",
    "\n",
    "Before any rule, look at the column: `describe()` as above, or a picture. The box plot of Topic 12 was made for this: it draws every value beyond its whiskers as a single point."
   ],
   "id": "t25-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.boxplot(x=df[\"price\"])\n",
    "plt.title(\"The prices of the 300 laptops\")\n",
    "plt.show()"
   ],
   "id": "t25-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The box with the middle half of the prices is squeezed to the left edge, and a row of single points stretches far to the right. Now the two rules that put numbers on \"far away\".\n",
    "\n",
    "### 4.2 The IQR rule\n",
    "\n",
    "The interquartile range is the width of the middle half of the data (Topic 18):\n",
    "\n",
    "$$\n",
    "\\text{IQR} = Q_3 - Q_1\n",
    "$$\n",
    "\n",
    "The rule draws two limits, 1.5 IQR outside the quartiles:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{lower limit} &= Q_1 - 1.5 \\times \\text{IQR} \\\\[4pt]\n",
    "\\text{upper limit} &= Q_3 + 1.5 \\times \\text{IQR}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "A value below the lower limit or above the upper limit is called an outlier. The whiskers of a box plot end at these limits.\n",
    "\n",
    "By hand. Nine values, already sorted:\n",
    "\n",
    "$$\n",
    "10 \\quad 12 \\quad 13 \\quad 14 \\quad 15 \\quad 16 \\quad 17 \\quad 18 \\quad 65\n",
    "$$\n",
    "\n",
    "With the rule of Topic 18, the quartile for the share $p$ stands at the position $1 + (n - 1) \\times p$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "Q_1:\\quad & \\text{position } 1 + 8 \\times 0.25 = 3 \\\\\n",
    "& \\text{the third value: } Q_1 = 13 \\\\[6pt]\n",
    "Q_3:\\quad & \\text{position } 1 + 8 \\times 0.75 = 7 \\\\\n",
    "& \\text{the seventh value: } Q_3 = 17 \\\\[10pt]\n",
    "& \\text{IQR} = 17 - 13 = 4 \\\\[4pt]\n",
    "& 1.5 \\times \\text{IQR} = 1.5 \\times 4 = 6 \\\\[10pt]\n",
    "& \\text{lower limit} = 13 - 6 = 7 \\\\[4pt]\n",
    "& \\text{upper limit} = 17 + 6 = 23\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Eight values lie between 7 and 23. The value 65 lies above 23: it is an outlier.\n",
    "\n",
    "In pandas, on the prices:\n",
    "\n",
    "Change it and run: replace `1.5` by `3` in both lines and run: the upper limit moves out to 3,890, a limit for values that are \"far out\"."
   ],
   "id": "t25-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = df[\"price\"].quantile(0.25)\n",
    "q3 = df[\"price\"].quantile(0.75)\n",
    "iqr = q3 - q1\n",
    "\n",
    "lower = q1 - 1.5 * iqr\n",
    "upper = q3 + 1.5 * iqr\n",
    "\n",
    "print(q1, q3, iqr)\n",
    "print(lower, upper)"
   ],
   "id": "t25-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`quantile(0.25)` is the first quartile and `quantile(0.75)` the third (Topic 18). No price lies below the lower limit, so only the upper limit matters here. The rows above it:"
   ],
   "id": "t25-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "outliers = df[df[\"price\"] > upper]\n",
    "\n",
    "print(len(outliers))\n",
    "print(outliers[[\"brand\", \"type\", \"ram_gb\", \"storage_gb\", \"price\"]].sort_values(\"price\"))"
   ],
   "id": "t25-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nine laptops. Now read them, because the rule has done its part and the thinking begins.\n",
    "\n",
    "- The first three cost about 3,000 to 3,300. They have 16 or 32 GB of memory and a large disk. These are simply the best laptops of the shop: real extreme values.\n",
    "- The other six cost between 9,790 and 25,860. An office laptop with 8 GB for 9,790? An ultrabook with a small disk for 17,480? Every one of these prices is about ten times what such a laptop costs. Somebody typed one zero too many: mistakes.\n",
    "\n",
    "There is a wide gap between the two groups (from 3,290 to 9,790), and it separates them cleanly.\n",
    "\n",
    "### 4.3 The z-score\n",
    "\n",
    "The z-score says how many standard deviations a value lies above or below the mean (Topic 18; it is also the formula of standard scaling in Topic 24):\n",
    "\n",
    "$$\n",
    "z = \\frac{x - \\text{mean}}{\\text{standard deviation}}\n",
    "$$\n",
    "\n",
    "In a column with the shape of a bell almost all values (99.7 percent) have a z-score between $-3$ and 3 (Topic 17). So the usual rule is: a value with a z-score below $-3$ or above 3 is an outlier. Some people use 2.5 or 2 as a stricter limit.\n",
    "\n",
    "By hand, for the same nine values:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{sum} = 10 + 12 + 13 + 14 + 15 \\\\\n",
    "& \\qquad\\quad + 16 + 17 + 18 + 65 = 180 \\\\[6pt]\n",
    "& \\text{mean} = \\frac{180}{9} = 20 \\\\[10pt]\n",
    "& \\text{squared deviations:} \\\\\n",
    "& 100 + 64 + 49 + 36 + 25 \\\\\n",
    "& \\quad + 16 + 9 + 4 + 2025 = 2328 \\\\[10pt]\n",
    "& \\text{standard deviation} = \\sqrt{\\frac{2328}{9}} \\\\[4pt]\n",
    "& \\qquad = \\sqrt{258.667} = 16.083 \\\\[10pt]\n",
    "& z \\text{ of } 65:\\quad \\frac{65 - 20}{16.083} = 2.798\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The z-score of 65 is 2.798. That is below 3: the z-score rule does not call 65 an outlier, although it is more than three times as large as every other value.\n",
    "\n",
    "The reason is the weak point of this rule. The mean and the standard deviation are calculated with the outlier in the data, and the outlier pulls both: the mean rose to 20, above eight of the nine values, and the standard deviation grew to 16. The outlier hides itself. This is called masking, and it is worst in small data sets. The quartiles of the IQR rule did not move at all.\n",
    "\n",
    "In pandas:"
   ],
   "id": "t25-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "z = (df[\"price\"] - df[\"price\"].mean()) / df[\"price\"].std()\n",
    "\n",
    "print((z.abs() > 3).sum())\n",
    "print(df[z.abs() > 3][\"price\"].sort_values().tolist())"
   ],
   "id": "t25-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`z.abs()` takes away the sign, so that one comparison covers both sides. (`std()` of pandas divides by $n - 1$; with hundreds of rows the difference to dividing by $n$ does not matter.)\n",
    "\n",
    "The z-score marks six prices, and they are exactly the six mistakes. The IQR rule marked nine: the same six and the three real, expensive laptops.\n",
    "\n",
    "### 4.4 The two rules on the weight"
   ],
   "id": "t25-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = df[\"weight_kg\"].quantile(0.25)\n",
    "q3 = df[\"weight_kg\"].quantile(0.75)\n",
    "upper_weight = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "z = (df[\"weight_kg\"] - df[\"weight_kg\"].mean()) / df[\"weight_kg\"].std()\n",
    "\n",
    "print(round(upper_weight, 2))\n",
    "print(df[df[\"weight_kg\"] > upper_weight][\"weight_kg\"].sort_values().tolist())\n",
    "print(df[z.abs() > 3][\"weight_kg\"].sort_values().tolist())"
   ],
   "id": "t25-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The IQR rule puts the upper limit at 3.58 kg and finds six weights above it: 900, 1,960, 1,970, 2,200, 2,220 and 2,770. No laptop weighs a ton. The weights were typed in grams. The z-score finds only five of them: the value 900 has a z-score just below 3, because the six wrong values themselves blew up the standard deviation to almost 300. Masking again, this time on real data.\n",
    "\n",
    "### 4.5 Which rule, and when?\n",
    "\n",
    "|  | IQR rule | z-score |\n",
    "| --- | --- | --- |\n",
    "| Built on | the quartiles | the mean and the standard deviation |\n",
    "| Moved by the outliers themselves | hardly | yes: masking |\n",
    "| Shape of the column | any shape; also skewed columns | meant for columns with the shape of a bell |\n",
    "| Small data sets | works | weak: in 9 values no z-score can reach 3 |\n",
    "| Usual limit | 1.5 IQR (3 IQR for \"far out\") | 3 (sometimes 2.5 or 2) |\n",
    "| Typical weakness | in a skewed column it marks many real values | misses outliers that hide behind each other |\n",
    "\n",
    "- The IQR rule is the usual first choice. It needs no assumption about the shape of the column, the outliers do not disturb it, and it is the rule behind the box plot, so the picture and the numbers agree.\n",
    "- The z-score is used when a column has roughly the shape of a bell and there are many rows: measurements, heights, test results, the errors of a model. It is also the language of many fields (\"a three sigma event\"), and it gives a number for how far away a value is, not only yes or no.\n",
    "- Both are rules of thumb, not judges. They point at candidates. Whether a candidate is a mistake or a real value is decided by looking at it.\n",
    "\n",
    "## 5. What to do with outliers\n",
    "\n",
    "### 5.1 Five options\n",
    "\n",
    "| Option | What is done | Fits when |\n",
    "| --- | --- | --- |\n",
    "| Repair | the wrong value is replaced by the right one | the value is a mistake and its cause is known (a wrong unit, a shifted decimal point) |\n",
    "| Remove | the row is deleted | the value is a mistake and the right value is not known; there are few such rows |\n",
    "| Cap | a value beyond a limit is replaced by the limit | the value is real but so extreme that it would dominate; the row itself is worth keeping |\n",
    "| Transform | the whole column is changed, for example with the logarithm (Topic 24) | the column has a long tail of real, large values |\n",
    "| Keep | nothing | the value is real, and the model should know such cases |\n",
    "\n",
    "Removing is only one of five, and it is the one that throws information away. The questions below decide which option fits.\n",
    "\n",
    "### 5.2 Question 1: is it a mistake or a real value?\n",
    "\n",
    "Everything else depends on this answer.\n",
    "\n",
    "- A mistake does not describe the world. A model that learns from it learns something false, and a test that contains it measures something false. Mistakes are cleaned in the whole table, and it is done before the split. This is data cleaning, the same kind of work as fixing a wrong date in Topic 11.\n",
    "- A real extreme value is part of the world the model will work in. The rules for it are stricter, and they follow from Topic 23: see Questions 2 and 3.\n",
    "\n",
    "### 5.3 Cleaning the mistakes\n",
    "\n",
    "The prices. The true prices of the six laptops are not known for certain: probably a tenth, but nobody can check. So the rows are removed. The limit comes from looking at the data: the real prices end at 3,290 and the mistakes begin at 9,790."
   ],
   "id": "t25-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df[df[\"price\"] < 9000]\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t25-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Six rows less: 294 laptops. The model again, with the same recipe:"
   ],
   "id": "t25-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "scores(train, test, numbers)"
   ],
   "id": "t25-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From a negative test score to 0.405. Six rows out of 300 had ruined the model.\n",
    "\n",
    "The weights. Here the cause is known: grams in the place of kilograms. So the values can be repaired, and no row is lost: every weight above 10 is divided by 1,000."
   ],
   "id": "t25-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "\n",
    "print(df[\"weight_kg\"].describe().round(2))"
   ],
   "id": "t25-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.loc[rows, column] = ...` changes the column only in the chosen rows (Topic 11). The weights now run from 0.9 to 3.33 kg, and the mean (1.92) and the median (1.91) agree again."
   ],
   "id": "t25-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "scores(train, test, numbers)"
   ],
   "id": "t25-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| The data | Test score |\n",
    "| --- | --- |\n",
    "| as it came | $-0.618$ |\n",
    "| the six wrong prices removed | 0.405 |\n",
    "| the six wrong weights repaired too | 0.527 |\n",
    "\n",
    "Twelve wrong values in a table of 300 rows made the difference between a useless model and a usable one. The score is still not high, but for another reason: the model has not seen the brand, the type and the condition yet. That is the second half of the lesson.\n",
    "\n",
    "### 5.4 Question 2: before or after the split?\n",
    "\n",
    "It depends on what is done.\n",
    "\n",
    "- Cleaning mistakes with a fixed rule: before the split, in the whole table. \"No laptop weighs more than 10 kg\" is knowledge about laptops. It was not learned from the rows, and it would be applied in the same way to every laptop that arrives tomorrow.\n",
    "- Everything that learns limits from the data: after the split, from the training data only. The IQR limits and the z-scores are calculated from the rows, exactly like the minimum and the maximum of a scaler in Topic 24. If they are calculated from all the rows, the test rows have helped to decide which training rows are removed: data leakage. So: split first, calculate the limits on the training data, and use these same limits wherever they are needed.\n",
    "\n",
    "The question to ask is the one of Topic 24: does the step learn something from the rows?\n",
    "\n",
    "Now the three real, expensive laptops. The data is already split. The limits come from the training data:"
   ],
   "id": "t25-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = train[\"price\"].quantile(0.25)\n",
    "q3 = train[\"price\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((train[\"price\"] > upper).sum())\n",
    "print((test[\"price\"] > upper).sum())"
   ],
   "id": "t25-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the training data three prices lie above the limit of 2,832.5; in the test data none.\n",
    "\n",
    "Removing them from the training data, and the scores:"
   ],
   "id": "t25-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_removed = train[train[\"price\"] <= upper]\n",
    "\n",
    "print(len(train), len(train_removed))\n",
    "scores(train_removed, test, numbers)"
   ],
   "id": "t25-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Capping them: `clip(upper=...)` replaces every value above the limit by the limit."
   ],
   "id": "t25-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_capped = train.copy()\n",
    "train_capped[\"price\"] = train_capped[\"price\"].clip(upper=upper)\n",
    "\n",
    "print(train[\"price\"].max(), train_capped[\"price\"].max())\n",
    "scores(train_capped, test, numbers)"
   ],
   "id": "t25-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`train.copy()` makes a copy, so that `train` itself stays as it is.\n",
    "\n",
    "| The training data | Test score |\n",
    "| --- | --- |\n",
    "| all rows kept | 0.527 |\n",
    "| the three most expensive laptops removed | 0.522 |\n",
    "| their prices capped at the limit | 0.528 |\n",
    "\n",
    "Almost nothing changes. That is the usual result for real extreme values that are not very far away: the model can live with them, and removing them brings nothing. The large gains of this lesson came from the mistakes. So these three laptops stay in the data.\n",
    "\n",
    "### 5.5 Question 3: in the training data, in the test data, or in both?\n",
    "\n",
    "|  | Mistakes | Real extreme values |\n",
    "| --- | --- | --- |\n",
    "| Training data | clean them | may be removed or capped, if that helps |\n",
    "| Test data | clean them | leave them in |\n",
    "\n",
    "- Never remove real extreme values from the test data. The test data stands for the laptops that will arrive tomorrow (Topic 23), and expensive laptops will arrive too. The model cannot refuse to price them. A test without them gives a score that is too flattering: it measures the model only on the easy cases.\n",
    "- Never remove outliers only from the test data. The model would still be trained on them and judged without them: the worst of both.\n",
    "- If a feature is capped, the limits of the training data are applied to the test data too (`clip` with the same numbers), exactly as a fitted scaler is applied to the test data. The row stays; only its extreme value is pulled in.\n",
    "- There is one honest exception: you decide that the model is not meant for such cases (\"this model prices laptops up to 3,000; more expensive ones are priced by hand\"). Then they leave both parts, and the decision is written down as a limit of the model.\n",
    "\n",
    "### 5.6 Question 4: outliers in the target?\n",
    "\n",
    "The target is the column the model learns to predict, so it deserves the most care.\n",
    "\n",
    "- A mistake in the target is the most harmful kind: the model learns a wrong answer, and a test row with a wrong answer punishes even a perfect prediction. The six wrong prices showed it. Clean them, in the whole table.\n",
    "- A real extreme target value may be removed from the training data when it damages the fit for the ordinary cases. It stays in the test data.\n",
    "- For a target with a long tail of real, large values (prices of houses, incomes), a common alternative to removing is to train on the logarithm of the target. The idea is the one of the log transform in Topic 24.\n",
    "- Never change the targets of the test data. They are the truth the model is measured against.\n",
    "\n",
    "### 5.7 Question 5: in every column, or in selected ones?\n",
    "\n",
    "In selected ones. Here is what the IQR rule would do in each numerical column of the training data:"
   ],
   "id": "t25-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in [\"ram_gb\", \"storage_gb\", \"screen_inch\", \"weight_kg\", \"usb_ports\", \"age_months\", \"price\"]:\n",
    "    q1 = train[name].quantile(0.25)\n",
    "    q3 = train[name].quantile(0.75)\n",
    "    low = q1 - 1.5 * (q3 - q1)\n",
    "    high = q3 + 1.5 * (q3 - q1)\n",
    "    print(name, ((train[name] < low) | (train[name] > high)).sum())"
   ],
   "id": "t25-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rule would throw away 25 laptops for their memory and 38 for their disk. Look at why. Most laptops have 8 or 16 GB of memory, so the upper limit lies at 28, and every laptop with 32 GB counts as an \"outlier\". The same happens to the disks of 1,024 and 2,048 GB. These are not mistakes and not even rare accidents. They are the upper models of the shop.\n",
    "\n",
    "Applied blindly to every column, the rule would remove about a quarter of the training data, and afterwards the model would never have seen a laptop with 32 GB. The rules for choosing the columns:\n",
    "\n",
    "- Columns with continuous measurements (a weight, a price, an area, an income) are the place for outlier rules.\n",
    "- Columns with a few fixed values (the memory, the number of rooms, the number of doors) are not: there the quartiles sit on the common values, and every less common value is marked.\n",
    "- Never on columns of 0 and 1, on encoded categories, or on identification numbers.\n",
    "- Every column in which rows are removed costs rows. Check how many rows are left.\n",
    "\n",
    "### 5.8 The answers side by side\n",
    "\n",
    "| Question | Answer |\n",
    "| --- | --- |\n",
    "| Is every outlier a mistake? | No. A rule finds candidates; you decide what they are. |\n",
    "| Mistakes | Repair them if the cause is known, remove the rows if not. In the whole table, before the split. |\n",
    "| Real extreme values | Often keep them. If they are handled: after the split, with limits from the training data. |\n",
    "| Remove them from the test data? | No. The test data stands for the real world. |\n",
    "| Remove them only from the test data? | Never. |\n",
    "| Outliers in the target | Mistakes: clean them everywhere. Real ones: at most out of the training data. |\n",
    "| Every column? | No. Selected columns with continuous measurements. |\n",
    "| Other ways than removing | Cap, transform with the logarithm, a robust scaler (Topic 24), or keep. |\n",
    "\n",
    "## 6. Categorical variables: why they are encoded\n",
    "\n",
    "### 6.1 A model calculates\n",
    "\n",
    "A linear regression multiplies every feature by a weight and adds the results. It cannot multiply the word \"gaming\" by 3.2.\n",
    "\n",
    "```python\n",
    "model = LinearRegression()\n",
    "model.fit(train[[\"ram_gb\", \"type\"]], train[\"price\"])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: could not convert string to float: 'office'\n",
    "```\n",
    "\n",
    "Nearly every model has this limit. A column of words must become one or several columns of numbers before training. That is encoding.\n",
    "\n",
    "It is worth the work, because the words carry information. The mean price in each group:"
   ],
   "id": "t25-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.groupby(\"type\")[\"price\"].mean().round(0))\n",
    "print(df.groupby(\"touchscreen\")[\"price\"].mean().round(0))"
   ],
   "id": "t25-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An ultrabook costs almost 600 manat more than an office laptop on average, and a touchscreen adds about 170. The model of Part 5 knew none of this.\n",
    "\n",
    "### 6.2 The kinds of categorical columns"
   ],
   "id": "t25-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in [\"touchscreen\", \"condition\", \"type\", \"brand\"]:\n",
    "    print(name, df[name].nunique(), df[name].unique()[:4].tolist())"
   ],
   "id": "t25-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a column, the number of its different values and up to four of them. The four columns are four different cases:\n",
    "\n",
    "| Column | Values | Kind | Encoding |\n",
    "| --- | --- | --- | --- |\n",
    "| `touchscreen` | 2: yes, no | binary: two values | 0 and 1 |\n",
    "| `condition` | 4: used, good, like new, new | ordinal: the values have an order | label (ordinal) encoding |\n",
    "| `type` | 3: office, gaming, ultrabook | nominal: no order, few values | one-hot encoding |\n",
    "| `brand` | 12 | nominal: no order, many values | target or frequency encoding (or one-hot) |\n",
    "\n",
    "Two questions decide the encoding: do the categories have an order? and how many are there? The number of different categories of a column is its cardinality.\n",
    "\n",
    "## 7. Label encoding: one number for every category\n",
    "\n",
    "### 7.1 Two values: 0 and 1"
   ],
   "id": "t25-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"touchscreen\"] = df[\"touchscreen\"].map({\"no\": 0, \"yes\": 1})\n",
    "\n",
    "print(df[\"touchscreen\"].value_counts())"
   ],
   "id": "t25-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`map` with a dictionary replaces every value by the one the dictionary gives for it (Topic 11). For a column with two values this is all that is needed: 1 means \"has it\", 0 means \"does not\". The weight of this feature will then say how much a touchscreen adds to the price.\n",
    "\n",
    "### 7.2 Ordered categories: numbers in the right order\n",
    "\n",
    "Label encoding gives every category a whole number. For an ordinal column the numbers follow the order of the categories. For this reason it is also called ordinal encoding."
   ],
   "id": "t25-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "order = {\"used\": 0, \"good\": 1, \"like new\": 2, \"new\": 3}\n",
    "df[\"condition\"] = df[\"condition\"].map(order)\n",
    "\n",
    "print(df[\"condition\"].value_counts().sort_index())"
   ],
   "id": "t25-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The order is written by you, in the dictionary. Now \"new\" (3) is larger than \"used\" (0), which is true, and a model can use the column like any number: one weight for every step up.\n",
    "\n",
    "The numbers also say that every step is equally large: from used to good is as far as from like new to new. That is an assumption. It is usually close enough, and when it is clearly wrong, one-hot encoding (Part 8) is the alternative.\n",
    "\n",
    "The model with the two new columns:\n",
    "\n",
    "Change it and run: take `\"condition\"` out of the list and run: the test score falls to 0.551."
   ],
   "id": "t25-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "features = numbers + [\"condition\", \"touchscreen\"]\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "scores(train, test, features)"
   ],
   "id": "t25-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The test score rises from 0.527 to 0.699.\n",
    "\n",
    "Both columns were encoded before the split. That is allowed here, because a dictionary written by hand learns nothing from the rows: \"used\" becomes 0 for every laptop, whatever the other rows contain.\n",
    "\n",
    "### 7.3 The encoders of scikit-learn\n",
    "\n",
    "scikit-learn has an encoder for this, `OrdinalEncoder`. It is used like a scaler, with `fit` and `transform`. The order is given as a list:"
   ],
   "id": "t25-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import OrdinalEncoder\n",
    "\n",
    "raw = pd.read_csv(\"laptops.csv\")\n",
    "\n",
    "encoder = OrdinalEncoder(categories=[[\"used\", \"good\", \"like new\", \"new\"]])\n",
    "codes = encoder.fit_transform(raw[[\"condition\"]])\n",
    "\n",
    "print(raw[\"condition\"].head(4).tolist())\n",
    "print(codes[:4].ravel())"
   ],
   "id": "t25-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`raw` is a fresh copy of the file, because `df[\"condition\"]` is already encoded. The encoder wants a table, so the column is taken with two pairs of brackets. `ravel()` only prints the result on one line.\n",
    "\n",
    "Without the list of categories the encoder puts them in the order of the alphabet:"
   ],
   "id": "t25-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "encoder = OrdinalEncoder()\n",
    "encoder.fit(raw[[\"condition\"]])\n",
    "\n",
    "print(encoder.categories_)"
   ],
   "id": "t25-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`good` = 0, `like new` = 1, `new` = 2, `used` = 3: \"used\" would be the best condition. The order of the alphabet is almost never the order of the meaning. Always give the order yourself.\n",
    "\n",
    "There is also a `LabelEncoder`. It numbers the categories in the order of the alphabet too, and it is meant for the target of a classification (Topic 27), not for features.\n",
    "\n",
    "### 7.4 The danger: numbers invent an order\n",
    "\n",
    "Label encoding is right for ordinal columns. For a nominal column it does harm. Try it with the type, encoded in the order of the alphabet:\n",
    "\n",
    "Change it and run: change the dictionary to `{\"office\": 0, \"gaming\": 1, \"ultrabook\": 2}` and run: with an order that follows the prices the score rises to 0.749. It is still below one-hot encoding (Part 8)."
   ],
   "id": "t25-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trial = df.copy()\n",
    "trial[\"type_code\"] = trial[\"type\"].map({\"gaming\": 0, \"office\": 1, \"ultrabook\": 2})\n",
    "\n",
    "train, test = train_test_split(trial, test_size=0.2, random_state=42)\n",
    "\n",
    "scores(train, test, features + [\"type_code\"])"
   ],
   "id": "t25-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`trial` is a copy of the table, so `df` itself stays as it is. The test score is 0.695. Without the column it was 0.699: the type, encoded like this, is worth nothing.\n",
    "\n",
    "The numbers tell the model that an office laptop lies exactly between a gaming laptop and an ultrabook, and that an ultrabook is \"twice an office laptop\". None of that means anything. In the prices the office laptops are the cheapest of the three, so a single weight for this column cannot follow them.\n",
    "\n",
    "## 8. One-hot encoding: one column for every category\n",
    "\n",
    "### 8.1 The idea\n",
    "\n",
    "One-hot encoding makes a new column for every category. A row has a 1 in the column of its own category and a 0 in all the others. These columns are called dummy variables, and so the method is also called dummy encoding.\n",
    "\n",
    "| type | type_gaming | type_office | type_ultrabook |\n",
    "| --- | --- | --- | --- |\n",
    "| office | 0 | 1 | 0 |\n",
    "| gaming | 1 | 0 | 0 |\n",
    "| ultrabook | 0 | 0 | 1 |\n",
    "| office | 0 | 1 | 0 |\n",
    "\n",
    "No category is larger than another, and no order is invented. The model gets one weight for every category: \"a gaming laptop costs this much more\".\n",
    "\n",
    "### 8.2 In pandas"
   ],
   "id": "t25-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(pd.get_dummies(df[\"type\"], dtype=int).head(4))"
   ],
   "id": "t25-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pd.get_dummies` makes the columns. `dtype=int` asks for 0 and 1; without it pandas writes `False` and `True`.\n",
    "\n",
    "### 8.3 One column can go: `drop_first`\n",
    "\n",
    "Look at the three columns. If a laptop is not a gaming laptop and not an ultrabook, it must be an office laptop: the third column can always be calculated from the other two. It is a perfect case of the multicollinearity of Topic 24, and it has a name of its own, the dummy variable trap. The cure is to drop one of the columns:\n",
    "\n",
    "Change it and run: take `drop_first=True` out and run: the table gets a third column, `type_gaming`."
   ],
   "id": "t25-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.get_dummies(df, columns=[\"type\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist())\n",
    "print(df[[\"type_office\", \"type_ultrabook\"]].head(4))"
   ],
   "id": "t25-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `columns=[\"type\"]` pandas encodes that column inside the table and removes the original. `drop_first=True` drops the first category in the order of the alphabet, `gaming`. A gaming laptop is now the row with 0 in both columns: it is the reference, and the weights of the other two columns say how much an office laptop or an ultrabook differs from a gaming laptop.\n",
    "\n",
    "For a linear model use `drop_first=True`. The predictions and the score are the same with all three columns; the weights are only readable with one column dropped.\n",
    "\n",
    "### 8.4 The score"
   ],
   "id": "t25-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "features = numbers + [\"condition\", \"touchscreen\", \"type_office\", \"type_ultrabook\"]\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "scores(train, test, features)"
   ],
   "id": "t25-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From 0.699 to 0.760. The three ways of handling the column, side by side:\n",
    "\n",
    "| How `type` is given to the model | Test score |\n",
    "| --- | --- |\n",
    "| not at all | 0.699 |\n",
    "| label encoding: gaming 0, office 1, ultrabook 2 | 0.695 |\n",
    "| one-hot encoding | 0.760 |\n",
    "\n",
    "Label encoding with an invented order brought nothing. One-hot encoding lets every type have its own effect.\n",
    "\n",
    "### 8.5 The encoder of scikit-learn\n",
    "\n",
    "`OneHotEncoder` does the same, with `fit` and `transform`:"
   ],
   "id": "t25-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import OneHotEncoder\n",
    "\n",
    "encoder = OneHotEncoder(sparse_output=False, handle_unknown=\"ignore\")\n",
    "encoder.fit(raw[[\"type\"]])\n",
    "\n",
    "print(encoder.get_feature_names_out())\n",
    "print(encoder.transform(raw[[\"type\"]].head(3)))"
   ],
   "id": "t25-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `sparse_output=False` returns an ordinary array.\n",
    "- `fit` learns the list of categories. That is its advantage over `get_dummies`: fitted on the training data, it produces the same columns for every later table, also for one new laptop.\n",
    "- `handle_unknown=\"ignore\"`: a category that was not in the training data (a new type, \"tablet\") gets 0 in all columns, where it would otherwise stop with an error.\n",
    "\n",
    "For a table that is encoded once, `get_dummies` is the simplest way, and this lesson uses it. In a system that receives new data every day, `OneHotEncoder` fitted on the training data is the safe way.\n",
    "\n",
    "### 8.6 When one-hot encoding does not fit\n",
    "\n",
    "Every category costs a column. Three types are three columns. Twelve brands are twelve. A column with 500 cities would be 500 columns, most of them almost always 0, and many with only a handful of rows to learn from: a wide table and an invitation to overfitting (Topic 23). For columns with many categories there are other encodings.\n",
    "\n",
    "## 9. Many categories: target encoding and frequency encoding\n",
    "\n",
    "The column `brand` has 12 values and no order.\n",
    "\n",
    "### 9.1 Target encoding\n",
    "\n",
    "Target encoding replaces every category by one number: the mean of the target in that category. A brand is replaced by the mean price of its laptops. It is also called mean encoding.\n",
    "\n",
    "By hand, with six laptops:\n",
    "\n",
    "| brand | price |\n",
    "| --- | --- |\n",
    "| Altra | 1,500 |\n",
    "| Altra | 1,700 |\n",
    "| Boreal | 1,000 |\n",
    "| Boreal | 1,200 |\n",
    "| Boreal | 1,400 |\n",
    "| Cirro | 2,000 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Altra:}\\quad & \\frac{1500 + 1700}{2} = 1600 \\\\[6pt]\n",
    "\\text{Boreal:}\\quad & \\frac{1000 + 1200 + 1400}{3} = 1200 \\\\[6pt]\n",
    "\\text{Cirro:}\\quad & \\frac{2000}{1} = 2000\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Every \"Altra\" in the column becomes 1,600, every \"Boreal\" 1,200, every \"Cirro\" 2,000. One column stays one column, however many categories there are, and its numbers have a meaning the model can use directly: an expensive brand has a large number.\n",
    "\n",
    "### 9.2 The danger: the target is inside the feature\n",
    "\n",
    "This encoding is built from the target, and that makes it the most dangerous one of the lesson.\n",
    "\n",
    "- It must be learned from the training data only. If the means are calculated from all the rows, the prices of the test laptops are inside the feature that is used to predict them: data leakage of the clearest kind (Topic 24). So: split first, calculate the means from the training data, and use these same means for the test data.\n",
    "- Rare categories are unreliable. The \"mean\" of Cirro above is the price of a single laptop. The model would learn that one price by heart: overfitting.\n",
    "\n",
    "That is why this encoding comes after the split, unlike the three before it:"
   ],
   "id": "t25-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "train = train.copy()\n",
    "test = test.copy()\n",
    "\n",
    "brand_means = train.groupby(\"brand\")[\"price\"].mean()\n",
    "\n",
    "print(brand_means.round(0))"
   ],
   "id": "t25-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`groupby(\"brand\")[\"price\"].mean()` is the mean price of every brand (Topic 11), from the training laptops only. The two `copy()` lines make `train` and `test` tables of their own, so that columns can be added to them."
   ],
   "id": "t25-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train[\"brand_price\"] = train[\"brand\"].map(brand_means)\n",
    "test[\"brand_price\"] = test[\"brand\"].map(brand_means)\n",
    "test[\"brand_price\"] = test[\"brand_price\"].fillna(train[\"price\"].mean())\n",
    "\n",
    "print(train[[\"brand\", \"brand_price\"]].head(4).round(0))"
   ],
   "id": "t25-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`map` replaces every brand by its mean. The test data gets the means of the training data. If the test data contains a brand that the training data did not have, `map` leaves a gap there, and `fillna` fills it with the mean price of all training laptops: the best guess for an unknown brand."
   ],
   "id": "t25-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scores(train, test, features + [\"brand_price\"])"
   ],
   "id": "t25-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From 0.760 to 0.941. The brand was the strongest piece of information in the table, and it was hidden in a text column.\n",
    "\n",
    "### 9.3 Frequency encoding\n",
    "\n",
    "Frequency encoding replaces every category by how often it appears: its share of the rows (or its count). It does not use the target, so it cannot leak the target. The shares are still learned from the training data."
   ],
   "id": "t25-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brand_share = train[\"brand\"].value_counts(normalize=True)\n",
    "\n",
    "train[\"brand_share\"] = train[\"brand\"].map(brand_share)\n",
    "test[\"brand_share\"] = test[\"brand\"].map(brand_share).fillna(0)\n",
    "\n",
    "print(brand_share.round(3).head(3))\n",
    "scores(train, test, features + [\"brand_share\"])"
   ],
   "id": "t25-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`value_counts(normalize=True)` gives shares in the place of counts (Topic 10). The score is 0.769, hardly above the 0.760 without the brand. In this shop a brand that is sold often is not more or less expensive than a rare one, so the frequency says nothing about the price. Frequency encoding helps only when being common or rare is itself connected to the target: a product that is bought often, a city with many customers.\n",
    "\n",
    "### 9.4 All the encodings of the brand side by side\n",
    "\n",
    "For the comparison the brand is also one-hot encoded (eleven columns, with `drop_first`):"
   ],
   "id": "t25-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brand_columns = pd.get_dummies(df[\"brand\"], prefix=\"brand\", drop_first=True, dtype=int)\n",
    "\n",
    "train_wide = train.join(brand_columns)\n",
    "test_wide = test.join(brand_columns)\n",
    "\n",
    "print(len(brand_columns.columns))\n",
    "scores(train_wide, test_wide, features + brand_columns.columns.tolist())"
   ],
   "id": "t25-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`join` adds the new columns to the rows with the same index (Topic 11).\n",
    "\n",
    "| How `brand` is given to the model | Columns | Test score |\n",
    "| --- | --- | --- |\n",
    "| not at all | 0 | 0.760 |\n",
    "| frequency encoding | 1 | 0.769 |\n",
    "| target encoding | 1 | 0.941 |\n",
    "| one-hot encoding | 11 | 0.965 |\n",
    "\n",
    "- One-hot encoding gives the best score here. With 12 brands and almost 300 rows the model can afford eleven columns, and every brand gets its own exact weight.\n",
    "- Target encoding comes close with a single column. With 12 categories that is a matter of taste. With 500 categories it is the difference between a table that works and one that does not.\n",
    "- Frequency encoding does not help in this data.\n",
    "\n",
    "### 9.5 Which encoding for which column\n",
    "\n",
    "| The column | Encoding | In Python |\n",
    "| --- | --- | --- |\n",
    "| two values | 0 and 1 | `df[c].map({\"no\": 0, \"yes\": 1})` |\n",
    "| ordered categories | label (ordinal) encoding, in your order | `df[c].map(order)` or `OrdinalEncoder(categories=[[...]])` |\n",
    "| no order, few categories (up to about 10 or 15) | one-hot encoding | `pd.get_dummies(df, columns=[c], drop_first=True, dtype=int)` or `OneHotEncoder` |\n",
    "| no order, many categories | target encoding (from the training data) | `train.groupby(c)[target].mean()`, then `map` |\n",
    "| no order, many categories, and how common a category is matters | frequency encoding | `train[c].value_counts(normalize=True)`, then `map` |\n",
    "\n",
    "scikit-learn also has a `TargetEncoder`. It does the same as the cells above and adds two protections: it pulls the means of rare categories towards the overall mean, and it calculates the training values in a way that is safer against overfitting. The idea is the one you have just done by hand.\n",
    "\n",
    "## 10. The whole road, from the file to the test score\n",
    "\n",
    "Topics 24 and 25 gave many steps. Their order matters, and one question sorts them: does the step learn something from the rows? Steps that do not come before the split. Steps that do come after it and learn from the training data only.\n",
    "\n",
    "Here is the whole recipe once more in one place, from an empty notebook. Every cell is short, and nothing in it is new.\n",
    "\n",
    "Step 1: read the file and drop the columns without information."
   ],
   "id": "t25-077"
  },
  {
   "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",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "df = df.drop(columns=[\"laptop_id\", \"seller_name\", \"currency\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t25-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 2: clean the mistakes. The wrong prices are removed, the wrong weights are repaired."
   ],
   "id": "t25-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df[df[\"price\"] < 9000]\n",
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "\n",
    "print(df.shape)\n",
    "print(df[\"weight_kg\"].max(), df[\"price\"].max())"
   ],
   "id": "t25-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 3: encode the columns that need no learning."
   ],
   "id": "t25-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"touchscreen\"] = df[\"touchscreen\"].map({\"no\": 0, \"yes\": 1})\n",
    "df[\"condition\"] = df[\"condition\"].map({\"used\": 0, \"good\": 1, \"like new\": 2, \"new\": 3})\n",
    "df = pd.get_dummies(df, columns=[\"type\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist())"
   ],
   "id": "t25-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 4: split."
   ],
   "id": "t25-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "train = train.copy()\n",
    "test = test.copy()\n",
    "\n",
    "print(train.shape, test.shape)"
   ],
   "id": "t25-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 5: target encoding of the brand, from the training data."
   ],
   "id": "t25-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brand_means = train.groupby(\"brand\")[\"price\"].mean()\n",
    "\n",
    "train[\"brand_price\"] = train[\"brand\"].map(brand_means)\n",
    "test[\"brand_price\"] = test[\"brand\"].map(brand_means).fillna(train[\"price\"].mean())\n",
    "\n",
    "train = train.drop(columns=[\"brand\"])\n",
    "test = test.drop(columns=[\"brand\"])\n",
    "\n",
    "print(train.shape, test.shape)"
   ],
   "id": "t25-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The text column `brand` has done its work and is dropped. Every column is a number now.\n",
    "\n",
    "Step 6: select the features (Topic 24). First the correlation of every column with the price, in the training data:"
   ],
   "id": "t25-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(train.corr()[\"price\"].round(2).sort_values())"
   ],
   "id": "t25-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `usb_ports` has a correlation of practically zero with the price (it prints as `-0.00`): it says nothing. It is dropped.\n",
    "- `screen_inch` and `screen_cm` have exactly the same correlation with the price. That is suspicious:"
   ],
   "id": "t25-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(train[\"screen_inch\"].corr(train[\"screen_cm\"]), 2))"
   ],
   "id": "t25-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A correlation of 1.0: the two columns are the same measurement in two units, the purest case of multicollinearity. One of them is enough; `screen_cm` is dropped."
   ],
   "id": "t25-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "features = [\"ram_gb\", \"storage_gb\", \"screen_inch\", \"weight_kg\", \"age_months\", \"condition\", \"touchscreen\", \"type_office\", \"type_ultrabook\", \"brand_price\"]\n",
    "\n",
    "X_train = train[features]\n",
    "X_test = test[features]\n",
    "y_train = train[\"price\"]\n",
    "y_test = test[\"price\"]\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t25-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 7: scale (Topic 24). The scaler is fitted on the training data."
   ],
   "id": "t25-093"
  },
  {
   "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",
    "print(X_train_scaled.shape, X_test_scaled.shape)"
   ],
   "id": "t25-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The columns of 0 and 1 are scaled here together with the others. That is simple and does no harm; for a linear regression the score is the same with and without scaling (Topic 24), and the scaled weights can be compared.\n",
    "\n",
    "Step 8: train and judge."
   ],
   "id": "t25-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = LinearRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_train_scaled, y_train), 3))\n",
    "print(round(model.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t25-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Step 9: read the weights."
   ],
   "id": "t25-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name, weight in zip(features, model.coef_):\n",
    "    print(name, round(weight, 1))"
   ],
   "id": "t25-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After standard scaling the weights can be compared (Topic 24). Five features are about equally strong, each worth around 200 manat for one standard deviation: the disk, the type (office or not), the weight, the brand and the memory. The size of the screen matters least. The encoded columns stand in the list like any other number.\n",
    "\n",
    "The test score is 0.939, practically the 0.941 of Part 9: the two dropped columns carried nothing, and scaling does not change the score of a linear regression. The model is simpler, and its weights can be read.\n",
    "\n",
    "### 10.1 From the first model to the last\n",
    "\n",
    "| Step | Test score |\n",
    "| --- | --- |\n",
    "| the numerical columns as they came | $-0.618$ |\n",
    "| the wrong prices removed | 0.405 |\n",
    "| the wrong weights repaired | 0.527 |\n",
    "| `condition` and `touchscreen` encoded | 0.699 |\n",
    "| `type` one-hot encoded | 0.760 |\n",
    "| `brand` target encoded | 0.941 |\n",
    "| two columns dropped, features scaled | 0.939 |\n",
    "\n",
    "The model was a plain `LinearRegression` from the first line to the last. The data was the same file. Cleaning twelve wrong values and encoding four text columns made the whole difference.\n",
    "\n",
    "## 11. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Removing every value that a rule marks. | A rule finds candidates. Many of them are real values. | Look at the marked rows and decide: mistake or real? |\n",
    "| Calling a real extreme value a mistake because it disturbs the model. | The model will meet such cases in real use. | Keep it, cap it, or state a limit for the model. |\n",
    "| Calculating IQR limits or z-scores from all rows and splitting afterwards. | The test rows help to decide what the training data looks like: data leakage. | Split first; limits from the training data. |\n",
    "| Removing real extreme values from the test data. | The score becomes too flattering. | Leave the test data as the world is. |\n",
    "| Removing outliers only from the test data. | The model is trained on them and judged without them. | Never. |\n",
    "| Applying the IQR rule to every column. | Columns with a few fixed values lose their less common values; a large part of the rows disappears. | Selected columns with continuous measurements. |\n",
    "| Using the z-score on a small or strongly skewed column. | The outliers pull the mean and the standard deviation and hide themselves. | The IQR rule. |\n",
    "| Removing a row when the mistake can be repaired. | A row of good data is lost with it. | Repair when the cause is known. |\n",
    "| Dropping a text column because \"models need numbers\". | The information is lost. | Encode it. |\n",
    "| Label encoding for a column without order (a type, a city). | The numbers invent an order and distances that do not exist. | One-hot encoding. |\n",
    "| Letting an encoder order an ordinal column by the alphabet. | \"used\" becomes the best condition. | Give the order yourself. |\n",
    "| One-hot encoding for a column with hundreds of categories. | Hundreds of columns, most of them almost empty. | Target or frequency encoding. |\n",
    "| Target encoding with the means of all rows. | The target of the test rows is inside their feature. | Means from the training data only. |\n",
    "| `get_dummies` without `dtype=int` and wondering about `True` and `False`. | pandas makes truth values by default. | `dtype=int` |\n",
    "| Keeping all dummy columns in a linear model and reading the weights. | One column follows from the others: the dummy variable trap. | `drop_first=True` |\n",
    "| Forgetting a category that appears only in the test data. | `map` leaves a gap, and the model stops at it. | `fillna` with a sensible value; `handle_unknown=\"ignore\"` for `OneHotEncoder`. |\n",
    "\n",
    "## 12. Solved problems\n",
    "\n",
    "Fourteen problems. The first four are short and solved by hand; the others are in Python on `laptops.csv`, and each one starts on its own, from reading the file. The longer ones are split into two or three cells.\n",
    "\n",
    "Problem 1. The IQR rule by hand\n",
    "\n",
    "The delivery times of nine orders in days, sorted: `2, 3, 3, 4, 4, 5, 5, 6, 15`. Find the limits of the IQR rule and the outliers.\n",
    "\n",
    "Idea. The quartiles stand at the positions $1 + (n - 1) \\times p$ (Part 4).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "Q_1:\\quad & \\text{position } 1 + 8 \\times 0.25 = 3 \\\\\n",
    "& \\text{the third value: } Q_1 = 3 \\\\[6pt]\n",
    "Q_3:\\quad & \\text{position } 1 + 8 \\times 0.75 = 7 \\\\\n",
    "& \\text{the seventh value: } Q_3 = 5 \\\\[10pt]\n",
    "& \\text{IQR} = 5 - 3 = 2 \\\\[4pt]\n",
    "& 1.5 \\times \\text{IQR} = 3 \\\\[10pt]\n",
    "& \\text{lower limit} = 3 - 3 = 0 \\\\[4pt]\n",
    "& \\text{upper limit} = 5 + 3 = 8\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: all values from 2 to 6 lie between 0 and 8. The value 15 lies above 8: it is the only outlier. Whether it is a mistake or a delivery that really took 15 days, the rule cannot say.\n",
    "\n",
    "Problem 2. A z-score by hand\n",
    "\n",
    "The marks of an exam have the mean 70 and the standard deviation 8. Find the z-scores of the marks 94, 50 and 98. Which of them does the z-score rule with the limit 3 call an outlier?\n",
    "\n",
    "Idea. $z = \\frac{x - \\text{mean}}{\\text{standard deviation}}$ (Part 4).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "94:\\quad & \\frac{94 - 70}{8} = 3 \\\\[4pt]\n",
    "50:\\quad & \\frac{50 - 70}{8} = -2.5 \\\\[4pt]\n",
    "98:\\quad & \\frac{98 - 70}{8} = 3.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: only 98 has a z-score above 3. The mark 94 lies exactly on the limit and is not beyond it; 50 lies 2.5 standard deviations below the mean, which is far but inside the limits.\n",
    "\n",
    "Problem 3. Which encoding?\n",
    "\n",
    "A table of flats has the columns `balcony` (yes, no), `floor_level` (low, middle, high), `heating` (gas, electric, central) and `street` (340 different streets). Choose an encoding for each.\n",
    "\n",
    "Idea. Two questions: is there an order, and how many categories are there? (Part 6)\n",
    "\n",
    "- `balcony`: two values. 0 and 1.\n",
    "- `floor_level`: three values with an order. Label (ordinal) encoding: low = 0, middle = 1, high = 2.\n",
    "- `heating`: three values without an order. One-hot encoding.\n",
    "- `street`: 340 values without an order. Target encoding (or frequency encoding).\n",
    "\n",
    "Why: numbers in order are right only where the categories have an order. Without an order every category needs its own column, and when that would be hundreds of columns, the category is replaced by one number that is learned from the training data.\n",
    "\n",
    "Problem 4. Target encoding by hand\n",
    "\n",
    "Six flats of the training data are in the table below. Encode the district with target encoding. What does a test flat in the district \"East\" get?\n",
    "\n",
    "| district | price |\n",
    "| --- | --- |\n",
    "| North | 90 |\n",
    "| North | 110 |\n",
    "| South | 150 |\n",
    "| South | 170 |\n",
    "| South | 160 |\n",
    "| West | 200 |\n",
    "\n",
    "Idea. The mean of the target in every category; an unknown category gets the mean of all training rows (Part 9).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{North:}\\quad & \\frac{90 + 110}{2} = 100 \\\\[6pt]\n",
    "\\text{South:}\\quad & \\frac{150 + 170 + 160}{3} = 160 \\\\[6pt]\n",
    "\\text{West:}\\quad & \\frac{200}{1} = 200 \\\\[10pt]\n",
    "\\text{all rows:}\\quad & \\frac{90 + 110 + 150 + 170 + 160 + 200}{6} \\\\[4pt]\n",
    "& = \\frac{880}{6} = 146.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: North becomes 100, South 160 and West 200. \"East\" does not appear in the training data, so it gets the overall mean 146.667. The value of West rests on a single flat and should not be trusted much.\n",
    "\n",
    "Problem 5. Outliers of a column with the IQR rule\n",
    "\n",
    "Find the upper limit of the IQR rule for `weight_kg` in `laptops.csv` and print the number of weights above it.\n",
    "\n",
    "Idea. `quantile(0.25)` and `quantile(0.75)`, then the limit (Part 4)."
   ],
   "id": "t25-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "\n",
    "q1 = df[\"weight_kg\"].quantile(0.25)\n",
    "q3 = df[\"weight_kg\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(round(upper, 2))\n",
    "print((df[\"weight_kg\"] > upper).sum())"
   ],
   "id": "t25-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a comparison gives a column of `True` and `False`, and `sum()` counts the `True` values (Topic 10). Six weights lie above 3.58 kg: the six that were typed in grams.\n",
    "\n",
    "Problem 6. The z-score against the IQR rule\n",
    "\n",
    "Count the outliers of `storage_gb` with the z-score (limit 3) and with the IQR rule. Why do the two numbers differ so much?\n",
    "\n",
    "Idea. A skewed column with a few fixed values (Parts 4 and 5)."
   ],
   "id": "t25-101"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "\n",
    "z = (df[\"storage_gb\"] - df[\"storage_gb\"].mean()) / df[\"storage_gb\"].std()\n",
    "print((z.abs() > 3).sum())\n",
    "\n",
    "q1 = df[\"storage_gb\"].quantile(0.25)\n",
    "q3 = df[\"storage_gb\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "print(upper, (df[\"storage_gb\"] > upper).sum())"
   ],
   "id": "t25-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the z-score marks the ten laptops with 2,048 GB. The IQR rule puts its limit at 896 GB and marks all 44 laptops with 1,024 or 2,048 GB. None of them is a mistake: these are real disk sizes. A column with a few fixed values is not a place for outlier rules.\n",
    "\n",
    "Problem 7. Remove or repair\n",
    "\n",
    "Remove the rows with a price of 9,000 or more, and repair the weights above 10 by dividing them by 1,000. Print the shape of the table and the largest weight.\n",
    "\n",
    "Idea. A mistake whose true value is not known is removed; a mistake with a known cause is repaired (Part 5)."
   ],
   "id": "t25-103"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "\n",
    "df = df[df[\"price\"] < 9000]\n",
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "\n",
    "print(df.shape)\n",
    "print(df[\"weight_kg\"].max())"
   ],
   "id": "t25-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: six rows are gone, and six weights are right again without losing their rows. Both steps use a fixed rule, so they are done on the whole table before any split.\n",
    "\n",
    "Problem 8. Limits from the training data\n",
    "\n",
    "Clean the table as in Problem 7 and split it (`test_size=0.2`, `random_state=42`). Calculate the upper IQR limit of the price from the training data, and print it together with the number of training rows and of test rows above it.\n",
    "\n",
    "Idea. A limit that is learned from the rows is learned from the training rows (Part 5)."
   ],
   "id": "t25-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "df = df[df[\"price\"] < 9000]\n",
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "print(train.shape, test.shape)"
   ],
   "id": "t25-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The limit comes from `train` alone. Then the same limit is used to look at both parts:"
   ],
   "id": "t25-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = train[\"price\"].quantile(0.25)\n",
    "q3 = train[\"price\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((train[\"price\"] > upper).sum(), (test[\"price\"] > upper).sum())"
   ],
   "id": "t25-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the limit was calculated without the test data, and then the same limit was used to look at both parts. Three training laptops lie above it. They are real laptops, so nothing has to be done with them.\n",
    "\n",
    "Problem 9. Two values and an order\n",
    "\n",
    "Encode `touchscreen` as 0 and 1 and `condition` in its order from 0 to 3. Print the mean price for every value of the encoded `condition`, rounded to whole numbers.\n",
    "\n",
    "Idea. `map` with a dictionary (Part 7)."
   ],
   "id": "t25-109"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "df = df[df[\"price\"] < 9000]\n",
    "\n",
    "df[\"touchscreen\"] = df[\"touchscreen\"].map({\"no\": 0, \"yes\": 1})\n",
    "df[\"condition\"] = df[\"condition\"].map({\"used\": 0, \"good\": 1, \"like new\": 2, \"new\": 3})\n",
    "\n",
    "print(df.groupby(\"condition\")[\"price\"].mean().round(0))"
   ],
   "id": "t25-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the mean price rises clearly from 0 (used) to 2 (like new), which is what the order of the numbers promises to the model. Between 2 and 3 the two means are close: in this file other columns, such as the brand and the memory, differ between the two groups. The model with all columns sorts that out.\n",
    "\n",
    "Problem 10. One-hot encoding\n",
    "\n",
    "One-hot encode the column `type` with all three columns, and print how many laptops each type has by adding up the new columns.\n",
    "\n",
    "Idea. `pd.get_dummies` makes a column of 0 and 1 for every category; the sum of such a column counts its rows (Part 8)."
   ],
   "id": "t25-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "\n",
    "dummies = pd.get_dummies(df[\"type\"], dtype=int)\n",
    "\n",
    "print(dummies.head(3))\n",
    "print(dummies.sum())"
   ],
   "id": "t25-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: every row has exactly one 1, so the three sums add up to the 300 rows. With `drop_first=True` the column `gaming` would be left out and a gaming laptop would be the row with two zeros.\n",
    "\n",
    "Problem 11. Target encoding of a column\n",
    "\n",
    "Clean the prices, split the table (`test_size=0.2`, `random_state=42`) and encode `type` with target encoding from the training data. Print the three means, rounded to whole numbers, and the first three values of the new column in the test data.\n",
    "\n",
    "Idea. `groupby` on the training data, `map` on both parts (Part 9)."
   ],
   "id": "t25-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "df = df[df[\"price\"] < 9000]\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "train = train.copy()\n",
    "test = test.copy()\n",
    "\n",
    "print(train.shape, test.shape)"
   ],
   "id": "t25-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The means come from the training data and are used for both parts:"
   ],
   "id": "t25-115"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "type_means = train.groupby(\"type\")[\"price\"].mean()\n",
    "\n",
    "train[\"type_price\"] = train[\"type\"].map(type_means)\n",
    "test[\"type_price\"] = test[\"type\"].map(type_means)\n",
    "\n",
    "print(type_means.round(0))\n",
    "print(test[\"type_price\"].head(3).round(0).tolist())"
   ],
   "id": "t25-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the test laptops get the means of the training laptops, never their own. Target encoding works for any categorical column; for a column with three categories one-hot encoding is the more usual choice.\n",
    "\n",
    "Problem 12. Does the encoding help?\n",
    "\n",
    "Clean the table as in Problem 7. Compare two models with the test score: one with `ram_gb`, `storage_gb`, `weight_kg` and `age_months`, and one that also gets the encoded `condition`.\n",
    "\n",
    "Idea. The judge of every feature is the score on the test data (Topic 24)."
   ],
   "id": "t25-117"
  },
  {
   "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(\"laptops.csv\")\n",
    "df = df[df[\"price\"] < 9000]\n",
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "df[\"condition\"] = df[\"condition\"].map({\"used\": 0, \"good\": 1, \"like new\": 2, \"new\": 3})\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "print(train.shape, test.shape)"
   ],
   "id": "t25-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two models, one after the other. Every line of the output shows the number of features and the test score:"
   ],
   "id": "t25-119"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = [\"ram_gb\", \"storage_gb\", \"weight_kg\", \"age_months\"]\n",
    "\n",
    "for features in [columns, columns + [\"condition\"]]:\n",
    "    model = LinearRegression()\n",
    "    model.fit(train[features], train[\"price\"])\n",
    "    print(len(features), round(model.score(test[features], test[\"price\"]), 3))"
   ],
   "id": "t25-120"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: one encoded column raises the score clearly. The information was in the file all the time; the model could not read it while it was text.\n",
    "\n",
    "Problem 13. Frequency encoding\n",
    "\n",
    "Split the table of Problem 7 and encode `brand` with frequency encoding from the training data. Print the three most common brands with their shares, rounded to 3 decimals.\n",
    "\n",
    "Idea. `value_counts(normalize=True)` on the training data, then `map` (Part 9)."
   ],
   "id": "t25-121"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "df = df[df[\"price\"] < 9000]\n",
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "train = train.copy()\n",
    "test = test.copy()\n",
    "\n",
    "print(train.shape, test.shape)"
   ],
   "id": "t25-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The shares come from the training data:"
   ],
   "id": "t25-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "brand_share = train[\"brand\"].value_counts(normalize=True)\n",
    "\n",
    "train[\"brand_share\"] = train[\"brand\"].map(brand_share)\n",
    "test[\"brand_share\"] = test[\"brand\"].map(brand_share).fillna(0)\n",
    "\n",
    "print(brand_share.head(3).round(3))"
   ],
   "id": "t25-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: every brand is replaced by its share of the training rows. A brand that the training data does not contain would get 0: it was never seen.\n",
    "\n",
    "Problem 14. A small complete recipe\n",
    "\n",
    "Use the features `ram_gb`, `weight_kg`, `age_months` and the encoded `condition` and `touchscreen`. Clean, encode, split (`test_size=0.2`, `random_state=42`), scale with a `StandardScaler` and train a `LinearRegression`. Print the test score and the weights.\n",
    "\n",
    "Idea. The order of Part 10: clean, encode by rule, split, scale with the training data, train.\n",
    "\n",
    "Clean and encode:"
   ],
   "id": "t25-125"
  },
  {
   "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",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "df = pd.read_csv(\"laptops.csv\")\n",
    "df = df[df[\"price\"] < 9000]\n",
    "df.loc[df[\"weight_kg\"] > 10, \"weight_kg\"] = df[\"weight_kg\"] / 1000\n",
    "df[\"touchscreen\"] = df[\"touchscreen\"].map({\"no\": 0, \"yes\": 1})\n",
    "df[\"condition\"] = df[\"condition\"].map({\"used\": 0, \"good\": 1, \"like new\": 2, \"new\": 3})\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t25-126"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Split, then scale with the numbers of the training data:"
   ],
   "id": "t25-127"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "features = [\"ram_gb\", \"weight_kg\", \"age_months\", \"condition\", \"touchscreen\"]\n",
    "train, test = train_test_split(df, test_size=0.2, random_state=42)\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(train[features])\n",
    "X_test_scaled = scaler.transform(test[features])\n",
    "\n",
    "print(X_train_scaled.shape, X_test_scaled.shape)"
   ],
   "id": "t25-128"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Train, judge, and read the weights:"
   ],
   "id": "t25-129"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = LinearRegression()\n",
    "model.fit(X_train_scaled, train[\"price\"])\n",
    "\n",
    "print(round(model.score(X_test_scaled, test[\"price\"]), 3))\n",
    "for name, weight in zip(features, model.coef_):\n",
    "    print(name, round(weight, 1))"
   ],
   "id": "t25-130"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the scaler was fitted on the training data and applied to both parts. Because the features are standardised, the weights can be compared: the memory has the largest effect of these five, and the two encoded columns stand in the list like any other number.\n",
    "\n",
    "## 15. Summary\n",
    "\n",
    "| Outliers |  |\n",
    "| --- | --- |\n",
    "| IQR rule | below $Q_1 - 1.5 \\times \\text{IQR}$ or above $Q_3 + 1.5 \\times \\text{IQR}$; the usual first choice |\n",
    "| z-score | below $-3$ or above 3; for bell-shaped columns with many rows |\n",
    "| Mistakes | repair (cause known) or remove; whole table, before the split |\n",
    "| Real extreme values | often keep; otherwise cap or remove in the training data, with limits from the training data |\n",
    "| Test data | only mistakes are cleaned; real values stay |\n",
    "| Columns | selected ones with continuous measurements, never all |\n",
    "\n",
    "| The column | Encoding |\n",
    "| --- | --- |\n",
    "| two values | 0 and 1 |\n",
    "| ordered categories | label (ordinal) encoding in your own order |\n",
    "| no order, few categories | one-hot (dummy) encoding, `drop_first=True` for linear models |\n",
    "| no order, many categories | target encoding, from the training data |\n",
    "| no order, many categories, frequency matters | frequency encoding |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `df[c].quantile(0.25)` | the first quartile |\n",
    "| `z = (df[c] - df[c].mean()) / df[c].std()` | the z-scores |\n",
    "| `df = df[df[c] < limit]` | removes rows |\n",
    "| `df.loc[df[c] > 10, c] = df[c] / 1000` | repairs values in chosen rows |\n",
    "| `train[c].clip(upper=limit)` | caps values |\n",
    "| `df[c].map({\"no\": 0, \"yes\": 1})` | encodes with a dictionary |\n",
    "| `pd.get_dummies(df, columns=[c], drop_first=True, dtype=int)` | one-hot encoding |\n",
    "| `train.groupby(c)[\"price\"].mean()` | the means for target encoding |\n",
    "| `train[c].value_counts(normalize=True)` | the shares for frequency encoding |\n",
    "\n",
    "### The order of the steps\n",
    "\n",
    "1. Drop the columns without information.\n",
    "2. Clean the mistakes: repair or remove.\n",
    "3. Encode what needs no learning: 0 and 1, ordinal, one-hot.\n",
    "4. Split.\n",
    "5. Learn from the training data: limits for real extreme values, target or frequency encoding, the selection of features, the scaler.\n",
    "6. Train on the training data, judge on the test data.\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. A rule finds outliers. You decide whether they are mistakes.\n",
    "2. Mistakes are cleaned everywhere. Real extreme values stay in the test data.\n",
    "3. Whatever learns from the rows learns from the training rows only.\n",
    "4. Never drop a text column that carries information: encode it.\n",
    "5. Numbers in order only for categories in order. Without order: one column per category.\n",
    "6. Target encoding only with the means of the training data.\n",
    "7. The judge of every step is the score on the test data.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "The data is now clean, encoded and scaled, and the model has more features than ever. More features are also more room for overfitting. Topic 26, Ridge and Lasso regression, shows how a linear model is kept simple while it is trained: regularization.\n",
    "\n",
    "Next: the practice notebook (topic-25-practice.ipynb), then Topic 26: Regularization: Ridge and Lasso regression."
   ],
   "id": "t25-131"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
