Asiman Data School

Module 3, topic 32, week 16, Thursday

k-Nearest Neighbors - Classification

A model that learns nothing and asks the most similar customers: distances, the vote of the k nearest, why scaling is essential, the hyperparameters, how to choose k (and why an odd k), and the preprocessing a distance-based model needs, on the bank data from the file to the measures.

Introduction: tell me who your neighbours are

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."

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.

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.

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.

What you will learn

  1. 1.What k-nearest neighbours is, and where it is used
  2. 2.How it decides for a new row: distances, the k nearest rows, a vote
  3. 3.How the distance is measured: Euclidean, Manhattan and Minkowski
  4. 4.Why scaling is essential for this model, shown by hand and on the bank data
  5. 5.The hyperparameters of KNeighborsClassifier and their roles
  6. 6.How to choose k: overfitting with a small k, underfitting with a large k, cross-validation, and why k should be odd
  7. 7.What scaling, encoding, outliers, missing values and useless features mean for k-nearest neighbours and for the models still to come
  8. 8.A whole project: from the file to a tuned model and its measures
The words of this lesson
WordMeaning
k-nearest neighbours (kNN)a model that predicts the class of a new row from the classes of the k most similar training rows
Neighboura training row that is close to the new row
khow many neighbours vote: the main hyperparameter
Distancea number that says how different two rows are; small means similar
Euclidean distancethe straight-line distance (Topic 13)
Manhattan distancethe sum of the differences along each feature, like walking along the streets of a city grid
Majority votethe class that most of the k neighbours have
Lazy learnera model that does no work when it is trained and all the work when it predicts
Curse of dimensionalitywith many features, all rows become almost equally far apart, and "nearest" loses its meaning

1What k-nearest neighbours is

1.1The idea

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.

That is the whole algorithm:

  1. Keep all the training rows.
  2. For a new row, measure its distance to every training row.
  3. Take the k rows with the smallest distances: the k nearest neighbours.
  4. Predict the class that most of them have.

1.2A lazy learner

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.

This has two consequences:

  • Training is instant, but predicting is slow when the training data is large: every prediction looks at all the stored rows.
  • 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").

1.3Where k-nearest neighbours is used

  • Recommendations: "customers who are similar to you bought...", films that people with similar tastes liked.
  • Banking and insurance: churn and credit risk, by comparing a customer with similar customers (the project of this lesson).
  • Medicine: finding the patients most similar to a new patient, and what their diagnosis was.
  • Recognising images and handwriting: a new picture of a digit gets the label of the most similar stored pictures.
  • Finding unusual rows: a row whose nearest neighbours are all far away is an outlier (fraud, a broken sensor).
  • Filling missing values: KNNImputer fills a gap with the values of the most similar rows.
  • As a simple baseline: a quick first model to compare the others with.

1.4Strengths and weaknesses

Strengths and weaknesses
StrengthsWeaknesses
Very simple to understand and to explainSlow predictions on large data: every prediction measures all distances
No training timeNeeds the whole training data in memory
No assumption about the shape of the classes: the border between them can have any formNeeds scaled features, or one feature decides the distances alone
Works for any number of classesUseless features and many features spoil the distances (the curse of dimensionality)
The same idea also predicts numbers (Topic 33)Sensitive to outliers, and it cannot work with missing values

Try it yourself

(a) What does KNeighborsClassifier do in fit? (b) What is such a model called? (c) Must the features be scaled for it? (d) When are its predictions slow?

Show a hint
Look at "A lazy learner" and the table of strengths and weaknesses.
Show the solution

Answer: (a) it stores the training rows; (b) a lazy learner; (c) yes; (d) when the training data is large.

All the work happens in predict: every new row is compared with every stored row.

2How it decides: an example with eight customers

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.

How it decides: an example with eight customers
CustomerTenure (years)ProductsLeft the bank?
A43leaves
B22stays
C51stays
D63stays
E11leaves
F74leaves
G81stays
H24leaves

A new customer N has been a customer for 4 years and uses 2 products. Will he leave?

2.1Step 1: the distances

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):

distance(N,A)=(4−4)2+(2−3)2=0+1=1=1\begin{aligned} & \text{distance}(N, A) \\[4pt] &= \sqrt{(4 - 4)^2 + (2 - 3)^2} \\[4pt] &= \sqrt{0 + 1} = \sqrt{1} = 1 \end{aligned}

For N and C = (5, 1):

distance(N,C)=(4−5)2+(2−1)2=1+1=2=1.414\begin{aligned} & \text{distance}(N, C) \\[4pt] &= \sqrt{(4 - 5)^2 + (2 - 1)^2} \\[4pt] &= \sqrt{1 + 1} = \sqrt{2} = 1.414 \end{aligned}

The same for all eight customers, sorted from the nearest to the farthest:

Step 1: the distances
RankCustomerDifferencesDistanceLeft the bank?
1A0 and 11=1\sqrt{1} = 1leaves
2C1 and 12=1.414\sqrt{2} = 1.414stays
3B2 and 04=2\sqrt{4} = 2stays
4D2 and 15=2.236\sqrt{5} = 2.236stays
5H2 and 28=2.828\sqrt{8} = 2.828leaves
6E3 and 110=3.162\sqrt{10} = 3.162leaves
7F3 and 213=3.606\sqrt{13} = 3.606leaves
8G4 and 117=4.123\sqrt{17} = 4.123stays
01234502468tenure (years)productsABCDEFGHN (new)
  • left the bank
  • stayed
  • the 3 nearest, ringed
The eight customers by tenure and number of products: orange left the bank, teal stayed. The new customer N sits at (4, 2). The dashed circle reaches the third nearest customer, B: inside are A, C and B, one leaver and two who stayed, so with k = 3 the model predicts "stays".

2.2Step 2: the vote of the k nearest

The prediction depends on how many neighbours vote:

Step 2: the vote of the k nearest
kThe k nearestLeaveStayShare that leftPrediction
1A1011=1\frac{1}{1} = 1leaves
3A, C, B1213=0.333\frac{1}{3} = 0.333stays
5A, C, B, D, H2325=0.4\frac{2}{5} = 0.4stays
7A, C, B, D, H, E, F4347=0.571\frac{4}{7} = 0.571leaves
8all eight4448=0.5\frac{4}{8} = 0.5a tie

Four lessons are in this table:

  • 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).
  • 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.
  • 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".
  • 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.

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.

Choose k and the kind of vote. The circle reaches the k-th nearest customer of N; the ringed customers vote.

01234502468tenure (years)productsABCDEFGHN (new)

The 3 nearest: A (1), C (1.414), B (2).

Votes for "leaves": 1, for "stays": 2. Share that left: 0.333. Prediction: stays.

Every neighbour has one vote. Try k = 1, 3, 7 and 8.

2.3Weighted votes

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 1distance\frac{1}{\text{distance}}, so close neighbours count more. For k = 3:

