{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 32: k-Nearest Neighbors - Classification\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 16, Thursday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. A cell that draws a chart shows it under the cell when you run it. The practice problems are in a separate notebook, topic-32-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 6 to 8 are one project that starts from the raw file, so start at the first cell of Part 6. The solved problems 5 to 16 are a second project that starts again from reading the file. Cells that try many values of k take a few seconds.\n",
    "\n",
    "This notebook reads the file Bank Customer Churn Prediction.csv. Put the file into the same folder as the notebook. On the Asiman Data School website the file is already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. What k-nearest neighbours is\n",
    "2. How it decides: an example with eight customers\n",
    "3. How the distance is measured\n",
    "4. The hyperparameters, and how to choose k\n",
    "5. Preprocessing for k-nearest neighbours, and for the models still to come\n",
    "6. The project: from the file to the scaled data\n",
    "7. The model\n",
    "8. Choosing k and the other hyperparameters\n",
    "9. The workflow, step by step\n",
    "10. Common mistakes\n",
    "11. Solved problems\n",
    "12. Practice (in topic-32-practice.ipynb)\n",
    "13. Check yourself (on the website)\n",
    "14. Summary"
   ],
   "id": "t32-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: tell me who your neighbours are\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, k-nearest neighbours keeps the training rows and predicts the class that most of the k nearest rows have; the share of their votes is its probability. Second, everything depends on the distance, so the features must be scaled, or the feature with the largest numbers decides alone. Third, k is the main decision: $k = 1$ memorises the training data, a very large k sees only the largest class, and an odd k avoids ties; cross-validation chooses it. Fourth, the preprocessing matters more than for any model so far: one-hot encoding, filled gaps, a look at outliers, and no useless features. Fifth, the measures of Topic 28 judge it, and a lower threshold raises its recall.\n",
    "\n",
    "The hyperparameters, the distances and the speed of the search are told around these five ideas.\n",
    "\n",
    "The twelfth lesson of Module 3. The models so far learned something from the training data: linear and logistic regression learned weights, a decision tree learned questions, a forest learned many trees. k-nearest neighbours learns nothing at all. It keeps the training data, and when a new customer comes, it looks for the customers who are most similar to him and lets them decide. \"Tell me who your neighbours are, and I will tell you who you are.\"\n",
    "\n",
    "This is one of the simplest ideas in machine learning, and it works surprisingly well when the data is prepared for it. It is also the first model of the course that is built on distances, so it shows more clearly than any model before why the features must be scaled.\n",
    "\n",
    "The lesson has two steps. On paper: what k-nearest neighbours is and where it is used, how it decides for a new customer (worked by hand with eight customers), how it measures distances, its hyperparameters, how to choose k (and why an odd k), and what preprocessing it needs. Then the project on `Bank Customer Churn Prediction.csv`, the file of Topics 27 to 30: data import, preprocessing, the model, its measures, the choice of k, and the other hyperparameters.\n",
    "\n",
    "You need: the distance between two points and the vector norms (Topics 13 and 15), the standard deviation (Topic 18), the train/test split, cross-validation and overfitting (Topic 23), scaling and encoding (Topics 24 and 25), and the measures of Topic 28.\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| k-nearest neighbours (kNN) | a model that predicts the class of a new row from the classes of the k most similar training rows |\n",
    "| Neighbour | a training row that is close to the new row |\n",
    "| k | how many neighbours vote: the main hyperparameter |\n",
    "| Distance | a number that says how different two rows are; small means similar |\n",
    "| Euclidean distance | the straight-line distance (Topic 13) |\n",
    "| Manhattan distance | the sum of the differences along each feature, like walking along the streets of a city grid |\n",
    "| Majority vote | the class that most of the k neighbours have |\n",
    "| Lazy learner | a model that does no work when it is trained and all the work when it predicts |\n",
    "| Curse of dimensionality | with many features, all rows become almost equally far apart, and \"nearest\" loses its meaning |\n",
    "\n",
    "## 1. What k-nearest neighbours is\n",
    "\n",
    "### 1.1 The idea\n",
    "\n",
    "A bank wants to know whether a new customer will leave. It does not have a formula. But it has 8,000 customers whose story it knows. So it asks: which known customers are most like this one? If most of the five customers most similar to him left the bank, he will probably leave too.\n",
    "\n",
    "That is the whole algorithm:\n",
    "\n",
    "1. Keep all the training rows.\n",
    "2. For a new row, measure its distance to every training row.\n",
    "3. Take the k rows with the smallest distances: the k nearest neighbours.\n",
    "4. Predict the class that most of them have.\n",
    "\n",
    "### 1.2 A lazy learner\n",
    "\n",
    "Every model so far did its work in `fit`: logistic regression searched for weights, a tree searched for questions. k-nearest neighbours does almost nothing in `fit`. It only stores the training data (in a structure that makes the search faster later). All the work happens in `predict`: for every new row, the distances to all stored rows are measured. Such a model is called a lazy learner (or instance-based learner): it learns no rule, it remembers examples.\n",
    "\n",
    "This has two consequences:\n",
    "\n",
    "- Training is instant, but predicting is slow when the training data is large: every prediction looks at all the stored rows.\n",
    "- There are no weights or questions to read: the model explains a prediction by its neighbours (\"these five customers are most like him, and four of them left\").\n",
    "\n",
    "### 1.3 Where k-nearest neighbours is used\n",
    "\n",
    "- Recommendations: \"customers who are similar to you bought...\", films that people with similar tastes liked.\n",
    "- Banking and insurance: churn and credit risk, by comparing a customer with similar customers (the project of this lesson).\n",
    "- Medicine: finding the patients most similar to a new patient, and what their diagnosis was.\n",
    "- Recognising images and handwriting: a new picture of a digit gets the label of the most similar stored pictures.\n",
    "- Finding unusual rows: a row whose nearest neighbours are all far away is an outlier (fraud, a broken sensor).\n",
    "- Filling missing values: `KNNImputer` fills a gap with the values of the most similar rows.\n",
    "- As a simple baseline: a quick first model to compare the others with.\n",
    "\n",
    "### 1.4 Strengths and weaknesses\n",
    "\n",
    "| Strengths | Weaknesses |\n",
    "| --- | --- |\n",
    "| Very simple to understand and to explain | Slow predictions on large data: every prediction measures all distances |\n",
    "| No training time | Needs the whole training data in memory |\n",
    "| No assumption about the shape of the classes: the border between them can have any form | Needs scaled features, or one feature decides the distances alone |\n",
    "| Works for any number of classes | Useless features and many features spoil the distances (the curse of dimensionality) |\n",
    "| The same idea also predicts numbers (Topic 33) | Sensitive to outliers, and it cannot work with missing values |\n",
    "\n",
    "## 2. How it decides: an example with eight customers\n",
    "\n",
    "Eight customers of a bank, described by two features: how many years they have been customers (`tenure`) and how many products they use (`products_number`). Four of them left the bank.\n",
    "\n",
    "| Customer | Tenure (years) | Products | Left the bank? |\n",
    "| --- | --- | --- | --- |\n",
    "| A | 4 | 3 | leaves |\n",
    "| B | 2 | 2 | stays |\n",
    "| C | 5 | 1 | stays |\n",
    "| D | 6 | 3 | stays |\n",
    "| E | 1 | 1 | leaves |\n",
    "| F | 7 | 4 | leaves |\n",
    "| G | 8 | 1 | stays |\n",
    "| H | 2 | 4 | leaves |\n",
    "\n",
    "A new customer N has been a customer for 4 years and uses 2 products. Will he leave?\n",
    "\n",
    "### 2.1 Step 1: the distances\n",
    "\n",
    "The Euclidean distance between two customers is the straight-line distance of Topic 13: the square root of the sum of the squared differences of the features. For N = (4, 2) and A = (4, 3):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{distance}(N, A) \\\\[4pt]\n",
    "&= \\sqrt{(4 - 4)^2 + (2 - 3)^2} \\\\[4pt]\n",
    "&= \\sqrt{0 + 1} = \\sqrt{1} = 1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For N and C = (5, 1):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{distance}(N, C) \\\\[4pt]\n",
    "&= \\sqrt{(4 - 5)^2 + (2 - 1)^2} \\\\[4pt]\n",
    "&= \\sqrt{1 + 1} = \\sqrt{2} = 1.414\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The same for all eight customers, sorted from the nearest to the farthest:\n",
    "\n",
    "| Rank | Customer | Differences | Distance | Left the bank? |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| 1 | A | 0 and 1 | $\\sqrt{1} = 1$ | leaves |\n",
    "| 2 | C | 1 and 1 | $\\sqrt{2} = 1.414$ | stays |\n",
    "| 3 | B | 2 and 0 | $\\sqrt{4} = 2$ | stays |\n",
    "| 4 | D | 2 and 1 | $\\sqrt{5} = 2.236$ | stays |\n",
    "| 5 | H | 2 and 2 | $\\sqrt{8} = 2.828$ | leaves |\n",
    "| 6 | E | 3 and 1 | $\\sqrt{10} = 3.162$ | leaves |\n",
    "| 7 | F | 3 and 2 | $\\sqrt{13} = 3.606$ | leaves |\n",
    "| 8 | G | 4 and 1 | $\\sqrt{17} = 4.123$ | stays |\n",
    "\n",
    "The picture is on the lesson page: the eight customers as points (tenure against products), orange for those who left, teal for those who stayed, the new customer N at (4, 2), and two circles around N: the one through B holds the 3 nearest, the one through F the 7 nearest.\n",
    "\n",
    "### 2.2 Step 2: the vote of the k nearest\n",
    "\n",
    "The prediction depends on how many neighbours vote:\n",
    "\n",
    "| k | The k nearest | Leave | Stay | Share that left | Prediction |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| 1 | A | 1 | 0 | $\\frac{1}{1} = 1$ | leaves |\n",
    "| 3 | A, C, B | 1 | 2 | $\\frac{1}{3} = 0.333$ | stays |\n",
    "| 5 | A, C, B, D, H | 2 | 3 | $\\frac{2}{5} = 0.4$ | stays |\n",
    "| 7 | A, C, B, D, H, E, F | 4 | 3 | $\\frac{4}{7} = 0.571$ | leaves |\n",
    "| 8 | all eight | 4 | 4 | $\\frac{4}{8} = 0.5$ | a tie |\n",
    "\n",
    "Four lessons are in this table:\n",
    "\n",
    "- The answer depends on k. With one neighbour N leaves, with three or five he stays, with seven he leaves again. Choosing k is the main decision of this model (Part 4).\n",
    "- k = 1 trusts a single customer. If A is an unusual customer, N gets A's unusual answer. A small k follows every accident of the training data: it overfits.\n",
    "- The share of the votes is the probability. scikit-learn's `predict_proba` gives exactly this share: for k = 5 the probability of leaving is 0.4, so the model predicts \"stays\".\n",
    "- An even k can tie. With k = 8, four neighbours say \"leaves\" and four say \"stays\". The model has no majority and must break the tie by a rule that has nothing to do with the data (scikit-learn takes the class that comes first, here \"stays\"). With two classes an odd k never ties.\n",
    "\n",
    "With three or more classes the vote works in the same way: the class with the most votes wins, and `predict_proba` gives a share for every class. A second kind of tie can happen too: two training rows at exactly the same distance at the edge of the k nearest. scikit-learn then takes the row that comes first in the training data.\n",
    "\n",
    "### 2.3 Weighted votes\n",
    "\n",
    "In the vote above, A counts as much as F, although A is three and a half times closer. With `weights=\"distance\"` every neighbour votes with the weight $\\frac{1}{\\text{distance}}$, so close neighbours count more. For k = 3:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{leaves:}\\quad & A:\\ \\tfrac{1}{1} = 1 \\\\[8pt]\n",
    "\\text{stays:}\\quad & C:\\ \\tfrac{1}{1.414} = 0.707, \\quad B:\\ \\tfrac{1}{2} = 0.5 \\\\[4pt]\n",
    "& \\text{together } 0.707 + 0.5 = 1.207\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "1.207 is more than 1: N still stays, but closer than in the plain vote (one against two).\n",
    "\n",
    "## 3. How the distance is measured\n",
    "\n",
    "### 3.1 Euclidean, Manhattan, Minkowski\n",
    "\n",
    "For two rows with the features $x_1, x_2, \\dots$ and $y_1, y_2, \\dots$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{Euclidean distance} \\\\[4pt]\n",
    "&= \\sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2 + \\dots}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{Manhattan distance} \\\\[4pt]\n",
    "&= |x_1 - y_1| + |x_2 - y_2| + \\dots\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The Euclidean distance is the straight line, the Manhattan distance the way along the streets of a grid city, where you can only walk along the features one after another. For N = (4, 2) and D = (6, 3):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Euclidean:}\\quad & \\sqrt{2^2 + 1^2} = \\sqrt{5} = 2.236 \\\\[6pt]\n",
    "\\text{Manhattan:}\\quad & 2 + 1 = 3\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Both are members of one family, the Minkowski distance with a power p:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{Minkowski distance} \\\\[4pt]\n",
    "&= \\left(|x_1 - y_1|^p + |x_2 - y_2|^p + \\dots\\right)^{1/p}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$p = 1$ gives the Manhattan distance, $p = 2$ the Euclidean distance. In scikit-learn the default is `metric=\"minkowski\"` with `p=2`: the Euclidean distance. Topic 15 met the same pair as the L1 and the L2 norm of the difference vector.\n",
    "\n",
    "The picture is on the lesson page: from N = (4, 2) to D = (6, 3), the straight Euclidean line of length 2.236 and the Manhattan path along the grid, 2 to the right and 1 up, of length 3.\n",
    "\n",
    "### 3.2 Why scaling is essential\n",
    "\n",
    "The eight customers had two features with similar ranges. Real features do not. In the bank data the age lies between 18 and 92, the balance between 0 and 250,898 euros. Take a new customer N, 40 years old with a balance of 50,000 euros, and two known customers:\n",
    "\n",
    "| Customer | Age | Balance (euros) |\n",
    "| --- | --- | --- |\n",
    "| N | 40 | 50,000 |\n",
    "| P | 41 | 120,000 |\n",
    "| Q | 60 | 52,000 |\n",
    "\n",
    "Without scaling:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{distance}(N, P) &= \\sqrt{1^2 + 70{,}000^2} = 70{,}000.0 \\\\[6pt]\n",
    "\\text{distance}(N, Q) &= \\sqrt{20^2 + 2{,}000^2} = 2{,}000.1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Q is \"much nearer\", although he is 20 years older. The balance is counted in tens of thousands and the age in tens, so the balance decides the distance alone: the age might as well not exist.\n",
    "\n",
    "Now divide each difference by the typical spread of its feature, about 10 years for the age and about 60,000 euros for the balance (their standard deviations in the bank data, Topic 18). This is what `StandardScaler` does (Topic 24):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{distance}(N, P) \\\\[4pt]\n",
    "&= \\sqrt{\\left(\\tfrac{1}{10}\\right)^2 + \\left(\\tfrac{70{,}000}{60{,}000}\\right)^2} \\\\[4pt]\n",
    "&= \\sqrt{0.01 + 1.362} = \\sqrt{1.372} = 1.171\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{distance}(N, Q) \\\\[4pt]\n",
    "&= \\sqrt{\\left(\\tfrac{20}{10}\\right)^2 + \\left(\\tfrac{2{,}000}{60{,}000}\\right)^2} \\\\[4pt]\n",
    "&= \\sqrt{4 + 0.001} = \\sqrt{4.001} = 2.000\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "After scaling, P is nearer: both features count, each in units of its own spread. The project shows what this does to the scores on the real data (Part 7).\n",
    "\n",
    "Rule: k-nearest neighbours always needs scaled features. `StandardScaler` is the usual choice; `MinMaxScaler` also works, and the project compares the two.\n",
    "\n",
    "## 4. The hyperparameters, and how to choose k\n",
    "\n",
    "### 4.1 The hyperparameters of `KNeighborsClassifier`\n",
    "\n",
    "| Hyperparameter | Default | Role |\n",
    "| --- | --- | --- |\n",
    "| `n_neighbors` | `5` | k, the number of neighbours that vote. Small k: a wiggly border that follows single customers (overfitting). Large k: a smooth border that ignores small groups (underfitting). |\n",
    "| `weights` | `\"uniform\"` | `\"uniform\"`: every neighbour has one vote. `\"distance\"`: a vote counts $\\frac{1}{\\text{distance}}$, so close neighbours count more. |\n",
    "| `metric` | `\"minkowski\"` | how the distance is measured; `\"euclidean\"` and `\"manhattan\"` can also be named directly |\n",
    "| `p` | `2` | the power of the Minkowski distance: 2 is Euclidean, 1 is Manhattan |\n",
    "| `algorithm` | `\"auto\"` | how the neighbours are searched: `\"brute\"` (measure every distance), `\"kd_tree\"` or `\"ball_tree\"` (tree structures that skip far rows). The answer is the same; only the speed differs. `\"auto\"` chooses. |\n",
    "| `leaf_size` | `30` | a setting of the two tree structures: speed and memory only |\n",
    "| `n_jobs` | `None` | how many processor cores search at the same time; `-1` uses all |\n",
    "\n",
    "There is no `random_state`: nothing in k-nearest neighbours is random. And there is no `class_weight`: for unbalanced classes the threshold of the probability is moved instead (Part 8, as in Topic 28).\n",
    "\n",
    "### 4.2 How the neighbours are found\n",
    "\n",
    "To predict the 2,000 test customers of the project, the plain way measures the distance from each of them to each of the 8,000 training customers:\n",
    "\n",
    "$$\n",
    "2{,}000 \\times 8{,}000 = 16{,}000{,}000 \\text{ distances}\n",
    "$$\n",
    "\n",
    "`algorithm=\"brute\"` does exactly this. `\"kd_tree\"` and `\"ball_tree\"` first sort the training rows into a tree of regions (this is the small amount of work `fit` does), so that the search can skip whole regions that are far away from the new row. With few features they are much faster; with many features they lose their advantage. `\"auto\"` chooses for you. All of them find the same neighbours: the choice changes the speed, never the prediction.\n",
    "\n",
    "### 4.3 Small k, large k: overfitting and underfitting\n",
    "\n",
    "- k = 1: each training customer is its own nearest neighbour, so the model is right for every training customer: a training accuracy of 1.0. On new customers it copies the class of one single customer, including every accident and every mislabelled row. That is overfitting (Topic 23): low bias, high variance.\n",
    "- Larger k: the vote averages more customers, the border between the classes becomes smoother, and single accidents no longer decide. The variance falls.\n",
    "- Very large k: the vote averages so many customers that it no longer sees small groups. In the extreme, k = the number of training rows, every new customer gets the same answer: the largest class (80 percent stay, so \"stays\"). That is underfitting: high bias.\n",
    "\n",
    "The picture is on the lesson page: 500 bank customers by their scaled age and balance, with the areas where the model predicts \"leaves\". With k = 1 the border wraps around single customers in small islands; with k = 31 it is smooth, and \"leaves\" covers mainly the older customers.\n",
    "\n",
    "The picture uses only two features of 500 bank customers. Orange areas are where the model predicts \"leaves\". With k = 1 the border wraps around single customers: islands of orange inside the teal. With k = 31 it is smooth: the model predicts \"leaves\" only where leavers really are the majority, among the older customers.\n",
    "\n",
    "### 4.4 How to choose k\n",
    "\n",
    "1. Odd k for two classes. With two classes an odd k can never tie. (With three classes ties can still happen; then `weights=\"distance\"` helps.)\n",
    "2. A first guess: a common rule of thumb is $k \\approx \\sqrt{n}$, the square root of the number of training rows. For 8,000 rows: $\\sqrt{8{,}000} = 89.4$. It is only a starting point: on the bank data a smaller k is better.\n",
    "3. Cross-validation (Topic 23): try several odd values of k on the training data, keep the one with the best mean score over the folds. Never choose k with the test data.\n",
    "4. Look at both scores: a training score far above the cross-validated score means a k that is too small.\n",
    "\n",
    "Searching several hyperparameters at once (k, `weights` and `p` together) is the subject of Topic 42.\n",
    "\n",
    "## 5. Preprocessing for k-nearest neighbours, and for the models still to come\n",
    "\n",
    "k-nearest neighbours is the model that needs the most careful preprocessing so far, because everything it does is measuring distances.\n",
    "\n",
    "- Scaling: essential. Without it the feature with the largest numbers decides alone (Part 3). The scaler is fitted on the training data only and then applied to the test data (Topic 24).\n",
    "- Encoding: needed, and it changes distances. Text must become numbers. One-hot encoding is the safe choice for categories without an order: every two different countries are then equally far apart. Numbers for categories (France 0, Germany 1, Spain 2) would make France and Spain \"farther apart\" than France and Germany, which means nothing.\n",
    "- Outliers in the features: they matter. An extreme value stretches the scale of its feature and can make one customer far from everybody. Look at them; real values stay, mistakes are corrected or removed (Topic 25).\n",
    "- Missing values: must be filled. A distance cannot be computed with a gap. Fill them before (Topic 11), or use `KNNImputer`, which fills a gap with the mean of the nearest rows.\n",
    "- Useless features: they hurt. Every feature adds to the distance. A feature that says nothing about the target (an estimated salary, a customer number) adds noise to every distance and makes the true neighbours harder to find. With many features all distances become alike: the curse of dimensionality. Choosing fewer, useful features helps this model more than most (Part 8).\n",
    "- Unbalanced classes: there is no `class_weight`. The probability threshold can be lowered (Topic 28); Topic 41 goes further.\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; one-hot for categories | 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 scaler and the model into one object, so that the scaler is always fitted on the right rows.\n",
    "\n",
    "## 6. The project: from the file to the scaled data\n",
    "\n",
    "Now the data: `Bank Customer Churn Prediction.csv`, 10,000 customers of a bank, and the column `churn` says who left (1) and who stayed (0).\n",
    "\n",
    "Every step is done again and explained as if it were new, so that the whole workflow is in one place. The cells continue from each other like the cells of a notebook.\n",
    "\n",
    "### 6.1 Step 1: read and look"
   ],
   "id": "t32-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head())"
   ],
   "id": "t32-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10,000 rows and 12 columns: an identification number, ten features (credit score, country, gender, age, years as a customer, balance, number of products, credit card, active membership, estimated salary) and the target `churn`.\n",
    "\n",
    "### 6.2 Step 2: check"
   ],
   "id": "t32-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())\n",
    "print(df.dtypes)"
   ],
   "id": "t32-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No missing values (k-nearest neighbours could not work with them), no repeated rows, and two text columns: `country` and `gender`.\n",
    "\n",
    "### 6.3 Step 3: drop what carries no information"
   ],
   "id": "t32-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t32-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An identification number says nothing about a customer. For k-nearest neighbours it would be worse than useless: it would be a feature in every distance, and customers with close numbers would count as \"similar\".\n",
    "\n",
    "### 6.4 Step 4: the target"
   ],
   "id": "t32-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"churn\"].value_counts())\n",
    "print(round(df[\"churn\"].mean(), 4))"
   ],
   "id": "t32-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "About 20 percent of the customers left: the classes are unbalanced. A model that always says \"stays\" is right 80 percent of the time, so the accuracy alone will not be enough: the measures of Topic 28 judge the models.\n",
    "\n",
    "### 6.5 Step 5: outliers"
   ],
   "id": "t32-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "q1 = df[\"age\"].quantile(0.25)\n",
    "q3 = df[\"age\"].quantile(0.75)\n",
    "upper = q3 + 1.5 * (q3 - q1)\n",
    "\n",
    "print(upper)\n",
    "print((df[\"age\"] > upper).sum())"
   ],
   "id": "t32-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "359 customers are older than the upper limit of the IQR rule (Topic 25). They are real customers, not mistakes, so they stay. For k-nearest neighbours they are a little more important than for a tree: a customer of 85 is far from almost everybody, and his neighbours are the few other old customers. That is right, as long as the age is scaled like every other feature.\n",
    "\n",
    "### 6.6 Step 6: encode"
   ],
   "id": "t32-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist())"
   ],
   "id": "t32-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`gender` becomes 0 and 1. `country` gets one-hot encoding, so every two countries are equally far apart. `products_number` stays a number: 1, 2, 3 and 4 products have a real order, and a customer with 2 products is closer to one with 3 than to one with 1.\n",
    "\n",
    "### 6.7 Step 7: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 3,000 customers become test data."
   ],
   "id": "t32-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t32-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "8,000 customers for training (the neighbours that will be searched) and 2,000 for the test, the same customers as in Topics 27 to 30.\n",
    "\n",
    "### 6.8 Step 8: scale"
   ],
   "id": "t32-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(X_train[[\"age\", \"balance\"]].std().round(1))"
   ],
   "id": "t32-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The balance spreads about 6,000 times more than the age. Without scaling, the balance would decide every distance alone (Part 3)."
   ],
   "id": "t32-017"
  },
  {
   "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)\n",
    "print(X_train_scaled[:3].round(2))"
   ],
   "id": "t32-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fit_transform` learns the mean and the standard deviation of every feature from the training customers and scales them; `transform` scales the test customers with the same numbers, so the test data does not help to build the model (Topic 24). Every feature now has a mean of 0 and a standard deviation of 1 on the training data, and one unit means \"one typical spread\" for every feature. The result is a NumPy array without column names.\n",
    "\n",
    "## 7. The model\n",
    "\n",
    "### 7.1 Train and judge\n",
    "\n",
    "Change it and run: write `KNeighborsClassifier(n_neighbors=1)` and run: the training accuracy becomes 1.0."
   ],
   "id": "t32-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn = KNeighborsClassifier()\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": "t32-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`KNeighborsClassifier` lives in `sklearn.neighbors`. With its default k = 5 it reaches an accuracy of about 0.87 on the training customers and 0.83 on the test customers. `fit` took almost no time: it only stored the 8,000 scaled training customers.\n",
    "\n",
    "### 7.2 How it decides for one customer\n",
    "\n",
    "Change it and run: change both `10` to `11` and look at the neighbours of another customer."
   ],
   "id": "t32-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer = X_test_scaled[[10]]\n",
    "\n",
    "distances, positions = knn.kneighbors(customer)\n",
    "\n",
    "print(distances.round(3))\n",
    "print(y_train.iloc[positions[0]].tolist())\n",
    "print(knn.predict_proba(customer))\n",
    "print(knn.predict(customer))\n",
    "print(y_test.iloc[10])"
   ],
   "id": "t32-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`kneighbors` returns the distances of the 5 nearest training customers and their positions in the training data. Two of the five left (the 1s), three stayed. `predict_proba` is exactly this share: 0.4 for leaving, 0.6 for staying, and the model predicts 0, \"stays\". But this customer really left: a miss, the kind of mistake the recall of Topic 28 counts.\n",
    "\n",
    "### 7.3 The measures of Topic 28"
   ],
   "id": "t32-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "predicted = knn.predict(X_test_scaled)\n",
    "leaving = knn.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))\n",
    "print(round(roc_auc_score(y_test, leaving), 4))"
   ],
   "id": "t32-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model finds only about 37 percent of the leaving customers (the recall), with a precision of about 0.61. Its AUC of 0.76 shows that the shares of the votes rank the customers moderately well. With k = 5 a probability can only be 0, 0.2, 0.4, 0.6, 0.8 or 1, so the ranking is coarse.\n",
    "\n",
    "### 7.4 Without scaling\n",
    "\n",
    "What would have happened without Step 8?"
   ],
   "id": "t32-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "unscaled = KNeighborsClassifier()\n",
    "unscaled.fit(X_train, y_train)\n",
    "\n",
    "print(round(unscaled.score(X_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, unscaled.predict_proba(X_test)[:, 1]), 4))"
   ],
   "id": "t32-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same model on the unscaled features: an accuracy of 0.764, below the 0.80 of always saying \"stays\", and an AUC of 0.54, hardly better than guessing (0.5). The neighbours were chosen by the balance and the estimated salary alone, which say little about leaving. Scaling raised the AUC from 0.54 to 0.76: for this model scaling is not a detail, it is the difference between a useless and a useful model.\n",
    "\n",
    "### 7.5 Another scaler: `MinMaxScaler`\n",
    "\n",
    "Part 3 said that `MinMaxScaler` (Topic 24) also works. It moves every feature into the range from 0 to 1 instead of giving it a mean of 0 and a standard deviation of 1:"
   ],
   "id": "t32-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "minmax = MinMaxScaler()\n",
    "X_train_minmax = minmax.fit_transform(X_train)\n",
    "X_test_minmax = minmax.transform(X_test)\n",
    "\n",
    "knn_minmax = KNeighborsClassifier()\n",
    "knn_minmax.fit(X_train_minmax, y_train)\n",
    "\n",
    "print(round(knn_minmax.score(X_test_minmax, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, knn_minmax.predict_proba(X_test_minmax)[:, 1]), 4))"
   ],
   "id": "t32-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Far better than no scaling, but a little below `StandardScaler` here. With min-max scaling the yes/no columns (gender, active member, the countries) keep their full range from 0 to 1, while the age is squeezed: most customers are between 25 and 50, a small part of the range from 18 to 92. So the yes/no columns weigh more in the distances than with the standard scaler. Which scaler is better depends on the data; compare them, as here, and keep the better one.\n",
    "\n",
    "## 8. Choosing k and the other hyperparameters\n",
    "\n",
    "### 8.1 k from 1 to 51\n",
    "\n",
    "Change it and run: add `101` and `301` to the list and run: very large k underfit."
   ],
   "id": "t32-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k in [1, 3, 5, 7, 11, 15, 21, 31, 51]:\n",
    "    model = KNeighborsClassifier(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    train_acc = round(model.score(X_train_scaled, y_train), 4)\n",
    "    test_acc = round(model.score(X_test_scaled, y_test), 4)\n",
    "    print(k, train_acc, test_acc)"
   ],
   "id": "t32-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows k, the training accuracy and the test accuracy.\n",
    "\n",
    "- k = 1 is right for every training customer (1.0) and the worst on the test customers (0.802): overfitting, exactly as in Part 4.\n",
    "- As k grows, the training accuracy falls and the test accuracy rises: the gap closes.\n",
    "- From about k = 15 on the test accuracy stays around 0.84, and for very large k it slowly falls again: the model starts to underfit."
   ],
   "id": "t32-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "ks = list(range(1, 52, 4))\n",
    "train_scores = []\n",
    "test_scores = []\n",
    "\n",
    "for k in ks:\n",
    "    model = KNeighborsClassifier(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 accuracy\")\n",
    "plt.plot(ks, test_scores, marker=\"o\", label=\"test accuracy\")\n",
    "plt.xlabel(\"k (n_neighbors)\")\n",
    "plt.ylabel(\"accuracy\")\n",
    "plt.title(\"Small k overfits; the gap closes as k grows\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t32-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.2 k chosen with cross-validation\n",
    "\n",
    "The test data must not choose k. Cross-validation on the training data does (Topic 23):\n",
    "\n",
    "Change it and run: change `cv=5` to `cv=10` and run: k = 15 stays among the best."
   ],
   "id": "t32-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for k in [5, 11, 15, 21, 31]:\n",
    "    model = KNeighborsClassifier(n_neighbors=k)\n",
    "    scores = cross_val_score(model, X_train_scaled, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))"
   ],
   "id": "t32-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows k and the mean accuracy of five folds. k = 15 has the highest mean. (Strictly, the scaler should be fitted again inside every fold; Topic 42 does this with a pipeline. Here the difference is tiny.)\n",
    "\n",
    "### 8.3 Why an odd k"
   ],
   "id": "t32-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k in [4, 5, 6]:\n",
    "    model = KNeighborsClassifier(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    leaving = model.predict_proba(X_test_scaled)[:, 1]\n",
    "    print(k, (leaving == 0.5).sum())"
   ],
   "id": "t32-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows k and the number of test customers whose neighbours are split exactly half and half. With k = 4, 214 of the 2,000 test customers are ties, and the model decides them by a rule that has nothing to do with the data. With k = 5 no tie is possible.\n",
    "\n",
    "### 8.4 The model with k = 15\n",
    "\n",
    "Change it and run: change `n_neighbors=15` to `n_neighbors=25` and run."
   ],
   "id": "t32-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "knn15 = KNeighborsClassifier(n_neighbors=15)\n",
    "knn15.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted15 = knn15.predict(X_test_scaled)\n",
    "leaving15 = knn15.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "print(confusion_matrix(y_test, predicted15))\n",
    "print(round(knn15.score(X_test_scaled, y_test), 4))\n",
    "print(round(recall_score(y_test, predicted15), 4))\n",
    "print(round(f1_score(y_test, predicted15), 4))\n",
    "print(round(roc_auc_score(y_test, leaving15), 4))"
   ],
   "id": "t32-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The accuracy rises from 0.83 to 0.842 and the AUC from 0.76 to 0.80: with 15 votes the probabilities are finer (16 possible values) and steadier. But the recall falls to 0.33: with more neighbours, the 20 percent of leavers are outvoted more often. A larger k pulls every prediction towards the large class.\n",
    "\n",
    "### 8.5 `weights` and `p`"
   ],
   "id": "t32-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for weights in [\"uniform\", \"distance\"]:\n",
    "    for p in [1, 2]:\n",
    "        model = KNeighborsClassifier(n_neighbors=15, weights=weights, p=p)\n",
    "        model.fit(X_train_scaled, y_train)\n",
    "        train_acc = round(model.score(X_train_scaled, y_train), 4)\n",
    "        test_acc = round(model.score(X_test_scaled, y_test), 4)\n",
    "        auc = round(roc_auc_score(y_test, model.predict_proba(X_test_scaled)[:, 1]), 4)\n",
    "        print(weights, p, train_acc, test_acc, auc)"
   ],
   "id": "t32-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the weights, p, the training accuracy, the test accuracy and the test AUC.\n",
    "\n",
    "- With `weights=\"distance\"` the training accuracy is 1.0 again: every training customer is its own neighbour at the distance 0, with an infinite weight. It is no sign of a perfect model; judge it on the test data only.\n",
    "- The Manhattan distance (`p=1`) is a little better than the Euclidean distance here; the differences are small.\n",
    "\n",
    "### 8.6 More recall: a lower threshold\n",
    "\n",
    "k-nearest neighbours has no `class_weight`. But it gives probabilities, and the threshold of 0.5 can be moved, as in Topic 28:\n",
    "\n",
    "Change it and run: change `0.3` to `0.2` and run: even more recall, less precision."
   ],
   "id": "t32-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predicted_03 = (leaving15 >= 0.3).astype(int)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_03), 4))\n",
    "print(round(precision_score(y_test, predicted_03), 4))\n",
    "print(round(f1_score(y_test, predicted_03), 4))"
   ],
   "id": "t32-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A customer counts as \"leaves\" when at least 30 percent of his 15 neighbours left (5 of 15). The recall rises from 0.33 to 0.56, the precision falls from 0.71 to 0.51, and the F1-score rises. For a bank that wants to call the customers who may leave, this is the more useful model.\n",
    "\n",
    "### 8.7 Fewer, better features\n",
    "\n",
    "k-nearest neighbours treats every feature as equally important. The estimated salary, the credit score and the tenure said little about leaving in Topics 29 and 30, but here they still take part in every distance. What happens with only the features that matter?\n",
    "\n",
    "Change it and run: remove `\"gender\"` from the list and run."
   ],
   "id": "t32-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = [\"age\", \"active_member\", \"products_number\", \"balance\", \"country_Germany\", \"gender\"]\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 = KNeighborsClassifier(n_neighbors=15)\n",
    "knn_few.fit(X_train_few, y_train)\n",
    "\n",
    "print(round(knn_few.score(X_test_few, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, knn_few.predict_proba(X_test_few)[:, 1]), 4))"
   ],
   "id": "t32-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With six features instead of eleven the accuracy rises to 0.861 and the AUC to 0.84, the best of the lesson. The five features that were left out added noise to every distance: two customers who are alike in age, products and activity looked far apart because their salaries differed. This is the curse of dimensionality on a small scale. The six features were chosen from what the trees and forests of Topics 29 and 30 found important; in a real project they would be chosen with cross-validation, without the test data.\n",
    "\n",
    "### 8.8 The scores of every model"
   ],
   "id": "t32-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = [\n",
    "    (\"k = 5, unscaled\", unscaled, X_test),\n",
    "    (\"k = 5\", knn, X_test_scaled),\n",
    "    (\"k = 5, MinMaxScaler\", knn_minmax, X_test_minmax),\n",
    "    (\"k = 15\", knn15, X_test_scaled),\n",
    "    (\"k = 15, six features\", knn_few, X_test_few),\n",
    "]\n",
    "\n",
    "for name, model, X_part in models:\n",
    "    acc = round(model.score(X_part, y_test), 4)\n",
    "    auc = round(roc_auc_score(y_test, model.predict_proba(X_part)[:, 1]), 4)\n",
    "    print(name, acc, auc)"
   ],
   "id": "t32-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a model, its test accuracy and its test AUC on the same 2,000 customers. Each model gets the test data in the form it was trained on: unscaled, scaled, or scaled with six features."
   ],
   "id": "t32-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "names = [name for name, model, X_part in models]\n",
    "aucs = [roc_auc_score(y_test, model.predict_proba(X_part)[:, 1]) for name, model, X_part in models]\n",
    "\n",
    "plt.barh(names, aucs)\n",
    "plt.xlim(0.5, 0.9)\n",
    "plt.xlabel(\"test AUC\")\n",
    "plt.title(\"Scaling, k and the features\")\n",
    "plt.show()"
   ],
   "id": "t32-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What the comparison shows:\n",
    "\n",
    "- Without scaling the model is close to guessing.\n",
    "- Scaling makes it useful; a well chosen k makes it better.\n",
    "- Leaving out useless features helps k-nearest neighbours most of all.\n",
    "\n",
    "## 9. The workflow, step by step\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look | shape, first rows, the meaning of the columns | 10,000 customers, 12 columns |\n",
    "| 2. Check | missing values, repeated rows, text columns | nothing missing; two text columns |\n",
    "| 3. Drop | columns without information | `customer_id` |\n",
    "| 4. Target | the share of each class | 20 percent left: unbalanced |\n",
    "| 5. Outliers | find them, decide | real customers, kept |\n",
    "| 6. Encode | text to numbers | `gender` 0 and 1, `country` one-hot, `products_number` a number |\n",
    "| 7. Split | training and test data | 8,000 and 2,000 |\n",
    "| 8. Scale | essential for distances; fitted on the training data | `StandardScaler` |\n",
    "| 9. Model | k-nearest neighbours | k = 5: accuracy 0.83, AUC 0.76 |\n",
    "| 10. Look inside | the neighbours of one customer | two of five left: probability 0.4 |\n",
    "| 11. Measures | confusion matrix, precision, recall, F1, AUC | recall only 0.37 |\n",
    "| 12. Tune | k with cross-validation; odd k; `weights`, `p` | k = 15: accuracy 0.842, AUC 0.80 |\n",
    "| 13. Threshold | for more recall | 0.3: recall 0.56 |\n",
    "| 14. Features | fewer, useful features | six features: AUC 0.84 |\n",
    "\n",
    "## 10. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Training k-nearest neighbours on unscaled features. | The feature with the largest numbers decides every distance. | `StandardScaler`, fitted on the training data. |\n",
    "| Fitting the scaler on all the data, or again on the test data. | The test data then helps to build the model, or is scaled with other numbers. | `fit_transform` on training, `transform` on test. |\n",
    "| Choosing k = 1 because the training accuracy is 1.0. | Every training row is its own neighbour; that is memorising. | Judge k with cross-validation or test data. |\n",
    "| Choosing an even k for two classes. | Votes can tie, and ties are broken by a rule unrelated to the data. | An odd k. |\n",
    "| Choosing k with the test data. | The test data then helps to build the model. | Cross-validation on the training data. |\n",
    "| Encoding countries as 0, 1, 2. | It invents distances between countries. | One-hot encoding. |\n",
    "| Leaving an identification number or useless features in. | They add noise to every distance. | Drop them; choose useful features. |\n",
    "| Expecting `class_weight` to fix unbalanced classes. | `KNeighborsClassifier` has none. | Move the threshold of the probability (Topic 28). |\n",
    "| Leaving missing values in. | A distance cannot be computed with a gap. | Fill them first. |\n",
    "| Expecting fast predictions on big data. | Every prediction measures the distance to all training rows. | Use fewer rows or features, or another model. |\n",
    "\n",
    "## 11. Solved problems\n",
    "\n",
    "The first four problems are short and solved by hand. Problems 5 to 16 are one project on `Bank Customer Churn Prediction.csv`, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.\n",
    "\n",
    "Problem 1. The vote\n",
    "\n",
    "A new customer has the distances 0.5, 1.2, 0.9, 2.0 and 1.5 to five training customers, who stayed, left, left, stayed and left. What does k-nearest neighbours predict (a) with k = 1, (b) with k = 3? (c) What is `predict_proba` for leaving with k = 3?\n",
    "\n",
    "Idea. Sort by distance, take the k nearest, count (Part 2).\n",
    "\n",
    "Sorted: 0.5 (stayed), 0.9 (left), 1.2 (left), 1.5 (left), 2.0 (stayed). With $k = 3$: two left, one stayed.\n",
    "\n",
    "$$\n",
    "\\text{share that left} = \\frac{2}{3} = 0.667\n",
    "$$\n",
    "\n",
    "Why: (a) the nearest customer stayed: \"stays\". (b) Two of the three nearest left: \"leaves\". (c) 0.667. One neighbour more changes the answer.\n",
    "\n",
    "Problem 2. Two distances\n",
    "\n",
    "Find the Euclidean and the Manhattan distance between the scaled customers (1, -2, 0.5) and (3, 1, 0.5).\n",
    "\n",
    "Idea. The differences are 2, 3 and 0 (Part 3).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Euclidean:}\\quad & \\sqrt{2^2 + 3^2 + 0^2} = \\sqrt{13} = 3.606 \\\\[6pt]\n",
    "\\text{Manhattan:}\\quad & 2 + 3 + 0 = 5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the Manhattan distance is never smaller than the Euclidean distance; it walks along each feature instead of going straight.\n",
    "\n",
    "Problem 3. Scaling\n",
    "\n",
    "Two customers differ by 5 years of age and by 30,000 euros of balance. The standard deviations are 10 years and 60,000 euros. Find the distance (a) without scaling, (b) after dividing each difference by its standard deviation.\n",
    "\n",
    "Idea. The feature with the larger numbers dominates without scaling (Part 3).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{without scaling:}\\quad & \\sqrt{5^2 + 30{,}000^2} \\\\[4pt]\n",
    "& = 30{,}000.0 \\\\[8pt]\n",
    "\\text{scaled:}\\quad & \\sqrt{\\left(\\tfrac{5}{10}\\right)^2 + \\left(\\tfrac{30{,}000}{60{,}000}\\right)^2} \\\\[4pt]\n",
    "& = \\sqrt{0.25 + 0.25} = \\sqrt{0.5} = 0.707\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: without scaling the age changes nothing at all; after scaling both differences are half a spread and count equally.\n",
    "\n",
    "Problem 4. Choosing k\n",
    "\n",
    "A training set has 6,400 customers, 80 percent of whom stayed. (a) What is the rule-of-thumb $k \\approx \\sqrt{n}$? (b) Is it a good k for two classes, and if not, which nearby k is? (c) What does the model predict for every customer with k = 6,400?\n",
    "\n",
    "Idea. The square root of n; odd k for two classes; the largest k gives the largest class (Part 4).\n",
    "\n",
    "$$\n",
    "\\sqrt{6{,}400} = 80\n",
    "$$\n",
    "\n",
    "Why: (a) 80. (b) 80 is even, so votes can tie; take 79 or 81, and check it with cross-validation. (c) \"stays\" for everybody: all 6,400 customers vote, and 80 percent of them stayed.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of missing values and the share of customers who left, rounded to 4 decimals.\n",
    "\n",
    "Idea. The first steps of the workflow (Part 6)."
   ],
   "id": "t32-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.isna().sum().sum())\n",
    "print(round(df[\"churn\"].mean(), 4))"
   ],
   "id": "t32-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: nothing to fill, which k-nearest neighbours requires, and one customer in five left.\n",
    "\n",
    "Problem 6. Drop and encode\n",
    "\n",
    "Drop `customer_id`, encode `gender` as 0 (Female) and 1 (Male), and one-hot encode `country` with `drop_first=True`. Print the number of columns.\n",
    "\n",
    "Idea. Text to numbers; one-hot keeps all countries equally far apart (Part 6)."
   ],
   "id": "t32-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))"
   ],
   "id": "t32-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: eleven features and the target.\n",
    "\n",
    "Problem 7. Split\n",
    "\n",
    "Make `X` and `y` and split them with `test_size=0.25` and `random_state=7`. Print the shapes of `X_train` and `X_test`.\n",
    "\n",
    "Idea. The split comes before the scaler learns anything."
   ],
   "id": "t32-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t32-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 7,500 customers to search for neighbours and 2,500 to judge with.\n",
    "\n",
    "Problem 8. Scale\n",
    "\n",
    "Fit a `StandardScaler` on the training data and scale both parts. Print the mean and the standard deviation of the first scaled training column, rounded to 2 decimals.\n",
    "\n",
    "Idea. Fit on training, transform both (Part 6)."
   ],
   "id": "t32-055"
  },
  {
   "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(abs(round(X_train_scaled[:, 0].mean(), 2)))\n",
    "print(round(X_train_scaled[:, 0].std(), 2))"
   ],
   "id": "t32-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a mean of 0 and a standard deviation of 1 on the training data. (`abs` turns a possible `-0.0` into `0.0`.)\n",
    "\n",
    "Problem 9. The default model\n",
    "\n",
    "Train a `KNeighborsClassifier` with its default settings on the scaled data. Print its training accuracy and its test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. k = 5 (Part 7)."
   ],
   "id": "t32-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn = KNeighborsClassifier()\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": "t32-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the training accuracy is higher: each training customer is among its own five neighbours.\n",
    "\n",
    "Problem 10. The neighbours of one customer\n",
    "\n",
    "For the first test customer, print the classes of his 5 nearest training customers as a list, then `predict_proba`.\n",
    "\n",
    "Idea. `kneighbors` gives the positions of the neighbours in the training data (Part 7)."
   ],
   "id": "t32-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customer = X_test_scaled[[0]]\n",
    "\n",
    "distances, positions = knn.kneighbors(customer)\n",
    "\n",
    "print(y_train.iloc[positions[0]].tolist())\n",
    "print(knn.predict_proba(customer))"
   ],
   "id": "t32-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the share of the 1s in the list is the second number of `predict_proba`.\n",
    "\n",
    "Problem 11. The measures\n",
    "\n",
    "Print the confusion matrix, the recall and the AUC of `knn`, the last two rounded to 4 decimals.\n",
    "\n",
    "Idea. The measures of Topic 28; the AUC needs the probabilities."
   ],
   "id": "t32-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "predicted = knn.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(roc_auc_score(y_test, knn.predict_proba(X_test_scaled)[:, 1]), 4))"
   ],
   "id": "t32-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a fair accuracy hides a low recall: most leaving customers are missed.\n",
    "\n",
    "Problem 12. k against the test accuracy\n",
    "\n",
    "For k = 1, 15 and 51, print k, the training accuracy and the test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. Small k overfits, very large k underfits (Part 8)."
   ],
   "id": "t32-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k in [1, 15, 51]:\n",
    "    model = KNeighborsClassifier(n_neighbors=k)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(k, round(model.score(X_train_scaled, y_train), 4), round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t32-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: k = 1 has a perfect training score and the lowest test score; the gap closes as k grows.\n",
    "\n",
    "Problem 13. k with cross-validation\n",
    "\n",
    "For k = 5, 15 and 25, print k and the mean accuracy 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 8)."
   ],
   "id": "t32-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for k in [5, 15, 25]:\n",
    "    scores = cross_val_score(KNeighborsClassifier(n_neighbors=k), X_train_scaled, y_train, cv=5)\n",
    "    print(k, round(scores.mean(), 4))"
   ],
   "id": "t32-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: k = 5 is clearly below the two larger values, which are close to each other.\n",
    "\n",
    "Problem 14. The model with k = 15\n",
    "\n",
    "Train a model with k = 15, called `knn15`. Print its test accuracy, its recall and its AUC, rounded to 4 decimals.\n",
    "\n",
    "Idea. The k chosen in the lesson (Part 8)."
   ],
   "id": "t32-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "knn15 = KNeighborsClassifier(n_neighbors=15)\n",
    "knn15.fit(X_train_scaled, y_train)\n",
    "\n",
    "leaving15 = knn15.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "print(round(knn15.score(X_test_scaled, y_test), 4))\n",
    "print(round(recall_score(y_test, knn15.predict(X_test_scaled)), 4))\n",
    "print(round(roc_auc_score(y_test, leaving15), 4))"
   ],
   "id": "t32-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a higher accuracy and AUC than k = 5, but a lower recall: more neighbours outvote the leavers more often.\n",
    "\n",
    "Problem 15. A lower threshold\n",
    "\n",
    "Predict \"leaves\" when the probability of `knn15` is at least 0.3. Print the recall and the F1-score, rounded to 4 decimals.\n",
    "\n",
    "Idea. No `class_weight`, but a movable threshold (Topic 28)."
   ],
   "id": "t32-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predicted_03 = (leaving15 >= 0.3).astype(int)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_03), 4))\n",
    "print(round(f1_score(y_test, predicted_03), 4))"
   ],
   "id": "t32-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the recall rises sharply, and the F1-score with it.\n",
    "\n",
    "Problem 16. Scaled against unscaled\n",
    "\n",
    "Train a model with k = 15 on the unscaled training data. Print its test AUC and the test AUC of `knn15`, rounded to 4 decimals.\n",
    "\n",
    "Idea. Distances need scaled features (Part 3)."
   ],
   "id": "t32-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = KNeighborsClassifier(n_neighbors=15)\n",
    "raw.fit(X_train, y_train)\n",
    "\n",
    "print(round(roc_auc_score(y_test, raw.predict_proba(X_test)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, leaving15), 4))"
   ],
   "id": "t32-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: unscaled, the AUC is little better than guessing; scaled, it is clearly useful.\n",
    "\n",
    "## 14. Summary\n",
    "\n",
    "|  | Formula or rule | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Euclidean distance | $\\sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2 + \\dots}$ | the straight line; `p=2`, the default |\n",
    "| Manhattan distance | the sum of the absolute differences | along each feature; `p=1` |\n",
    "| Prediction | the majority class of the k nearest rows | `predict_proba` is the share of the votes |\n",
    "| Weighted vote | each vote counts $\\frac{1}{\\text{distance}}$ | `weights=\"distance\"` |\n",
    "| Small k | low bias, high variance | k = 1 memorises: training accuracy 1.0 |\n",
    "| Large k | high bias, low variance | k = n always predicts the largest class |\n",
    "| Rule of thumb | $k \\approx \\sqrt{n}$, odd for two classes | then cross-validation |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `KNeighborsClassifier(n_neighbors=15)` | k-nearest neighbours with k = 15 |\n",
    "| `weights=\"distance\"`, `p=1` | weighted votes, Manhattan distance |\n",
    "| `StandardScaler().fit_transform(X_train)`, then `transform(X_test)` | the scaling the model needs |\n",
    "| `knn.kneighbors(row)` | the distances and positions of the k nearest training rows |\n",
    "| `knn.predict_proba(X)[:, 1]` | the share of the neighbours of class 1 |\n",
    "| `(probabilities >= 0.3).astype(int)` | a lower threshold for more recall |\n",
    "| `cross_val_score(knn, X_train_scaled, y_train, cv=5)` | choosing k without the test data |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. k-nearest neighbours stores the training rows and votes with the k nearest; the share of the votes is the probability.\n",
    "2. Always scale the features, with the scaler fitted on the training data.\n",
    "3. Small k overfits, large k underfits; choose an odd k with cross-validation.\n",
    "4. One-hot encode categories, fill missing values, look at outliers, and drop useless features.\n",
    "5. Without `class_weight`, raise the recall by lowering the threshold.\n",
    "6. Predictions are slow on large data: every prediction measures all the distances.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "Topic 33 uses the same neighbours to predict a number: the mean of the neighbours' values instead of a vote. Topic 34 then brings Naive Bayes, a model that calculates probabilities with Bayes' rule (Topic 16) instead of measuring distances.\n",
    "\n",
    "Next: the practice notebook (topic-32-practice.ipynb), then Topic 33: k-Nearest Neighbors - Regression."
   ],
   "id": "t32-073"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
