{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 33: k-Nearest Neighbors - Regression\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 17, 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-33-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 5 to 7 are one project that starts from the raw file, so start at the first cell of Part 5. The solved problems 5 to 16 are a second project that starts again from reading the file. Cells that try many values of k take a few seconds.\n",
    "\n",
    "This notebook reads the file car_prices.csv. Put the file into the same folder as the notebook. On the Asiman Data School website the file is already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. From a class to a number\n",
    "2. How it predicts: an example with eight cars\n",
    "3. The hyperparameters, and what is different for regression\n",
    "4. Preprocessing for k-nearest neighbours regression, and for the models still to come\n",
    "5. The project: from the raw file to the scaled data\n",
    "6. The model\n",
    "7. Choosing k, the features and the other hyperparameters\n",
    "8. The workflow, step by step\n",
    "9. Common mistakes\n",
    "10. Solved problems\n",
    "11. Practice (in topic-33-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Summary"
   ],
   "id": "t33-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: the price of the neighbours\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, k-nearest neighbours regression predicts the mean of the values of the k nearest training rows (or a mean weighted by $\\frac{1}{\\text{distance}}$). Second, a mean cannot tie, so k does not have to be odd, and a very large k predicts the mean of all training values. Third, scaling is essential, and with many one-hot columns the choice of a few useful features matters more than anything else: here it lifted the R² from 0.64 to 0.81. Fourth, k, `weights` and the features are chosen with cross-validation and judged with R², MAE and RMSE. Fifth, the model cannot predict outside the range of its training values.\n",
    "\n",
    "What is the same as in Topic 32 (distances, the hyperparameters, overfitting with a small k) is only recalled, with the place where Topic 32 explains it.\n",
    "\n",
    "The thirteenth lesson of Module 3. Topic 32 used k-nearest neighbours to predict a class: will a customer leave the bank? This lesson uses the same idea to predict a number: the price of a car. The neighbours no longer vote; the model takes the mean of their prices.\n",
    "\n",
    "Almost everything else is the same as in Topic 32: the distances, the need for scaling, the hyperparameters, the choice of k with cross-validation. This lesson recalls those parts in one or two sentences and points to the place in Topic 32. The time goes to what is new when the target is a number:\n",
    "\n",
    "- the prediction as the mean (or the weighted mean) of the neighbours' values, worked by hand;\n",
    "- why an odd k does not matter any more, and what a very large k predicts;\n",
    "- the measures of regression: R², MAE and RMSE (Topic 22);\n",
    "- a data set with many one-hot columns, where the choice of the features decides almost everything (the curse of dimensionality, seen clearly);\n",
    "- what k-nearest neighbours cannot predict.\n",
    "\n",
    "The data is `car_prices.csv`, the 10,000 car adverts of Topic 31, again from the raw file: every preprocessing step is done in the lesson.\n",
    "\n",
    "You need: k-nearest neighbours for classes (Topic 32), linear regression and the measures R², MAE and RMSE (Topic 22), the train/test split, cross-validation and overfitting (Topic 23), scaling and encoding (Topics 24 and 25), and the cleaning of the car data (Topic 31).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| k-nearest neighbours regression | a model that predicts a number as the mean of the values of the k most similar training rows |\n",
    "| Weighted mean | a mean in which close neighbours count more: each value is weighted by $\\frac{1}{\\text{distance}}$ |\n",
    "| R² | the share of the variance of the target that the model explains (Topic 22) |\n",
    "| MAE | mean absolute error: the typical error, in manats |\n",
    "| RMSE | root mean squared error: in manats too, large errors count more |\n",
    "| Curse of dimensionality | with many features, all rows become almost equally far apart, and \"nearest\" loses its meaning |\n",
    "| Extrapolation | predicting outside the range of the training data; k-nearest neighbours cannot do it |\n",
    "\n",
    "## 1. From a class to a number\n",
    "\n",
    "### 1.1 What stays the same\n",
    "\n",
    "| Idea | In short | Where in Topic 32 |\n",
    "| --- | --- | --- |\n",
    "| Lazy learner | `fit` only stores the training rows; all the work happens in `predict` | Part 1 |\n",
    "| The k nearest | for a new row, measure the distance to every training row and take the k smallest | Part 2 |\n",
    "| Distances | Euclidean (`p=2`, the default), Manhattan (`p=1`), Minkowski | Part 3 |\n",
    "| Scaling is essential | without it the feature with the largest numbers decides every distance | Part 3 |\n",
    "| Hyperparameters | `n_neighbors`, `weights`, `metric`, `p`, `algorithm`, `leaf_size`, `n_jobs`; no `random_state` | Part 4 |\n",
    "| Small k overfits, large k underfits | k = 1 memorises the training data; the gap closes as k grows | Part 4 |\n",
    "| k is chosen with cross-validation | never with the test data | Part 4 |\n",
    "| Preprocessing | scaling, one-hot encoding, filled gaps, a look at outliers, no useless features | Part 5 |\n",
    "\n",
    "If one of these is not clear, read its place in Topic 32 first: this lesson uses all of them.\n",
    "\n",
    "### 1.2 What changes\n",
    "\n",
    "|  | Classification (Topic 32) | Regression (this topic) |\n",
    "| --- | --- | --- |\n",
    "| Target | a class: leaves or stays | a number: the price of a car |\n",
    "| The k neighbours | vote | give their values |\n",
    "| The prediction | the class with the most votes | the mean of the neighbours' values |\n",
    "| `predict_proba` | the share of the votes | does not exist |\n",
    "| `weights=\"distance\"` | a weighted vote | a weighted mean |\n",
    "| Odd k | needed for two classes, to avoid ties | not needed: a mean never ties |\n",
    "| A very large k | always predicts the largest class | always predicts the mean of all training values |\n",
    "| Measures | accuracy, recall, F1, AUC (Topic 28) | R², MAE, RMSE (Topic 22) |\n",
    "| In scikit-learn | `KNeighborsClassifier` | `KNeighborsRegressor` |\n",
    "\n",
    "### 1.3 Where k-nearest neighbours regression is used\n",
    "\n",
    "- Prices: what similar flats, houses or cars sold for (the project of this lesson).\n",
    "- Recommendations with a score: the rating a user would give a film, from the ratings of similar users.\n",
    "- Filling missing numbers: `KNNImputer` fills a gap with the mean of the nearest rows (Topic 32).\n",
    "- Science and engineering: a measurement estimated from the most similar earlier measurements, for example the energy use of a building from similar buildings.\n",
    "- As a simple baseline: a quick model to compare the others with.\n",
    "\n",
    "## 2. How it predicts: an example with eight cars\n",
    "\n",
    "Eight cars, described by two features: their age in years and their engine volume in litres. The target is the price in thousands of manats.\n",
    "\n",
    "| Car | Age (years) | Engine (litres) | Price (thousand AZN) |\n",
    "| --- | --- | --- | --- |\n",
    "| A | 2 | 2.0 | 30 |\n",
    "| B | 3 | 1.6 | 22 |\n",
    "| C | 5 | 2.0 | 18 |\n",
    "| D | 8 | 1.6 | 10 |\n",
    "| E | 1 | 3.0 | 45 |\n",
    "| F | 6 | 2.5 | 20 |\n",
    "| G | 10 | 1.4 | 6 |\n",
    "| H | 4 | 1.8 | 24 |\n",
    "\n",
    "A new car N is 4 years old and has a 2.0-litre engine. What is its price?\n",
    "\n",
    "### 2.1 Step 1: the distances\n",
    "\n",
    "Exactly as in Topic 32, the Euclidean distance. For N = (4, 2.0) and H = (4, 1.8):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{distance}(N, H) \\\\[4pt]\n",
    "&= \\sqrt{(4 - 4)^2 + (2.0 - 1.8)^2} \\\\[4pt]\n",
    "&= \\sqrt{0 + 0.04} = \\sqrt{0.04} = 0.2\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For N and B = (3, 1.6):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{distance}(N, B) \\\\[4pt]\n",
    "&= \\sqrt{(4 - 3)^2 + (2.0 - 1.6)^2} \\\\[4pt]\n",
    "&= \\sqrt{1 + 0.16} = \\sqrt{1.16} = 1.077\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "All eight, from the nearest to the farthest:\n",
    "\n",
    "| Rank | Car | Distance | Price |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | H | $\\sqrt{0.04} = 0.2$ | 24 |\n",
    "| 2 | C | $\\sqrt{1} = 1$ | 18 |\n",
    "| 3 | B | $\\sqrt{1.16} = 1.077$ | 22 |\n",
    "| 4 | A | $\\sqrt{4} = 2$ | 30 |\n",
    "| 5 | F | $\\sqrt{4.25} = 2.062$ | 20 |\n",
    "| 6 | E | $\\sqrt{10} = 3.162$ | 45 |\n",
    "| 7 | D | $\\sqrt{16.16} = 4.02$ | 10 |\n",
    "| 8 | G | $\\sqrt{36.36} = 6.03$ | 6 |\n",
    "\n",
    "The picture is on the lesson page: the eight cars as points (age against engine), each labelled with its price, the new car N at (4, 2.0), and its three nearest neighbours H, C and B marked.\n",
    "\n",
    "### 2.2 Step 2: the mean of the k nearest\n",
    "\n",
    "| k | The k nearest | Their prices | Prediction |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | H | 24 | 24 |\n",
    "| 3 | H, C, B | 24, 18, 22 | $\\frac{24 + 18 + 22}{3} = 21.333$ |\n",
    "| 5 | H, C, B, A, F | 24, 18, 22, 30, 20 | $\\frac{24 + 18 + 22 + 30 + 20}{5} = 22.8$ |\n",
    "| 8 | all eight | all prices | $\\frac{175}{8} = 21.875$ |\n",
    "\n",
    "With k = 3:\n",
    "\n",
    "$$\n",
    "\\text{prediction} = \\frac{24 + 18 + 22}{3} = \\frac{64}{3} = 21.333\n",
    "$$\n",
    "\n",
    "N is predicted at about 21,333 manats. Four lessons are in this table:\n",
    "\n",
    "- The answer depends on k, as for classes.\n",
    "- k = 1 copies one car. N gets exactly H's price, with every accident of H's advert: overfitting.\n",
    "- k = all eight gives the mean of all training prices, 21.875, for every new car whatever its age or engine: the model has stopped looking at the features. That is underfitting, the regression version of \"always the largest class\".\n",
    "- No ties. A mean is always one number, so k = 2, 4 or 8 is as good a choice as an odd k. The rule \"odd k\" of Topic 32 was only about votes.\n",
    "\n",
    "### 2.3 The weighted mean\n",
    "\n",
    "H is five times closer to N than C. With `weights=\"distance\"` each price is weighted by $\\frac{1}{\\text{distance}}$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "w_H &= \\tfrac{1}{0.2} = 5 \\\\[4pt]\n",
    "w_C &= \\tfrac{1}{1} = 1 \\\\[4pt]\n",
    "w_B &= \\tfrac{1}{1.077} = 0.929\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{prediction} \\\\[4pt]\n",
    "&= \\frac{5 \\times 24 + 1 \\times 18 + 0.929 \\times 22}{5 + 1 + 0.929} \\\\[4pt]\n",
    "&= \\frac{158.438}{6.929} = 22.866\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The very close H pulls the prediction towards its own price, 24. The weighted mean trusts close cars more than far ones, which is often right for prices. Its weakness is the same as in Topic 32: every training car is its own neighbour at the distance 0, so the training R² becomes almost 1 and says nothing.\n",
    "\n",
    "### 2.4 A second kind of tie\n",
    "\n",
    "Two training cars can be at exactly the same distance at the edge of the k nearest. scikit-learn then takes the car that comes first in the training data, as in Topic 32. In real data with many cars that have the same year, engine and mileage, this happens more often than one would think.\n",
    "\n",
    "## 3. The hyperparameters, and what is different for regression\n",
    "\n",
    "`KNeighborsRegressor` has the same hyperparameters as `KNeighborsClassifier` (Topic 32, Part 4):\n",
    "\n",
    "| Hyperparameter | Default | Role in regression |\n",
    "| --- | --- | --- |\n",
    "| `n_neighbors` | `5` | k, the number of neighbours whose values are averaged. Small: overfitting; large: underfitting, up to the mean of all training values. |\n",
    "| `weights` | `\"uniform\"` | `\"uniform\"`: a plain mean. `\"distance\"`: a mean weighted by $\\frac{1}{\\text{distance}}$. |\n",
    "| `metric`, `p` | `\"minkowski\"`, `2` | the distance: Euclidean with `p=2`, Manhattan with `p=1` |\n",
    "| `algorithm`, `leaf_size` | `\"auto\"`, `30` | how the neighbours are searched: speed only |\n",
    "| `n_jobs` | `None` | processor cores for the search |\n",
    "\n",
    "There is no `random_state` (nothing is random), no `class_weight` and no `predict_proba` (there are no classes).\n",
    "\n",
    "### 3.1 Choosing k for regression\n",
    "\n",
    "1. Even or odd does not matter: a mean cannot tie.\n",
    "2. A first guess of $k \\approx \\sqrt{n}$ is again only a starting point; on the car data a small k is better.\n",
    "3. Cross-validation chooses k (Topic 23), and here it also chooses `weights` and the features.\n",
    "4. The training score with k = 1 or with `weights=\"distance\"` is close to 1 and means nothing.\n",
    "\n",
    "### 3.2 Small and large k in one picture\n",
    "\n",
    "The picture is on the lesson page: 300 cars by year and price, the prediction of k = 1 (jumping from one car's price to the next) and of k = 25 (a smooth curve), and both lines flat after the newest year in the data.\n",
    "\n",
    "The picture uses only the year of 300 cars. With k = 1 the prediction jumps from the price of one car to the price of the next: every accident of a single advert is copied. With k = 25 it is a smooth curve: the mean of 25 cars of about the same year. After the newest year in the data both lines are flat, which is the next point.\n",
    "\n",
    "### 3.3 What k-nearest neighbours cannot predict\n",
    "\n",
    "A prediction is a mean of training prices. A mean is never higher than the highest of its values. So, exactly like the random forest of Topic 31, k-nearest neighbours cannot predict outside the range of the training prices: a new car newer or more expensive than all training cars gets about the price of the most similar training cars. With k = 5 it is even stricter: a prediction is a mean of five prices, so it can reach the most expensive training price only if the five nearest cars are all that expensive.\n",
    "\n",
    "## 4. Preprocessing for k-nearest neighbours regression, and for the models still to come\n",
    "\n",
    "The rules of Topic 32 (Part 5) hold, and the car data shows two of them more strongly than the bank data:\n",
    "\n",
    "- Scaling: essential. The mileage is counted in hundreds of thousands of kilometres, the engine in litres. Without scaling, the mileage decides every distance alone.\n",
    "- Encoding: needed, but it brings many columns. One-hot encoding of eight text columns gives 83 features, most of them 0 or 1. After scaling, every one of them counts in the distance as much as the year.\n",
    "- Useless features and the curse of dimensionality. With 83 features, two cars that are alike in year, engine and mileage can still look far apart because they differ in colour, city and market. The true neighbours are hidden. For k-nearest neighbours the choice of a few useful features is often the largest improvement of all (Part 7).\n",
    "- Missing values: must be filled. A distance cannot be computed with a gap. The training medians fill them after the split, as in Topic 31.\n",
    "- Repeated rows and impossible values. A repeated advert in the training and the test data would be its own nearest neighbour; it is dropped before the split. A year 0 would make a car far from everything; such rows are removed (Topic 31).\n",
    "- Outliers in the target. A very expensive car pulls the mean of its neighbours up; with a small k one such neighbour changes a prediction a lot. They are real cars and stay.\n",
    "\n",
    "| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |\n",
    "| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |\n",
    "| Decision tree, random forest, bagged trees (29, 30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |\n",
    "| k-nearest neighbours (32, 33) | essential: distances | needed; few, useful columns | sensitive | fill |\n",
    "| Naive Bayes (34) | not needed for the usual Gaussian form | needed | sensitive | fill |\n",
    "| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive | fill |\n",
    "| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost, LightGBM and CatBoost handle them |\n",
    "| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |\n",
    "\n",
    "Topic 42 will put the preprocessing and the model into one object, so that every step is fitted on the right rows.\n",
    "\n",
    "## 5. The project: from the raw file to the scaled data\n",
    "\n",
    "Now the data: `car_prices.csv`, the 10,000 car adverts of Topic 31.\n",
    "\n",
    "The file is the raw data: the repeated adverts, the missing values, the impossible values, the outliers and the text columns are all still in it. Every step is done again and explained as if it were new; Topic 31 (Part 6) gives the longer reasons for each one. The cells continue from each other like the cells of a notebook.\n",
    "\n",
    "### 5.1 Step 1: read and look"
   ],
   "id": "t33-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"car_prices.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head())"
   ],
   "id": "t33-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10,000 adverts and 19 columns: the brand and model, the year, the engine volume and horsepower, the fuel, the mileage, the gearbox, the driven wheels, the body, the colour, the seats, the owners, three yes/no columns (new, damaged, painted), the market, the city, and the target `price_azn`, the price in manats.\n",
    "\n",
    "### 5.2 Step 2: check"
   ],
   "id": "t33-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())"
   ],
   "id": "t33-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Missing values in several columns, and 691 adverts that appear twice.\n",
    "\n",
    "### 5.3 Step 3: drop the repeated rows"
   ],
   "id": "t33-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop_duplicates()\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t33-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For k-nearest neighbours a repeated advert is the worst kind of leak: if one copy lands in the training data and the other in the test data, the test copy finds itself as its nearest neighbour at the distance 0 and gets its own price.\n",
    "\n",
    "### 5.4 Step 4: remove the impossible rows"
   ],
   "id": "t33-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df[(df[\"year\"] >= 1950) & (df[\"mileage_km\"] <= 1_000_000)]\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t33-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A year 0 and a mileage of three million kilometres are mistakes in the adverts (Topic 31, Steps 4 and 5).\n",
    "\n",
    "### 5.5 Step 5: drop the column with too many categories"
   ],
   "id": "t33-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"model\"].nunique())\n",
    "\n",
    "df = df.drop(columns=[\"model\"])"
   ],
   "id": "t33-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "797 different models would become 796 one-hot columns: far too many for a model that measures distances.\n",
    "\n",
    "### 5.6 Step 6: the target"
   ],
   "id": "t33-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"price_azn\"].describe().round(0))"
   ],
   "id": "t33-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Prices from 1,200 to 160,000 manats; the mean is above the median, because a few expensive cars pull it up. They are real cars and stay.\n",
    "\n",
    "The features have outliers too:"
   ],
   "id": "t33-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for column in [\"mileage_km\", \"engine_l\", \"horsepower\"]:\n",
    "    q1 = df[column].quantile(0.25)\n",
    "    q3 = df[column].quantile(0.75)\n",
    "    upper = q3 + 1.5 * (q3 - q1)\n",
    "    print(column, upper, (df[column] > upper).sum())"
   ],
   "id": "t33-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hundreds of cars with a long mileage, a large engine or a strong motor: real taxis, trucks and sports cars. For k-nearest neighbours they matter more than for a forest (Topic 32, Part 5): after scaling, a 15-litre truck is far from almost every car, and its neighbours are the few other trucks. That is right, so they stay; but they also stretch the scale of their feature for everybody else.\n",
    "\n",
    "### 5.7 Step 7: group the rare brands and fill the missing market"
   ],
   "id": "t33-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counts = df[\"brand\"].value_counts()\n",
    "rare = counts[counts < 50].index\n",
    "df.loc[df[\"brand\"].isin(rare), \"brand\"] = \"other\"\n",
    "\n",
    "df[\"market\"] = df[\"market\"].fillna(\"unknown\")\n",
    "\n",
    "print(df[\"brand\"].nunique())\n",
    "print((df[\"market\"] == \"unknown\").sum())"
   ],
   "id": "t33-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Brands with fewer than 50 cars become `\"other\"`, and a missing market becomes a category of its own.\n",
    "\n",
    "### 5.8 Step 8: encode"
   ],
   "id": "t33-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_columns = [\"brand\", \"fuel\", \"gearbox\", \"drive\", \"body\", \"colour\", \"market\", \"city\"]\n",
    "\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t33-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "83 features and the target. Keep this number in mind: for k-nearest neighbours every one of these columns takes part in every distance.\n",
    "\n",
    "### 5.9 Step 9: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: about 2,780 cars become test data."
   ],
   "id": "t33-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"price_azn\"])\n",
    "y = df[\"price_azn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t33-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "7,407 cars for training (the neighbours that will be searched) and 1,852 for the test, the same cars as in Topic 31.\n",
    "\n",
    "### 5.10 Step 10: fill the missing numbers with the training medians"
   ],
   "id": "t33-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()\n",
    "\n",
    "X_train = X_train.fillna(medians)\n",
    "X_test = X_test.fillna(medians)\n",
    "\n",
    "print(X_train.isna().sum().sum(), X_test.isna().sum().sum())"
   ],
   "id": "t33-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "k-nearest neighbours cannot measure a distance with a gap. The medians come from the training cars only (Topic 23).\n",
    "\n",
    "### 5.11 Step 11: scale"
   ],
   "id": "t33-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(X_train[[\"year\", \"engine_l\", \"mileage_km\"]].std().round(1))"
   ],
   "id": "t33-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mileage spreads about 100,000 times more than the engine volume: without scaling it would decide every distance alone."
   ],
   "id": "t33-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(X_train_scaled.shape, X_test_scaled.shape)"
   ],
   "id": "t33-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The scaler learns the mean and the standard deviation of every feature from the training cars and applies them to both parts (Topic 24).\n",
    "\n",
    "## 6. The model\n",
    "\n",
    "### 6.1 Train and judge\n",
    "\n",
    "Change it and run: write `KNeighborsRegressor(n_neighbors=1)` and run: the training R² becomes almost 1."
   ],
   "id": "t33-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "\n",
    "knn = KNeighborsRegressor()\n",
    "knn.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(knn.score(X_train_scaled, y_train), 4))\n",
    "print(round(knn.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t33-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`KNeighborsRegressor` lives in `sklearn.neighbors`, next to the classifier, and `score` gives the R². With k = 5 and all 83 features the model explains about 64 percent of the variance of the test prices: far below the random forest of Topic 31 (0.865 on the same test cars). The rest of the lesson finds out why, and how to do better.\n",
    "\n",
    "### 6.2 The measures of regression"
   ],
   "id": "t33-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error\n",
    "\n",
    "predicted = knn.predict(X_test_scaled)\n",
    "\n",
    "print(round(r2_score(y_test, predicted), 4))\n",
    "print(round(mean_absolute_error(y_test, predicted)))\n",
    "print(round(root_mean_squared_error(y_test, predicted)))"
   ],
   "id": "t33-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A typical error of about 5,200 manats (the MAE), and an RMSE of about 8,400: some cars are predicted very badly.\n",
    "\n",
    "### 6.3 How it predicts one car\n",
    "\n",
    "Change it and run: change both `[[0]]` and `iloc[0]` to the position 5 and look at the neighbours of another car."
   ],
   "id": "t33-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "car = X_test_scaled[[0]]\n",
    "\n",
    "distances, positions = knn.kneighbors(car)\n",
    "\n",
    "print(distances.round(3))\n",
    "print(y_train.iloc[positions[0]].tolist())\n",
    "print(knn.predict(car))\n",
    "print(y_test.iloc[0])"
   ],
   "id": "t33-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The five nearest training cars, their distances and their prices. The prediction, 25,200 manats, is exactly the mean of the five prices. The car really costs 42,500: its five \"nearest\" cars all cost between 23,500 and 27,500. With 83 features, the cars that are nearest in all columns together are not necessarily the most similar in what decides a price.\n",
    "\n",
    "### 6.4 How much do the neighbours agree?\n",
    "\n",
    "The five prices say more than their mean. When they are close to each other, the neighbours agree and the prediction is trustworthy; when they spread widely, it is not. Their standard deviation (Topic 18) measures it:"
   ],
   "id": "t33-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = y_train.iloc[positions[0]]\n",
    "\n",
    "print(round(np.std(prices)))"
   ],
   "id": "t33-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The five prices of this car lie close together (a spread of about 1,800 manats), and yet the true price is far away: the neighbours agree with each other, but they are the wrong neighbours. A small spread is a good sign only when the features that decide the distance are the right ones; Part 7 comes back to this.\n",
    "\n",
    "### 6.5 Without scaling"
   ],
   "id": "t33-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "unscaled = KNeighborsRegressor()\n",
    "unscaled.fit(X_train, y_train)\n",
    "\n",
    "print(round(unscaled.score(X_test, y_test), 4))"
   ],
   "id": "t33-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On the unscaled features the R² falls to 0.39: the neighbours were chosen almost only by the mileage, the feature with the largest numbers.\n",
    "\n",
    "### 6.6 The model cannot go beyond the training prices"
   ],
   "id": "t33-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(y_train.max())\n",
    "print(round(predicted.max()))"
   ],
   "id": "t33-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The most expensive training car costs 160,000 manats, but the highest prediction for a test car is far below it: a mean of five prices is pulled towards the middle.\n",
    "\n",
    "## 7. Choosing k, the features and the other hyperparameters\n",
    "\n",
    "### 7.1 k from 1 to 51\n",
    "\n",
    "Change it and run: add `101` and `501` to the list and run: very large k drift towards the mean."
   ],
   "id": "t33-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k in [1, 3, 5, 7, 10, 15, 25, 51]:\n",
    "    model = KNeighborsRegressor(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    train_r2 = round(model.score(X_train_scaled, y_train), 4)\n",
    "    test_r2 = round(model.score(X_test_scaled, y_test), 4)\n",
    "    print(k, train_r2, test_r2)"
   ],
   "id": "t33-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows k, the training R² and the test R².\n",
    "\n",
    "- k = 1 has a training R² of almost 1 (not exactly 1: a few training cars have exactly the same features but different prices) and a low test R²: overfitting.\n",
    "- The test R² is highest around k = 3 to 5, then falls: with many neighbours the prediction drifts towards the mean of all prices.\n",
    "- k = 10 (even) is a perfectly good value here: there is nothing to tie."
   ],
   "id": "t33-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "ks = [1, 2, 3, 5, 7, 10, 15, 20, 30, 40, 51]\n",
    "train_scores = []\n",
    "test_scores = []\n",
    "\n",
    "for k in ks:\n",
    "    model = KNeighborsRegressor(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    train_scores.append(model.score(X_train_scaled, y_train))\n",
    "    test_scores.append(model.score(X_test_scaled, y_test))\n",
    "\n",
    "plt.plot(ks, train_scores, marker=\"o\", label=\"training R²\")\n",
    "plt.plot(ks, test_scores, marker=\"o\", label=\"test R²\")\n",
    "plt.xlabel(\"k (n_neighbors)\")\n",
    "plt.ylabel(\"R²\")\n",
    "plt.title(\"Small k overfits; large k drifts towards the mean\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t33-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.2 k chosen with cross-validation"
   ],
   "id": "t33-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for k in [3, 5, 7, 10, 15]:\n",
    "    model = KNeighborsRegressor(n_neighbors=k)\n",
    "    scores = cross_val_score(model, X_train_scaled, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))"
   ],
   "id": "t33-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a regressor `cross_val_score` uses the R² by default. k = 5 and k = 7 are about equally good, and both are far below the random forest.\n",
    "\n",
    "### 7.3 `weights` and `p`"
   ],
   "id": "t33-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for weights in [\"uniform\", \"distance\"]:\n",
    "    for p in [1, 2]:\n",
    "        model = KNeighborsRegressor(n_neighbors=5, weights=weights, p=p)\n",
    "        model.fit(X_train_scaled, y_train)\n",
    "        train_r2 = round(model.score(X_train_scaled, y_train), 4)\n",
    "        test_r2 = round(model.score(X_test_scaled, y_test), 4)\n",
    "        print(weights, p, train_r2, test_r2)"
   ],
   "id": "t33-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the weights, p, the training R² and the test R². Both changes help: the weighted mean trusts the closest cars more, and the Manhattan distance (`p=1`) is less dominated by a single large difference. Each alone lifts the test R² from 0.64 to about 0.67 or 0.69; together they reach 0.72. With `weights=\"distance\"` the training R² is almost 1 again: ignore it.\n",
    "\n",
    "### 7.4 Fewer, better features\n",
    "\n",
    "The real problem is the 83 features. Which ones matter for a price? The random forest of Topic 31 found the year, the engine volume, the horsepower and the mileage most important, then a few yes/no columns. Take only these nine:\n",
    "\n",
    "Change it and run: remove `\"body_sedan\"` and `\"fuel_petrol\"` from the list and run."
   ],
   "id": "t33-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = [\"year\", \"engine_l\", \"horsepower\", \"mileage_km\", \"is_new\", \"gearbox_manual\", \"drive_front\", \"fuel_petrol\", \"body_sedan\"]\n",
    "\n",
    "scaler_few = StandardScaler()\n",
    "X_train_few = scaler_few.fit_transform(X_train[columns])\n",
    "X_test_few = scaler_few.transform(X_test[columns])\n",
    "\n",
    "knn_few = KNeighborsRegressor()\n",
    "knn_few.fit(X_train_few, y_train)\n",
    "\n",
    "print(round(knn_few.score(X_test_few, y_test), 4))"
   ],
   "id": "t33-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With nine features instead of 83 the test R² jumps from 0.64 to 0.81, with the same k = 5. The 74 columns that were left out (colours, cities, markets, rare body types, most brands) were noise in every distance: two cars of the same year, engine and mileage looked far apart because one was white and the other black. This is the curse of dimensionality, and on this data it is the most important lesson of the topic. (A real project would choose the features with cross-validation, without the test data; Topic 42 shows tools for it.)\n",
    "\n",
    "### 7.5 k and `weights` on the nine features"
   ],
   "id": "t33-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k in [3, 5, 7, 10, 15]:\n",
    "    model = KNeighborsRegressor(n_neighbors=k, weights=\"distance\")\n",
    "    scores = cross_val_score(model, X_train_few, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))"
   ],
   "id": "t33-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On the nine features, with the weighted mean, k = 7 has the highest cross-validated R².\n",
    "\n",
    "### 7.6 The tuned model\n",
    "\n",
    "Change it and run: change `n_neighbors=7` to `n_neighbors=10` and run."
   ],
   "id": "t33-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned = KNeighborsRegressor(n_neighbors=7, weights=\"distance\")\n",
    "tuned.fit(X_train_few, y_train)\n",
    "\n",
    "tuned_predicted = tuned.predict(X_test_few)\n",
    "\n",
    "print(round(r2_score(y_test, tuned_predicted), 4))\n",
    "print(round(mean_absolute_error(y_test, tuned_predicted)))\n",
    "print(round(root_mean_squared_error(y_test, tuned_predicted)))"
   ],
   "id": "t33-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The tuned model explains 82 percent of the variance of the test prices, with a typical error of about 3,300 manats: much better than the 0.64 and 5,200 of the first model. The random forest of Topic 31 is still a little better (R² 0.865 with its defaults), because trees choose their own features at every split and are not disturbed by useless ones."
   ],
   "id": "t33-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.scatter(y_test, tuned_predicted, s=6, alpha=0.5)\n",
    "plt.plot([0, 160000], [0, 160000], color=\"gray\")\n",
    "plt.xlabel(\"true price (AZN)\")\n",
    "plt.ylabel(\"predicted price (AZN)\")\n",
    "plt.title(\"The tuned model: predicted against true prices\")\n",
    "plt.show()"
   ],
   "id": "t33-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most cars lie close to the grey line of perfect predictions. The expensive cars lie below it: few training cars are as expensive, so their neighbours are cheaper and the mean is too low.\n",
    "\n",
    "### 7.7 The scores of every model"
   ],
   "id": "t33-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = [\n",
    "    (\"k = 5, unscaled\", unscaled, X_test),\n",
    "    (\"k = 5, 83 features\", knn, X_test_scaled),\n",
    "    (\"k = 5, nine features\", knn_few, X_test_few),\n",
    "    (\"k = 7, distance, nine features\", tuned, X_test_few),\n",
    "]\n",
    "\n",
    "for name, model, X_part in models:\n",
    "    model_predicted = model.predict(X_part)\n",
    "    r2 = round(r2_score(y_test, model_predicted), 4)\n",
    "    mae = round(mean_absolute_error(y_test, model_predicted))\n",
    "    print(name, r2, mae)"
   ],
   "id": "t33-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a model, its test R² and its MAE on the same 1,852 cars. Each model gets the test data in the form it was trained on."
   ],
   "id": "t33-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "names = [name for name, model, X_part in models]\n",
    "r2s = [r2_score(y_test, model.predict(X_part)) for name, model, X_part in models]\n",
    "\n",
    "plt.barh(names, r2s)\n",
    "plt.xlim(0, 0.9)\n",
    "plt.xlabel(\"test R²\")\n",
    "plt.title(\"Scaling, the features and k\")\n",
    "plt.show()"
   ],
   "id": "t33-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What the comparison shows:\n",
    "\n",
    "- Without scaling the model is poor.\n",
    "- Scaling helps, but 83 features keep it far from good.\n",
    "- Choosing nine useful features is the largest step; the weighted mean and a tuned k add the last part.\n",
    "\n",
    "## 8. The workflow, step by step\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look | shape, first rows, the meaning of the columns | 10,000 adverts, 19 columns |\n",
    "| 2. Check | missing values, repeated rows | gaps in four columns, 691 copies |\n",
    "| 3. Repeated rows | drop them before the split | a copy would be its own neighbour |\n",
    "| 4. Impossible values | remove them | year 0, three million kilometres |\n",
    "| 5. Too many categories | drop | `model` (797 values) |\n",
    "| 6. Target | its range and outliers | real expensive cars, kept |\n",
    "| 7. Rare categories, missing text | group, fill | brands under 50 cars, market `\"unknown\"` |\n",
    "| 8. Encode | one-hot | 83 features |\n",
    "| 9. Split | training and test data | 7,407 and 1,852 |\n",
    "| 10. Missing numbers | training medians, after the split | horsepower, seats, owners |\n",
    "| 11. Scale | essential for distances | `StandardScaler` |\n",
    "| 12. Model | k-nearest neighbours, k = 5 | R² 0.64 |\n",
    "| 13. Tune | k, `weights`, `p` with cross-validation | R² about 0.72 |\n",
    "| 14. Features | a few useful ones | nine features: R² 0.81 |\n",
    "| 15. Judge | R², MAE, RMSE on the same test data | tuned: R² 0.82, MAE about 3,300 |\n",
    "\n",
    "## 9. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Training on unscaled features. | The mileage decides every distance alone. | `StandardScaler`, fitted on the training data. |\n",
    "| Keeping repeated rows. | A copy in the test data finds itself as its neighbour. | `drop_duplicates()` before the split. |\n",
    "| Using all one-hot columns without thinking. | Useless columns hide the true neighbours. | Choose a few useful features. |\n",
    "| Choosing an odd k \"to avoid ties\". | A mean cannot tie; odd and even k are both fine. | Choose k with cross-validation. |\n",
    "| Trusting a training R² of almost 1. | With k = 1 or weighted means every training car is its own neighbour. | Judge on cross-validation or test data. |\n",
    "| Choosing k with the test data. | The test data then helps to build the model. | Cross-validation on the training data. |\n",
    "| Leaving missing values in. | A distance cannot be computed with a gap. | Fill them, with training values, after the split. |\n",
    "| Expecting predictions above the highest training price. | A prediction is a mean of training prices. | Know the range of the training data. |\n",
    "| Using accuracy or recall for prices. | They are measures for classes. | R², MAE, RMSE. |\n",
    "\n",
    "## 10. Solved problems\n",
    "\n",
    "The first four problems are short and solved by hand. Problems 5 to 16 are one project on `car_prices.csv`, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.\n",
    "\n",
    "Problem 1. The mean of the neighbours\n",
    "\n",
    "A new car has the distances 0.4, 1.3, 0.9, 2.1 and 0.6 to five training cars with the prices 18, 25, 20, 40 and 16 thousand manats. What does k-nearest neighbours predict (a) with k = 1, (b) with k = 3, (c) with k = 5?\n",
    "\n",
    "Idea. Sort by distance, take the k nearest, take the mean of their prices (Part 2).\n",
    "\n",
    "Sorted: 0.4 (18), 0.6 (16), 0.9 (20), 1.3 (25), 2.1 (40).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "k = 3:\\quad & \\frac{18 + 16 + 20}{3} = \\frac{54}{3} = 18 \\\\[8pt]\n",
    "k = 5:\\quad & \\frac{18 + 16 + 20 + 25 + 40}{5} \\\\[4pt]\n",
    "& = \\frac{119}{5} = 23.8\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: (a) 18 thousand, the price of the nearest car. (b) 18 thousand. (c) 23.8 thousand: the far and expensive car pulls the mean up.\n",
    "\n",
    "Problem 2. The weighted mean\n",
    "\n",
    "The three nearest cars have the distances 0.5, 1 and 2 and the prices 20, 30 and 40 thousand manats. Find the prediction with `weights=\"distance\"`.\n",
    "\n",
    "Idea. Each price is weighted by $\\frac{1}{\\text{distance}}$ (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{weights:}\\quad & \\tfrac{1}{0.5} = 2, \\quad \\tfrac{1}{1} = 1, \\quad \\tfrac{1}{2} = 0.5 \\\\[8pt]\n",
    "\\text{prediction} &= \\frac{2 \\times 20 + 1 \\times 30 + 0.5 \\times 40}{2 + 1 + 0.5} \\\\[4pt]\n",
    "&= \\frac{90}{3.5} = 25.714\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the plain mean would be 30 thousand; the weighted mean, 25.714 thousand, is pulled towards the closest car.\n",
    "\n",
    "Problem 3. A very large k\n",
    "\n",
    "A training set has 6,000 cars with a mean price of 23,500 manats. What does k-nearest neighbours predict for every new car with k = 6,000? Is this overfitting or underfitting?\n",
    "\n",
    "Idea. All training cars are neighbours of every new car (Part 2).\n",
    "\n",
    "Why: 23,500 manats for every car, whatever its age or engine: the model no longer looks at the features. That is underfitting, the regression version of \"always the largest class\".\n",
    "\n",
    "Problem 4. Odd or even\n",
    "\n",
    "(a) Can k = 4 give a tie in k-nearest neighbours regression? (b) In classification with two classes? (c) What does `KNeighborsRegressor` have instead of `predict_proba`?\n",
    "\n",
    "Idea. A mean against a vote (Parts 2 and 3).\n",
    "\n",
    "Why: (a) No: the mean of four prices is one number. (b) Yes: two neighbours of each class. (c) Nothing: a regressor predicts a number with `predict`; there are no classes and no probabilities.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of repeated rows and the number of missing values in the whole table.\n",
    "\n",
    "Idea. The first steps of the workflow (Part 5)."
   ],
   "id": "t33-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"car_prices.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.duplicated().sum())\n",
    "print(df.isna().sum().sum())"
   ],
   "id": "t33-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: copies to drop and gaps to fill before any distance can be measured.\n",
    "\n",
    "Problem 6. Copies, impossible rows and the model column\n",
    "\n",
    "Drop the repeated rows, keep only the cars made in 1950 or later with at most 1,000,000 km, and drop the column `model`. Print the shape.\n",
    "\n",
    "Idea. Clean before anything else (Part 5)."
   ],
   "id": "t33-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop_duplicates()\n",
    "df = df[(df[\"year\"] >= 1950) & (df[\"mileage_km\"] <= 1_000_000)]\n",
    "df = df.drop(columns=[\"model\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t33-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 9,259 cars and 18 columns.\n",
    "\n",
    "Problem 7. Categories and encoding\n",
    "\n",
    "Group the brands with fewer than 50 cars as `\"other\"`, fill the missing `market` with `\"unknown\"`, and one-hot encode the eight text columns with `drop_first=True` and `dtype=int`. Print the number of columns.\n",
    "\n",
    "Idea. Text to numbers (Part 5)."
   ],
   "id": "t33-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counts = df[\"brand\"].value_counts()\n",
    "rare = counts[counts < 50].index\n",
    "df.loc[df[\"brand\"].isin(rare), \"brand\"] = \"other\"\n",
    "\n",
    "df[\"market\"] = df[\"market\"].fillna(\"unknown\")\n",
    "\n",
    "text_columns = [\"brand\", \"fuel\", \"gearbox\", \"drive\", \"body\", \"colour\", \"market\", \"city\"]\n",
    "df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))"
   ],
   "id": "t33-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 83 features and the target.\n",
    "\n",
    "Problem 8. Split and fill\n",
    "\n",
    "Make `X` and `y`, split them with `test_size=0.25` and `random_state=7`, and fill `horsepower`, `seats` and `owners` with the training medians. Print the shapes of `X_train` and `X_test`.\n",
    "\n",
    "Idea. The medians come from the training data, after the split (Part 5)."
   ],
   "id": "t33-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"price_azn\"])\n",
    "y = df[\"price_azn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)\n",
    "\n",
    "medians = X_train[[\"horsepower\", \"seats\", \"owners\"]].median()\n",
    "X_train = X_train.fillna(medians)\n",
    "X_test = X_test.fillna(medians)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t33-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 6,944 cars to search for neighbours and 2,315 to judge with.\n",
    "\n",
    "Problem 9. Scale\n",
    "\n",
    "Fit a `StandardScaler` on the training data and scale both parts. Print the shape of the scaled training data.\n",
    "\n",
    "Idea. Fit on training, transform both (Part 5)."
   ],
   "id": "t33-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(X_train_scaled.shape)"
   ],
   "id": "t33-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the same 83 columns, now each with the mean 0 and the standard deviation 1 on the training cars.\n",
    "\n",
    "Problem 10. The default model\n",
    "\n",
    "Train a `KNeighborsRegressor` with its default settings on the scaled data. Print its training R² and its test R², rounded to 4 decimals.\n",
    "\n",
    "Idea. k = 5 (Part 6)."
   ],
   "id": "t33-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "\n",
    "knn = KNeighborsRegressor()\n",
    "knn.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(knn.score(X_train_scaled, y_train), 4))\n",
    "print(round(knn.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t33-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a clear gap between training and test, and a test R² far below the random forest.\n",
    "\n",
    "Problem 11. Its errors in manats\n",
    "\n",
    "Print the MAE and the RMSE of the model on the test data, as whole numbers.\n",
    "\n",
    "Idea. The measures of regression (Topic 22)."
   ],
   "id": "t33-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error\n",
    "\n",
    "predicted = knn.predict(X_test_scaled)\n",
    "\n",
    "print(round(mean_absolute_error(y_test, predicted)))\n",
    "print(round(root_mean_squared_error(y_test, predicted)))"
   ],
   "id": "t33-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a typical error of over 5,000 manats.\n",
    "\n",
    "Problem 12. The neighbours of one car\n",
    "\n",
    "For the first test car, print the prices of its 5 nearest training cars as a list, then the prediction.\n",
    "\n",
    "Idea. The prediction is the mean of these prices (Part 6)."
   ],
   "id": "t33-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "car = X_test_scaled[[0]]\n",
    "\n",
    "distances, positions = knn.kneighbors(car)\n",
    "\n",
    "print(y_train.iloc[positions[0]].tolist())\n",
    "print(knn.predict(car))"
   ],
   "id": "t33-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the mean of the five prices is the second line.\n",
    "\n",
    "Problem 13. k with cross-validation\n",
    "\n",
    "For k = 3, 5 and 10, print k and the mean R² of a 5-fold cross-validation on the scaled training data, rounded to 4 decimals.\n",
    "\n",
    "Idea. The test data does not choose k (Part 7)."
   ],
   "id": "t33-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for k in [3, 5, 10]:\n",
    "    scores = cross_val_score(KNeighborsRegressor(n_neighbors=k), X_train_scaled, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))"
   ],
   "id": "t33-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: k = 5 is the best of the three; an even k is as possible as an odd one.\n",
    "\n",
    "Problem 14. Nine features\n",
    "\n",
    "Scale only the nine features `year`, `engine_l`, `horsepower`, `mileage_km`, `is_new`, `gearbox_manual`, `drive_front`, `fuel_petrol` and `body_sedan` with a new `StandardScaler`, train a default `KNeighborsRegressor` on them, and print its test R², rounded to 4 decimals.\n",
    "\n",
    "Idea. Fewer, useful features against the curse of dimensionality (Part 7)."
   ],
   "id": "t33-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = [\"year\", \"engine_l\", \"horsepower\", \"mileage_km\", \"is_new\", \"gearbox_manual\", \"drive_front\", \"fuel_petrol\", \"body_sedan\"]\n",
    "\n",
    "scaler_few = StandardScaler()\n",
    "X_train_few = scaler_few.fit_transform(X_train[columns])\n",
    "X_test_few = scaler_few.transform(X_test[columns])\n",
    "\n",
    "knn_few = KNeighborsRegressor()\n",
    "knn_few.fit(X_train_few, y_train)\n",
    "\n",
    "print(round(knn_few.score(X_test_few, y_test), 4))"
   ],
   "id": "t33-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: far better than with 83 features, with the same k.\n",
    "\n",
    "Problem 15. The tuned model\n",
    "\n",
    "Train a model with k = 7 and `weights=\"distance\"` on the nine features. Print its test R², its MAE and its RMSE, the last two as whole numbers.\n",
    "\n",
    "Idea. The settings chosen in the lesson (Part 7)."
   ],
   "id": "t33-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tuned = KNeighborsRegressor(n_neighbors=7, weights=\"distance\")\n",
    "tuned.fit(X_train_few, y_train)\n",
    "\n",
    "tuned_predicted = tuned.predict(X_test_few)\n",
    "\n",
    "print(round(r2_score(y_test, tuned_predicted), 4))\n",
    "print(round(mean_absolute_error(y_test, tuned_predicted)))\n",
    "print(round(root_mean_squared_error(y_test, tuned_predicted)))"
   ],
   "id": "t33-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the best of the project on this split too.\n",
    "\n",
    "Problem 16. Scaled against unscaled\n",
    "\n",
    "Train a default `KNeighborsRegressor` on the unscaled nine features. Print its test R² and the test R² of `knn_few`, rounded to 4 decimals.\n",
    "\n",
    "Idea. Scaling matters even with few features (Part 4)."
   ],
   "id": "t33-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = KNeighborsRegressor()\n",
    "raw.fit(X_train[columns], y_train)\n",
    "\n",
    "print(round(raw.score(X_test[columns], y_test), 4))\n",
    "print(round(knn_few.score(X_test_few, y_test), 4))"
   ],
   "id": "t33-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: without scaling the mileage decides alone, even among nine features.\n",
    "\n",
    "## 13. Summary\n",
    "\n",
    "|  | Formula or rule | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Prediction | the mean of the k nearest training values | no vote, no probability |\n",
    "| Weighted prediction | $\\frac{w_1 y_1 + w_2 y_2 + \\dots}{w_1 + w_2 + \\dots}$ with $w = \\frac{1}{\\text{distance}}$ | close neighbours count more |\n",
    "| Small k | low bias, high variance | k = 1 copies one training row |\n",
    "| Large k | high bias, low variance | k = n predicts the mean of all training values |\n",
    "| Odd or even k | both are fine | a mean cannot tie |\n",
    "| Range | between the smallest and the largest training value | no extrapolation |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `KNeighborsRegressor(n_neighbors=7, weights=\"distance\")` | the weighted mean of the 7 nearest values |\n",
    "| `knn.kneighbors(row)` | the distances and positions of the k nearest training rows |\n",
    "| `knn.score(X_test, y_test)` | the test R² |\n",
    "| `r2_score`, `mean_absolute_error`, `root_mean_squared_error` | the measures of regression |\n",
    "| `cross_val_score(knn, X_train_scaled, y_train, cv=5)` | k chosen with the R² of five folds |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. k-nearest neighbours regression predicts the mean (or weighted mean) of the k nearest training values.\n",
    "2. Always scale; drop repeated rows before the split; fill missing values after it with training values.\n",
    "3. Choose a few useful features: with many one-hot columns the true neighbours disappear.\n",
    "4. Choose k with cross-validation; even and odd k are both fine for regression.\n",
    "5. Judge with R², MAE and RMSE on the test data; a training R² near 1 means nothing for this model.\n",
    "6. Predictions stay inside the range of the training values.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "Topic 34 brings Naive Bayes, a classifier that measures no distances at all: it calculates probabilities with Bayes' rule (Topic 16), feature by feature.\n",
    "\n",
    "Next: the practice notebook (topic-33-practice.ipynb), then Topic 34: Naive Bayes."
   ],
   "id": "t33-083"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