leaves:A: 11=1stays:C: 11.414=0.707,B: 12=0.5together 0.707+0.5=1.207\begin{aligned} \text{leaves:}\quad & A:\ \tfrac{1}{1} = 1 \\[8pt] \text{stays:}\quad & C:\ \tfrac{1}{1.414} = 0.707, \quad B:\ \tfrac{1}{2} = 0.5 \\[4pt] & \text{together } 0.707 + 0.5 = 1.207 \end{aligned}

1.207 is more than 1: N still stays, but closer than in the plain vote (one against two).

Try it yourself

A new customer M has been a customer for 7 years and uses 2 products. Use the eight customers of the table. (a) What is the distance from M to F = (7, 4)? (b) The three nearest customers are D, G and F. What does the model predict with k=3k = 3? (c) The fourth and fifth nearest are C and A. What is predict_proba for leaving with k=5k = 5?

Show a hint
D and G stayed, F left; C stayed, A left. The probability is the share of the neighbours that left.
Show the solution

Answer: (a) 2; (b) stays; (c) 0.4.

distance(M,F)=(7−7)2+(2−4)2=4=2k=5:25=0.4\begin{aligned} \text{distance}(M, F) &= \sqrt{(7 - 7)^2 + (2 - 4)^2} \\[4pt] &= \sqrt{4} = 2 \\[8pt] k = 5:\quad & \frac{2}{5} = 0.4 \end{aligned}

With k=3k = 3 two neighbours stayed (D and G, both at 2=1.414\sqrt{2} = 1.414) and one left (F): "stays". With k=5k = 5 F and A left, D, G and C stayed.

3How the distance is measured

3.1Euclidean, Manhattan, Minkowski

For two rows with the features x1,x2,…x_1, x_2, \dots and y1,y2,…y_1, y_2, \dots:

Euclidean distance=(x1−y1)2+(x2−y2)2+…\begin{aligned} & \text{Euclidean distance} \\[4pt] &= \sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2 + \dots} \end{aligned}
Manhattan distance=∣x1−y1∣+∣x2−y2∣+…\begin{aligned} & \text{Manhattan distance} \\[4pt] &= |x_1 - y_1| + |x_2 - y_2| + \dots \end{aligned}

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):

Euclidean:22+12=5=2.236Manhattan:2+1=3\begin{aligned} \text{Euclidean:}\quad & \sqrt{2^2 + 1^2} = \sqrt{5} = 2.236 \\[6pt] \text{Manhattan:}\quad & 2 + 1 = 3 \end{aligned}

Both are members of one family, the Minkowski distance with a power p:

Minkowski distance=(∣x1−y1∣p+∣x2−y2∣p+… )1/p\begin{aligned} & \text{Minkowski distance} \\[4pt] &= \left(|x_1 - y_1|^p + |x_2 - y_2|^p + \dots\right)^{1/p} \end{aligned}

p=1p = 1 gives the Manhattan distance, p=2p = 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.

345671234ND21
  • Euclidean: √5 = 2.236
  • Manhattan: 2 + 1 = 3
Two ways from N = (4, 2) to D = (6, 3). The Euclidean distance is the straight line: √5 = 2.236. The Manhattan distance walks along the features, 2 to the right and 1 up: 2 + 1 = 3.

3.2Why scaling is essential

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:

Why scaling is essential
CustomerAgeBalance (euros)
N4050,000
P41120,000
Q6052,000

Without scaling:

distance(N,P)=12+70,0002=70,000.0distance(N,Q)=202+2,0002=2,000.1\begin{aligned} \text{distance}(N, P) &= \sqrt{1^2 + 70{,}000^2} = 70{,}000.0 \\[6pt] \text{distance}(N, Q) &= \sqrt{20^2 + 2{,}000^2} = 2{,}000.1 \end{aligned}

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.

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):

distance(N,P)=(110)2+(70,00060,000)2=0.01+1.362=1.372=1.171\begin{aligned} & \text{distance}(N, P) \\[4pt] &= \sqrt{\left(\tfrac{1}{10}\right)^2 + \left(\tfrac{70{,}000}{60{,}000}\right)^2} \\[4pt] &= \sqrt{0.01 + 1.362} = \sqrt{1.372} = 1.171 \end{aligned}
distance(N,Q)=(2010)2+(2,00060,000)2=4+0.001=4.001=2.000\begin{aligned} & \text{distance}(N, Q) \\[4pt] &= \sqrt{\left(\tfrac{20}{10}\right)^2 + \left(\tfrac{2{,}000}{60{,}000}\right)^2} \\[4pt] &= \sqrt{4 + 0.001} = \sqrt{4.001} = 2.000 \end{aligned}

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).

The new customer N (40 years, 50,000 euros) and two known customers. Measure the distances without and with scaling.

N to P: age difference 1, balance difference 70,000; the balance gives 100 percent of the squared distance.

N to Q: age difference 20, balance difference 2,000; the balance gives 100 percent of the squared distance.

The nearer customer: Q.

The balance is counted in tens of thousands, the age in tens: the balance decides alone.

Rule: k-nearest neighbours always needs scaled features. StandardScaler is the usual choice; MinMaxScaler also works, and the project compares the two.

Try it yourself

(a) Find the Euclidean distance between (1,2)(1, 2) and (4,6)(4, 6). (b) Find their Manhattan distance. (c) Which value of p gives the Manhattan distance? (d) Two customers differ by 2 years and by 12,000 euros; the spreads are 10 years and 60,000 euros. Which difference is larger after scaling?

Show a hint
The differences are 3 and 4. After scaling, divide each difference by its spread.
Show the solution

Answer: (a) 5; (b) 7; (c) 1; (d) they are equal (0.2 and 0.2).

Euclidean:32+42=25=5Manhattan:3+4=7scaled:210=0.2,12,00060,000=0.2\begin{aligned} \text{Euclidean:}\quad & \sqrt{3^2 + 4^2} = \sqrt{25} = 5 \\[6pt] \text{Manhattan:}\quad & 3 + 4 = 7 \\[6pt] \text{scaled:}\quad & \tfrac{2}{10} = 0.2, \quad \tfrac{12{,}000}{60{,}000} = 0.2 \end{aligned}

Without scaling the balance would decide alone; after scaling the two differences count the same.

4The hyperparameters, and how to choose k

4.1The hyperparameters of KNeighborsClassifier

The hyperparameters of KNeighborsClassifier
HyperparameterDefaultRole
n_neighbors5k, 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).
weights"uniform""uniform": every neighbour has one vote. "distance": a vote counts 1distance\frac{1}{\text{distance}}, so close neighbours count more.
metric"minkowski"how the distance is measured; "euclidean" and "manhattan" can also be named directly
p2the power of the Minkowski distance: 2 is Euclidean, 1 is Manhattan
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.
leaf_size30a setting of the two tree structures: speed and memory only
n_jobsNonehow many processor cores search at the same time; -1 uses all

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).

4.2How the neighbours are found

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:

2,000×8,000=16,000,000 distances2{,}000 \times 8{,}000 = 16{,}000{,}000 \text{ distances}

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.

4.3Small k, large k: overfitting and underfitting

  • 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.
  • Larger k: the vote averages more customers, the border between the classes becomes smoother, and single accidents no longer decide. The variance falls.
  • 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.
−2024−1012age (scaled)

k = 1

a border around single customers

−2024−1012age (scaled)

k = 31

a smooth border

  • left / area of "leaves"
  • stayed / area of "stays"
The border of the model on two features of 500 bank customers, age and balance, both scaled. In the orange area the model predicts "leaves". With k = 1 the border wraps around single customers in small islands: it overfits. With k = 31 it is smooth, and "leaves" covers mainly the older customers.

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.

The border of the model on two features of 500 bank customers. Choose k: in the orange area the model predicts "leaves".

−2024−1012age (scaled)

k = 1: islands around single customers: overfitting.

Small k: low bias, high variance. Large k: high bias, low variance.

4.4How to choose k

  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.)
  2. A first guess: a common rule of thumb is k≈nk \approx \sqrt{n}, the square root of the number of training rows. For 8,000 rows: 8,000=89.4\sqrt{8{,}000} = 89.4. It is only a starting point: on the bank data a smaller k is better.
  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.
  4. Look at both scores: a training score far above the cross-validated score means a k that is too small.

Searching several hyperparameters at once (k, weights and p together) is the subject of Topic 42.

Which hyperparameter is it?

1 of 7

With 1 the model memorises the training rows; with the number of rows it always predicts the largest class.

Try it yourself

(a) What is the training accuracy of k-nearest neighbours with k=1k = 1? (b) A training set has 2,500 rows. What is the rule-of-thumb n\sqrt{n}? (c) What does the model predict for every row when k is the number of training rows? (d) Does algorithm="brute" change the predictions?

Show a hint
Every training row is its own nearest neighbour. With all rows voting, the largest class wins.
Show the solution

Answer: (a) 1; (b) 50; (c) the largest class; (d) no.

2,500=50\sqrt{2{,}500} = 50

50 is even; for two classes take 49 or 51, then compare with cross-validation. The search algorithm changes only the speed.

5Preprocessing for k-nearest neighbours, and for the models still to come

k-nearest neighbours is the model that needs the most careful preprocessing so far, because everything it does is measuring distances.

  • 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).
  • 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.
  • 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).
  • 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.
  • 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).
  • Unbalanced classes: there is no class_weight. The probability threshold can be lowered (Topic 28); Topic 41 goes further.
Preprocessing for k-nearest neighbours, and for the models still to come
Model (topic)ScalingEncoding of textOutliers in the featuresMissing values
Linear regression (22)not needed for the predictionsneededsensitivefill
Ridge, Lasso, logistic regression (26, 27)neededneededsensitivefill
Decision tree, random forest, bagged trees (29, 30, 31)not neededneededrobustfill (recent scikit-learn can handle them)
k-nearest neighbours (32, 33)essential: distancesneeded; one-hot for categoriessensitivefill
Naive Bayes (34)not needed for the usual Gaussian formneededsensitivefill
Support vector machines, voting (35, 36)needed for the support vector machine; voting as the models insideneededsensitivefill
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robustXGBoost, LightGBM and CatBoost handle them
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitivefill

Topic 42 will put the scaler and the model into one object, so that the scaler is always fitted on the right rows.

Try it yourself

(a) Must the features be scaled for k-nearest neighbours? (b) How should country be encoded? (c) What must be done with missing values? (d) Do useless features help, hurt or change nothing?

Show a hint
Everything the model does is measuring distances.
Show the solution

Answer: (a) yes; (b) one-hot; (c) fill them; (d) they hurt.

Scaling makes every feature count in units of its spread; one-hot keeps the countries equally far apart; a distance cannot be computed with a gap; a useless feature adds noise to every distance.

6The project: from the file to the scaled data

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).

The data file: Bank Customer Churn Prediction.csv

10,000 customers, 12 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.

Download

Loading the table ...

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.

6.1Step 1: read and look

Python
import pandas as pd

df = pd.read_csv("Bank Customer Churn Prediction.csv")

print(df.shape)
print(df.head())

Output

(10000, 12)
   customer_id  credit_score country  ... active_member  estimated_salary  churn
0     15634602           619  France  ...             1         101348.88      1
1     15647311           608   Spain  ...             1         112542.58      0
2     15619304           502  France  ...             0         113931.57      1
3     15701354           699  France  ...             0          93826.63      0
4     15737888           850   Spain  ...             1          79084.10      0

[5 rows x 12 columns]

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.

6.2Step 2: check

Python, continues from the cells above
print(df.isna().sum().sum())
print(df.duplicated().sum())
print(df.dtypes)

Output

0
0
customer_id           int64
credit_score          int64
country                 str
gender                  str
age                   int64
tenure                int64
balance             float64
products_number       int64
credit_card           int64
active_member         int64
estimated_salary    float64
churn                 int64
dtype: object

No missing values (k-nearest neighbours could not work with them), no repeated rows, and two text columns: country and gender.

6.3Step 3: drop what carries no information

Python, continues from the cells above
df = df.drop(columns=["customer_id"])

print(df.shape)

Output

(10000, 11)

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".

6.4Step 4: the target

Python, continues from the cells above
print(df["churn"].value_counts())
print(round(df["churn"].mean(), 4))

Output

churn
0    7963
1    2037
Name: count, dtype: int64
0.2037

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.

6.5Step 5: outliers

Python, continues from the cells above
q1 = df["age"].quantile(0.25)
q3 = df["age"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)

print(upper)
print((df["age"] > upper).sum())

Output

62.0
359

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.

6.6Step 6: encode

Python, continues from the cells above
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)

print(df.columns.tolist())

Output

['credit_score', 'gender', 'age', 'tenure', 'balance', 'products_number', 'credit_card', 'active_member', 'estimated_salary', 'churn', 'country_Germany', 'country_Spain']

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.

6.7Step 7: split

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["churn"])
y = df["churn"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print(X_train.shape, X_test.shape)

Output

(8000, 11) (2000, 11)

Change it and run: change test_size to 0.3 and run: 3,000 customers become test data.

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.

6.8Step 8: scale

Python, continues from the cells above
print(X_train[["age", "balance"]].std().round(1))

Output

age           10.5
balance    62461.0
dtype: float64

The balance spreads about 6,000 times more than the age. Without scaling, the balance would decide every distance alone (Part 3).

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(X_train_scaled.shape, X_test_scaled.shape)
print(X_train_scaled[:3].round(2))

Output

(8000, 11) (2000, 11)
[[ 0.36  0.91 -0.66  0.35 -1.22  0.81  0.65  0.97  1.37 -0.58 -0.58]
 [-0.2   0.91  0.29 -0.35  0.7   0.81  0.65  0.97  1.66  1.73 -0.58]
 [-0.96  0.91 -1.42 -0.7   0.62 -0.92  0.65 -1.03 -0.25 -0.58  1.73]]

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.

7The model

7.1Train and judge

Python, continues from the cells above
from sklearn.neighbors import KNeighborsClassifier

knn = KNeighborsClassifier()
knn.fit(X_train_scaled, y_train)

print(round(knn.score(X_train_scaled, y_train), 4))
print(round(knn.score(X_test_scaled, y_test), 4))

Output

0.8741
0.83

Change it and run: write KNeighborsClassifier(n_neighbors=1) and run: the training accuracy becomes 1.0.

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.

7.2How it decides for one customer

Python, continues from the cells above
customer = X_test_scaled[[10]]

distances, positions = knn.kneighbors(customer)

print(distances.round(3))
print(y_train.iloc[positions[0]].tolist())
print(knn.predict_proba(customer))
print(knn.predict(customer))
print(y_test.iloc[10])

Output

[[2.112 2.223 2.244 2.444 2.446]]
[0, 0, 1, 0, 1]
[[0.6 0.4]]
[0]
1

Change it and run: change both 10 to 11 and look at the neighbours of another customer.

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.

7.3The measures of Topic 28

Python, continues from the cells above
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score

predicted = knn.predict(X_test_scaled)
leaving = knn.predict_proba(X_test_scaled)[:, 1]

print(confusion_matrix(y_test, predicted))
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, leaving), 4))

Output

[[1514   93]
 [ 247  146]]
0.6109
0.3715
0.462
0.7604

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.

7.4Without scaling

What would have happened without Step 8?

Python, continues from the cells above
unscaled = KNeighborsClassifier()
unscaled.fit(X_train, y_train)

print(round(unscaled.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, unscaled.predict_proba(X_test)[:, 1]), 4))

Output

0.764
0.5373

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.

7.5Another scaler: MinMaxScaler

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:

Python, continues from the cells above
from sklearn.preprocessing import MinMaxScaler

minmax = MinMaxScaler()
X_train_minmax = minmax.fit_transform(X_train)
X_test_minmax = minmax.transform(X_test)

knn_minmax = KNeighborsClassifier()
knn_minmax.fit(X_train_minmax, y_train)

print(round(knn_minmax.score(X_test_minmax, y_test), 4))
print(round(roc_auc_score(y_test, knn_minmax.predict_proba(X_test_minmax)[:, 1]), 4))

Output

0.8235
0.7359

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.

Try it yourself

This task continues from the cells of Parts 6 and 7. Take the test customer at position 11. Print the classes of his 5 nearest training customers as a list, then predict_proba, then his true class.
Show a hint
customer = X_test_scaled[[11]], distances, positions = knn.kneighbors(customer), then y_train.iloc[positions[0]].tolist(), knn.predict_proba(customer) and y_test.iloc[11].
Show the solution
Python, continues from the cells above
customer = X_test_scaled[[11]]

distances, positions = knn.kneighbors(customer)

print(y_train.iloc[positions[0]].tolist())
print(knn.predict_proba(customer))
print(y_test.iloc[11])

Output

[0, 1, 1, 1, 1]
[[0.2 0.8]]
1

Try it yourself

This task continues from the cells of Parts 6 and 7. Train a model with k = 15 on the min-max scaled data (X_train_minmax). Print its test accuracy and its test AUC, rounded to 4 decimals. Is it still below the standard scaler?
Show a hint
model = KNeighborsClassifier(n_neighbors=15), model.fit(X_train_minmax, y_train), then score and roc_auc_score on X_test_minmax.
Show the solution
Python, continues from the cells above
model = KNeighborsClassifier(n_neighbors=15)
model.fit(X_train_minmax, y_train)

print(round(model.score(X_test_minmax, y_test), 4))
print(round(roc_auc_score(y_test, model.predict_proba(X_test_minmax)[:, 1]), 4))

Output

0.8205
0.7582

8Choosing k and the other hyperparameters

8.1k from 1 to 51

Python, continues from the cells above
for k in [1, 3, 5, 7, 11, 15, 21, 31, 51]:
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train_scaled, y_train)
    train_acc = round(model.score(X_train_scaled, y_train), 4)
    test_acc = round(model.score(X_test_scaled, y_test), 4)
    print(k, train_acc, test_acc)

Output

1 1.0 0.802
3 0.897 0.832
5 0.8741 0.83
7 0.862 0.8345
11 0.8514 0.838
15 0.847 0.842
21 0.8423 0.84
31 0.8376 0.838
51 0.8303 0.835

Change it and run: add 101 and 301 to the list and run: very large k underfit.

Every line shows k, the training accuracy and the test accuracy.

  • 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.
  • As k grows, the training accuracy falls and the test accuracy rises: the gap closes.
  • 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.

The model of the project with k from 1 to 51 (odd values): the training and the test accuracy.

0.80.9111121314151

k = 5: training accuracy 0.8741, test accuracy 0.83, gap 0.0441.

The upper line: training, teal: test. k = 1 memorises the training customers; as k grows the gap closes.

Python, continues from the cells above
import matplotlib.pyplot as plt

ks = list(range(1, 52, 4))
train_scores = []
test_scores = []

for k in ks:
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train_scaled, y_train)
    train_scores.append(model.score(X_train_scaled, y_train))
    test_scores.append(model.score(X_test_scaled, y_test))

plt.plot(ks, train_scores, marker="o", label="training accuracy")
plt.plot(ks, test_scores, marker="o", label="test accuracy")
plt.xlabel("k (n_neighbors)")
plt.ylabel("accuracy")
plt.title("Small k overfits; the gap closes as k grows")
plt.legend()
plt.show()
Chart: Small k overfits; the gap closes as k grows

8.2k chosen with cross-validation

The test data must not choose k. Cross-validation on the training data does (Topic 23):

Python, continues from the cells above
from sklearn.model_selection import cross_val_score

for k in [5, 11, 15, 21, 31]:
    model = KNeighborsClassifier(n_neighbors=k)
    scores = cross_val_score(model, X_train_scaled, y_train, cv=5)
    print(k, round(scores.mean(), 4))

Output

5 0.8251
11 0.8306
15 0.8329
21 0.8286
31 0.829

Change it and run: change cv=5 to cv=10 and run: k = 15 stays among the best.

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.)

8.3Why an odd k

Python, continues from the cells above
for k in [4, 5, 6]:
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train_scaled, y_train)
    leaving = model.predict_proba(X_test_scaled)[:, 1]
    print(k, (leaving == 0.5).sum())

Output

4 214
5 0
6 151

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.

8.4The model with k = 15

Python, continues from the cells above
knn15 = KNeighborsClassifier(n_neighbors=15)
knn15.fit(X_train_scaled, y_train)

predicted15 = knn15.predict(X_test_scaled)
leaving15 = knn15.predict_proba(X_test_scaled)[:, 1]

print(confusion_matrix(y_test, predicted15))
print(round(knn15.score(X_test_scaled, y_test), 4))
print(round(recall_score(y_test, predicted15), 4))
print(round(f1_score(y_test, predicted15), 4))
print(round(roc_auc_score(y_test, leaving15), 4))

Output

[[1553   54]
 [ 262  131]]
0.842
0.3333
0.4533
0.8036

Change it and run: change n_neighbors=15 to n_neighbors=25 and run.

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.

8.5weights and p

Python, continues from the cells above
for weights in ["uniform", "distance"]:
    for p in [1, 2]:
        model = KNeighborsClassifier(n_neighbors=15, weights=weights, p=p)
        model.fit(X_train_scaled, y_train)
        train_acc = round(model.score(X_train_scaled, y_train), 4)
        test_acc = round(model.score(X_test_scaled, y_test), 4)
        auc = round(roc_auc_score(y_test, model.predict_proba(X_test_scaled)[:, 1]), 4)
        print(weights, p, train_acc, test_acc, auc)

Output

uniform 1 0.8468 0.845 0.8074
uniform 2 0.847 0.842 0.8036
distance 1 1.0 0.8475 0.8095
distance 2 1.0 0.8445 0.8073

Every line shows the weights, p, the training accuracy, the test accuracy and the test AUC.

  • 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.
  • The Manhattan distance (p=1) is a little better than the Euclidean distance here; the differences are small.

8.6More recall: a lower threshold

k-nearest neighbours has no class_weight. But it gives probabilities, and the threshold of 0.5 can be moved, as in Topic 28:

Python, continues from the cells above
predicted_03 = (leaving15 >= 0.3).astype(int)

print(round(recall_score(y_test, predicted_03), 4))
print(round(precision_score(y_test, predicted_03), 4))
print(round(f1_score(y_test, predicted_03), 4))

Output

0.5598
0.514
0.5359

Change it and run: change 0.3 to 0.2 and run: even more recall, less precision.

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.

8.7Fewer, better features

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?

Python, continues from the cells above
columns = ["age", "active_member", "products_number", "balance", "country_Germany", "gender"]

scaler_few = StandardScaler()
X_train_few = scaler_few.fit_transform(X_train[columns])
X_test_few = scaler_few.transform(X_test[columns])

knn_few = KNeighborsClassifier(n_neighbors=15)
knn_few.fit(X_train_few, y_train)

print(round(knn_few.score(X_test_few, y_test), 4))
print(round(roc_auc_score(y_test, knn_few.predict_proba(X_test_few)[:, 1]), 4))

Output

0.861
0.8422

Change it and run: remove "gender" from the list and run.

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.

8.8The scores of every model

Python, continues from the cells above
models = [
    ("k = 5, unscaled", unscaled, X_test),
    ("k = 5", knn, X_test_scaled),
    ("k = 5, MinMaxScaler", knn_minmax, X_test_minmax),
    ("k = 15", knn15, X_test_scaled),
    ("k = 15, six features", knn_few, X_test_few),
]

for name, model, X_part in models:
    acc = round(model.score(X_part, y_test), 4)
    auc = round(roc_auc_score(y_test, model.predict_proba(X_part)[:, 1]), 4)
    print(name, acc, auc)

Output

k = 5, unscaled 0.764 0.5373
k = 5 0.83 0.7604
k = 5, MinMaxScaler 0.8235 0.7359
k = 15 0.842 0.8036
k = 15, six features 0.861 0.8422

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.

Python, continues from the cells above
import matplotlib.pyplot as plt

names = [name for name, model, X_part in models]
aucs = [roc_auc_score(y_test, model.predict_proba(X_part)[:, 1]) for name, model, X_part in models]

plt.barh(names, aucs)
plt.xlim(0.5, 0.9)
plt.xlabel("test AUC")
plt.title("Scaling, k and the features")
plt.show()
Chart: Scaling, k and the features

What the comparison shows:

  • Without scaling the model is close to guessing.
  • Scaling makes it useful; a well chosen k makes it better.
  • Leaving out useless features helps k-nearest neighbours most of all.

Try it yourself

This task continues from the cells of Parts 6 and 7. Train a model with k = 7 and weights="distance". Print its test accuracy and its test AUC, rounded to 4 decimals.
Show a hint
model = KNeighborsClassifier(n_neighbors=7, weights="distance"), fit on the scaled data, then score and roc_auc_score.
Show the solution
Python, continues from the cells above
model = KNeighborsClassifier(n_neighbors=7, weights="distance")
model.fit(X_train_scaled, y_train)

print(round(model.score(X_test_scaled, y_test), 4))
print(round(roc_auc_score(y_test, model.predict_proba(X_test_scaled)[:, 1]), 4))

Output

0.8355
0.7777

Try it yourself

This task continues from the cells of Parts 6 to 8. Predict "leaves" when the probability of knn15 is at least 0.4 (leaving15 holds it). Print the recall and the precision, rounded to 4 decimals. Compare with 0.5 and 0.3.
Show a hint
predicted_04 = (leaving15 >= 0.4).astype(int), then recall_score and precision_score.
Show the solution
Python, continues from the cells above
predicted_04 = (leaving15 >= 0.4).astype(int)

print(round(recall_score(y_test, predicted_04), 4))
print(round(precision_score(y_test, predicted_04), 4))

Output

0.4809
0.5888

Try it yourself

This task continues from the cells of Parts 6 and 7. Print the mean accuracy of a 5-fold cross-validation of a model with k = 15 and p=1 (the Manhattan distance), rounded to 4 decimals. Compare it with 0.8329 for the Euclidean distance.
Show a hint
cross_val_score(KNeighborsClassifier(n_neighbors=15, p=1), X_train_scaled, y_train, cv=5).mean().
Show the solution
Python, continues from the cells above
from sklearn.model_selection import cross_val_score

model = KNeighborsClassifier(n_neighbors=15, p=1)
scores = cross_val_score(model, X_train_scaled, y_train, cv=5)

print(round(scores.mean(), 4))

Output

0.8305

9The workflow, step by step

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns10,000 customers, 12 columns
2. Checkmissing values, repeated rows, text columnsnothing missing; two text columns
3. Dropcolumns without informationcustomer_id
4. Targetthe share of each class20 percent left: unbalanced
5. Outliersfind them, decidereal customers, kept
6. Encodetext to numbersgender 0 and 1, country one-hot, products_number a number
7. Splittraining and test data8,000 and 2,000
8. Scaleessential for distances; fitted on the training dataStandardScaler
9. Modelk-nearest neighboursk = 5: accuracy 0.83, AUC 0.76
10. Look insidethe neighbours of one customertwo of five left: probability 0.4
11. Measuresconfusion matrix, precision, recall, F1, AUCrecall only 0.37
12. Tunek with cross-validation; odd k; weights, pk = 15: accuracy 0.842, AUC 0.80
13. Thresholdfor more recall0.3: recall 0.56
14. Featuresfewer, useful featuressix features: AUC 0.84

Try it yourself

(a) Which step must come before scaling: the split or the model? (b) On which data is the scaler fitted? (c) Which k did cross-validation choose? (d) Which change gave the highest AUC?

Show a hint
Look at Steps 7, 8, 12 and 14 of the table.
Show the solution

Answer: (a) the split; (b) the training data; (c) 15; (d) fewer, useful features.

The scaler learns its means and spreads from the training data only, so the split comes first. Leaving out five useless features gave the AUC 0.84.

10Common mistakes

Common mistakes
MistakeWhy it is wrongRight
Training k-nearest neighbours on unscaled features.The feature with the largest numbers decides every distance.StandardScaler, fitted on the training data.
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.
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.
Choosing an even k for two classes.Votes can tie, and ties are broken by a rule unrelated to the data.An odd k.
Choosing k with the test data.The test data then helps to build the model.Cross-validation on the training data.
Encoding countries as 0, 1, 2.It invents distances between countries.One-hot encoding.
Leaving an identification number or useless features in.They add noise to every distance.Drop them; choose useful features.
Expecting class_weight to fix unbalanced classes.KNeighborsClassifier has none.Move the threshold of the probability (Topic 28).
Leaving missing values in.A distance cannot be computed with a gap.Fill them first.
Expecting fast predictions on big data.Every prediction measures the distance to all training rows.Use fewer rows or features, or another model.

11Solved problems

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.

Problem 1: The vote

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?

Idea. Sort by distance, take the k nearest, count (Part 2).

Sorted: 0.5 (stayed), 0.9 (left), 1.2 (left), 1.5 (left), 2.0 (stayed). With k=3k = 3: two left, one stayed.

share that left=23=0.667\text{share that left} = \frac{2}{3} = 0.667

Why: (a) the nearest customer stayed: "stays". (b) Two of the three nearest left: "leaves". (c) 0.667. One neighbour more changes the answer.

Problem 2: Two distances

Find the Euclidean and the Manhattan distance between the scaled customers (1, -2, 0.5) and (3, 1, 0.5).

Idea. The differences are 2, 3 and 0 (Part 3).

Euclidean:22+32+02=13=3.606Manhattan:2+3+0=5\begin{aligned} \text{Euclidean:}\quad & \sqrt{2^2 + 3^2 + 0^2} = \sqrt{13} = 3.606 \\[6pt] \text{Manhattan:}\quad & 2 + 3 + 0 = 5 \end{aligned}

Why: the Manhattan distance is never smaller than the Euclidean distance; it walks along each feature instead of going straight.

Problem 3: Scaling

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.

Idea. The feature with the larger numbers dominates without scaling (Part 3).

without scaling:52+30,0002=30,000.0scaled:(510)2+(30,00060,000)2=0.25+0.25=0.5=0.707\begin{aligned} & \text{without scaling:} \\[4pt] & \sqrt{5^2 + 30{,}000^2} = 30{,}000.0 \\[10pt] & \text{scaled:} \\[4pt] & \sqrt{\left(\tfrac{5}{10}\right)^2 + \left(\tfrac{30{,}000}{60{,}000}\right)^2} \\[4pt] &= \sqrt{0.25 + 0.25} = \sqrt{0.5} = 0.707 \end{aligned}

Why: without scaling the age changes nothing at all; after scaling both differences are half a spread and count equally.

Problem 4: Choosing k

A training set has 6,400 customers, 80 percent of whom stayed. (a) What is the rule-of-thumb k≈nk \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?

Idea. The square root of n; odd k for two classes; the largest k gives the largest class (Part 4).

6,400=80\sqrt{6{,}400} = 80

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.

Problem 5: Read and check

Read the file. Print its shape, the number of missing values and the share of customers who left, rounded to 4 decimals.

Idea. The first steps of the workflow (Part 6).

Python
import pandas as pd

df = pd.read_csv("Bank Customer Churn Prediction.csv")

print(df.shape)
print(df.isna().sum().sum())
print(round(df["churn"].mean(), 4))

Output

(10000, 12)
0
0.2037

Why: nothing to fill, which k-nearest neighbours requires, and one customer in five left.

Problem 6: Drop and encode

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.

Idea. Text to numbers; one-hot keeps all countries equally far apart (Part 6).

Python, continues from the cells above
df = df.drop(columns=["customer_id"])
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)

print(len(df.columns))

Output

12

Why: eleven features and the target.

Problem 7: Split

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.

Idea. The split comes before the scaler learns anything.

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["churn"])
y = df["churn"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)

print(X_train.shape, X_test.shape)

Output

(7500, 11) (2500, 11)

Why: 7,500 customers to search for neighbours and 2,500 to judge with.

Problem 8: Scale

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.

Idea. Fit on training, transform both (Part 6).

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(abs(round(X_train_scaled[:, 0].mean(), 2)))
print(round(X_train_scaled[:, 0].std(), 2))

Output

0.0
1.0

Why: a mean of 0 and a standard deviation of 1 on the training data. (abs turns a possible -0.0 into 0.0.)

Problem 9: The default model

Train a KNeighborsClassifier with its default settings on the scaled data. Print its training accuracy and its test accuracy, rounded to 4 decimals.

Idea. k = 5 (Part 7).

Python, continues from the cells above
from sklearn.neighbors import KNeighborsClassifier

knn = KNeighborsClassifier()
knn.fit(X_train_scaled, y_train)

print(round(knn.score(X_train_scaled, y_train), 4))
print(round(knn.score(X_test_scaled, y_test), 4))

Output

0.8696
0.8264

Why: the training accuracy is higher: each training customer is among its own five neighbours.

Problem 10: The neighbours of one customer

For the first test customer, print the classes of his 5 nearest training customers as a list, then predict_proba.

Idea. kneighbors gives the positions of the neighbours in the training data (Part 7).

Python, continues from the cells above
customer = X_test_scaled[[0]]

distances, positions = knn.kneighbors(customer)

print(y_train.iloc[positions[0]].tolist())
print(knn.predict_proba(customer))

Output

[0, 0, 1, 0, 1]
[[0.6 0.4]]

Why: the share of the 1s in the list is the second number of predict_proba.

Problem 11: The measures

Print the confusion matrix, the recall and the AUC of knn, the last two rounded to 4 decimals.

Idea. The measures of Topic 28; the AUC needs the probabilities.

Python, continues from the cells above
from sklearn.metrics import confusion_matrix, recall_score, f1_score, roc_auc_score

predicted = knn.predict(X_test_scaled)

print(confusion_matrix(y_test, predicted))
print(round(recall_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, knn.predict_proba(X_test_scaled)[:, 1]), 4))

Output

[[1880  110]
 [ 324  186]]
0.3647
0.773

Why: a fair accuracy hides a low recall: most leaving customers are missed.

Problem 12: k against the test accuracy

For k = 1, 15 and 51, print k, the training accuracy and the test accuracy, rounded to 4 decimals.

Idea. Small k overfits, very large k underfits (Part 8).

Python, continues from the cells above
for k in [1, 15, 51]:
    model = KNeighborsClassifier(n_neighbors=k)
    model.fit(X_train_scaled, y_train)
    print(k, round(model.score(X_train_scaled, y_train), 4), round(model.score(X_test_scaled, y_test), 4))

Output

1 1.0 0.7892
15 0.8456 0.834
51 0.8293 0.83

Why: k = 1 has a perfect training score and the lowest test score; the gap closes as k grows.

Problem 13: k with cross-validation

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.

Idea. The test data does not choose k (Part 8).

Python, continues from the cells above
from sklearn.model_selection import cross_val_score

for k in [5, 15, 25]:
    scores = cross_val_score(KNeighborsClassifier(n_neighbors=k), X_train_scaled, y_train, cv=5)
    print(k, round(scores.mean(), 4))

Output

5 0.8264
15 0.8296
25 0.8293

Why: k = 5 is clearly below the two larger values, which are close to each other.

Problem 14: The model with k = 15

Train a model with k = 15, called knn15. Print its test accuracy, its recall and its AUC, rounded to 4 decimals.

Idea. The k chosen in the lesson (Part 8).

Python, continues from the cells above
knn15 = KNeighborsClassifier(n_neighbors=15)
knn15.fit(X_train_scaled, y_train)

leaving15 = knn15.predict_proba(X_test_scaled)[:, 1]

print(round(knn15.score(X_test_scaled, y_test), 4))
print(round(recall_score(y_test, knn15.predict(X_test_scaled)), 4))
print(round(roc_auc_score(y_test, leaving15), 4))

Output

0.834
0.302
0.8094

Why: a higher accuracy and AUC than k = 5, but a lower recall: more neighbours outvote the leavers more often.

Problem 15: A lower threshold

Predict "leaves" when the probability of knn15 is at least 0.3. Print the recall and the F1-score, rounded to 4 decimals.

Idea. No class_weight, but a movable threshold (Topic 28).

Python, continues from the cells above
predicted_03 = (leaving15 >= 0.3).astype(int)

print(round(recall_score(y_test, predicted_03), 4))
print(round(f1_score(y_test, predicted_03), 4))

Output

0.5549
0.5365

Why: the recall rises sharply, and the F1-score with it.

Problem 16: Scaled against unscaled

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.

Idea. Distances need scaled features (Part 3).

Python, continues from the cells above
raw = KNeighborsClassifier(n_neighbors=15)
raw.fit(X_train, y_train)

print(round(roc_auc_score(y_test, raw.predict_proba(X_test)[:, 1]), 4))
print(round(roc_auc_score(y_test, leaving15), 4))

Output

0.519
0.8094

Why: unscaled, the AUC is little better than guessing; scaled, it is clearly useful.

12Practice

Sixteen problems. The first four are solved on paper. Problems 5 to 16 are one project in Python on Bank Customer Churn Prediction.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the file to a tuned model. Under every problem there is a hint and a solution.

12.1Group A: by hand

  1. 1.A new customer has the distances 1.1, 0.4, 2.3, 0.8, 1.6, 0.9 and 2.0 to seven training customers, who left, stayed, left, left, stayed, stayed and left. (a) What is predicted with k=3k = 3? (b) What is predict_proba for leaving with k=5k = 5? Give 1 decimal. (c) What happens with k=4k = 4?

    Show a hint
    Sort the distances first.
    Show one possible solution

    Answer: (a) stays; (b) 0.4; (c) a tie.

    Sorted: 0.4 (stayed), 0.8 (left), 0.9 (stayed), 1.1 (left), 1.6 (stayed), 2.0 (left), 2.3 (left). With k=3k = 3 one left and two stayed: "stays".

    k=5:25=0.4k = 5:\quad \frac{2}{5} = 0.4

    With k=4k = 4 two left and two stayed: a tie.

  2. 2.Find the Euclidean and the Manhattan distance between (2,0,−1)(2, 0, -1) and (−1,4,−1)(-1, 4, -1).

    Show a hint
    The differences are 3, 4 and 0.
    Show one possible solution

    Answer: Euclidean 5; Manhattan 7.

    Euclidean:32+42+02=25=5Manhattan:3+4+0=7\begin{aligned} \text{Euclidean:}\quad & \sqrt{3^2 + 4^2 + 0^2} = \sqrt{25} = 5 \\[6pt] \text{Manhattan:}\quad & 3 + 4 + 0 = 7 \end{aligned}
  3. 3.Two customers differ by 30 years of age and by 6,000 euros of balance; the standard deviations are 10 years and 60,000 euros. (a) Which difference decides the unscaled distance? (b) What is the scaled distance? Give 3 decimals.

    Show a hint
    Divide each difference by its standard deviation, then use the Euclidean formula.
    Show one possible solution

    Answer: (a) the balance; (b) 3.002.

    unscaled:302+6,0002=6,000.075scaled:3010=3,6,00060,000=0.132+0.12=9.01=3.002\begin{aligned} \text{unscaled:}\quad & \sqrt{30^2 + 6{,}000^2} = 6{,}000.075 \\[8pt] \text{scaled:}\quad & \tfrac{30}{10} = 3, \quad \tfrac{6{,}000}{60{,}000} = 0.1 \\[4pt] & \sqrt{3^2 + 0.1^2} = \sqrt{9.01} = 3.002 \end{aligned}

    After scaling the age difference, three spreads, is the large one.

  4. 4.(a) Which setting makes close neighbours vote more? (b) Which value of p gives the Manhattan distance? (c) Does KNeighborsClassifier need a random_state? (d) Is a training accuracy of 1.0 with k=1k = 1 a good sign?

    Show a hint
    Look at the table of hyperparameters and at "Small k, large k".
    Show one possible solution

    Answer: (a) weights="distance"; (b) 1; (c) no; (d) no.

    Nothing in the model is random. With k=1k = 1 every training customer is its own nearest neighbour, so the training accuracy says nothing about new customers.

12.2Group B: one project in Python

The same workflow as in the lesson, on the same file, with another split: test_size=0.3 with random_state=1. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created.

Steps 5 to 8: from the file to the split

Read the file, drop and encode, split.

  1. 5.Read Bank Customer Churn Prediction.csv into df. Print the shape, then the number of customers who left.
    Show a hint
    df = pd.read_csv("Bank Customer Churn Prediction.csv"), then print(df.shape) and print(df["churn"].sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("Bank Customer Churn Prediction.csv")
    
    print(df.shape)
    print(df["churn"].sum())

    Output

    (10000, 12)
    2037
  2. 6.Drop the column customer_id and encode gender as 0 (Female) and 1 (Male). Print the number of men. This step continues from Step 5.
    Show a hint
    df = df.drop(columns=["customer_id"]) and df["gender"] = df["gender"].map({"Female": 0, "Male": 1}). The men are the rows with 1: print(df["gender"].sum()).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop(columns=["customer_id"])
    df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
    
    print(df["gender"].sum())

    Output

    5457
  3. 7.One-hot encode country inside the table, with drop_first=True and dtype=int. Print the number of columns.
    Show a hint
    df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int), then print(len(df.columns)).
    Show one possible solution
    Python, continues from the cells above
    df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)
    
    print(len(df.columns))

    Output

    12
  4. 8.Make X (all columns without churn) and y. Split them with test_size=0.3 and random_state=1. Print the number of test customers, then how many of them left.
    Show a hint
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1), then len(y_test) and y_test.sum().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["churn"])
    y = df["churn"]
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    
    print(len(y_test))
    print(y_test.sum())

    Output

    3000
    627

Steps 9 to 12: scaling, the model and its measures

The scaler fitted on the training data, k-nearest neighbours, the confusion matrix, recall, F1 and AUC.

  1. 9.Fit a StandardScaler on X_train and scale both parts into X_train_scaled and X_test_scaled. Print the mean of the scaled test ages (column position 2), rounded to 4 decimals.
    Show a hint
    scaler.fit_transform(X_train) and scaler.transform(X_test); then X_test_scaled[:, 2].mean().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.preprocessing import StandardScaler
    
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    
    print(round(X_test_scaled[:, 2].mean(), 4))

    Output

    -0.0071
  2. 10.Train a KNeighborsClassifier called knn with its default settings on the scaled data. Print its test accuracy, rounded to 4 decimals.
    Show a hint
    knn = KNeighborsClassifier(), knn.fit(X_train_scaled, y_train), then knn.score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.neighbors import KNeighborsClassifier
    
    knn = KNeighborsClassifier()
    knn.fit(X_train_scaled, y_train)
    
    print(round(knn.score(X_test_scaled, y_test), 4))

    Output

    0.82
  3. 11.Put the predictions of knn for the test customers into predicted and print the confusion matrix.
    Show a hint
    predicted = knn.predict(X_test_scaled), then print(confusion_matrix(y_test, predicted)).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import confusion_matrix
    
    predicted = knn.predict(X_test_scaled)
    
    print(confusion_matrix(y_test, predicted))

    Output

    [[2243  130]
     [ 410  217]]
  4. 12.Print the recall, the F1-score and the AUC of knn, each rounded to 4 decimals.
    Show a hint
    recall_score and f1_score with (y_test, predicted); roc_auc_score with knn.predict_proba(X_test_scaled)[:, 1].
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import recall_score, f1_score, roc_auc_score
    
    print(round(recall_score(y_test, predicted), 4))
    print(round(f1_score(y_test, predicted), 4))
    print(round(roc_auc_score(y_test, knn.predict_proba(X_test_scaled)[:, 1]), 4))

    Output

    0.3461
    0.4456
    0.7547

Steps 13 to 16: choosing k and a lower threshold

Cross-validation, the model with k = 15, a threshold of 0.3, and the test accuracy for many k with a chart.

  1. 13.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.
    Show a hint
    A loop over [5, 15, 25]; cross_val_score(KNeighborsClassifier(n_neighbors=k), X_train_scaled, y_train, cv=5), then .mean().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import cross_val_score
    
    for k in [5, 15, 25]:
        scores = cross_val_score(KNeighborsClassifier(n_neighbors=k), X_train_scaled, y_train, cv=5)
        print(k, round(scores.mean(), 4))

    Output

    5 0.8281
    15 0.8324
    25 0.8314
  2. 14.Train a model with k = 15, called knn15. Print its test accuracy and its AUC, rounded to 4 decimals.
    Show a hint
    knn15 = KNeighborsClassifier(n_neighbors=15), fit; the AUC from knn15.predict_proba(X_test_scaled)[:, 1].
    Show one possible solution
    Python, continues from the cells above
    knn15 = KNeighborsClassifier(n_neighbors=15)
    knn15.fit(X_train_scaled, y_train)
    
    print(round(knn15.score(X_test_scaled, y_test), 4))
    print(round(roc_auc_score(y_test, knn15.predict_proba(X_test_scaled)[:, 1]), 4))

    Output

    0.8277
    0.7967
  3. 15.Predict "leaves" when the probability of knn15 is at least 0.3. Print the recall and the precision, rounded to 4 decimals.
    Show a hint
    (knn15.predict_proba(X_test_scaled)[:, 1] >= 0.3).astype(int), then recall_score and precision_score.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import precision_score
    
    predicted_03 = (knn15.predict_proba(X_test_scaled)[:, 1] >= 0.3).astype(int)
    
    print(round(recall_score(y_test, predicted_03), 4))
    print(round(precision_score(y_test, predicted_03), 4))

    Output

    0.5407
    0.5512
  4. 16.For k = 1, 3, 5, ..., 29, compute the test accuracy. Print the highest of these accuracies, rounded to 4 decimals, then draw the test accuracy against k as a line.
    Show a hint
    ks = list(range(1, 30, 2)); append each score to a list; max(...); plt.plot(ks, accuracies) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import matplotlib.pyplot as plt
    
    ks = list(range(1, 30, 2))
    accuracies = []
    
    for k in ks:
        model = KNeighborsClassifier(n_neighbors=k)
        model.fit(X_train_scaled, y_train)
        accuracies.append(model.score(X_test_scaled, y_test))
    
    print(round(max(accuracies), 4))
    
    plt.plot(ks, accuracies, marker="o")
    plt.xlabel("k")
    plt.ylabel("test accuracy")
    plt.show()

    Output

    0.8297
    The chart this code draws

13Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.What does KNeighborsClassifier do in fit?

Question 2

2.How does k-nearest neighbours classify a new row?

Question 3

3.Why must the features be scaled for k-nearest neighbours?

Question 4

4.With k = 1, the training accuracy is 1.0. What does this mean?

Question 5

5.Why is an odd k chosen for two classes?

Question 6

6.What happens when k equals the number of training rows?

Question 7

7.Which p of the Minkowski distance gives the Manhattan distance?

Question 8

8.How should k be chosen?

Question 9

9.What does weights="distance" change?

Question 10

10.Why can useless features hurt k-nearest neighbours?

Question 11

11.KNeighborsClassifier has no class_weight. How can its recall be raised?

Question 12

12.How should country be encoded for k-nearest neighbours?

0 of 12 answered.

14Summary

Summary
Formula or ruleMeaning
Euclidean distance(x1−y1)2+(x2−y2)2+…\sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2 + \dots}the straight line; p=2, the default
Manhattan distancethe sum of the absolute differencesalong each feature; p=1
Predictionthe majority class of the k nearest rowspredict_proba is the share of the votes
Weighted voteeach vote counts 1distance\frac{1}{\text{distance}}weights="distance"
Small klow bias, high variancek = 1 memorises: training accuracy 1.0
Large khigh bias, low variancek = n always predicts the largest class
Rule of thumbk≈nk \approx \sqrt{n}, odd for two classesthen cross-validation
Summary
CodeWhat it does
KNeighborsClassifier(n_neighbors=15)k-nearest neighbours with k = 15
weights="distance", p=1weighted votes, Manhattan distance
StandardScaler().fit_transform(X_train), then transform(X_test)the scaling the model needs
knn.kneighbors(row)the distances and positions of the k nearest training rows
knn.predict_proba(X)[:, 1]the share of the neighbours of class 1
(probabilities >= 0.3).astype(int)a lower threshold for more recall
cross_val_score(knn, X_train_scaled, y_train, cv=5)choosing k without the test data

Rules to keep

  1. k-nearest neighbours stores the training rows and votes with the k nearest; the share of the votes is the probability.
  2. Always scale the features, with the scaler fitted on the training data.
  3. Small k overfits, large k underfits; choose an odd k with cross-validation.
  4. One-hot encode categories, fill missing values, look at outliers, and drop useless features.
  5. Without class_weight, raise the recall by lowering the threshold.
  6. Predictions are slow on large data: every prediction measures all the distances.

What comes next

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.