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.
Lesson notebook
The lesson as a Jupyter notebook: the project on the bank data cell by cell, from the file and the scaling to the choice of k and the measures, and the sixteen solved problems.
topic-32-k-nearest-neighbors-classification.ipynb, 66 KB
Practice notebook
The same project on the bank data in twelve steps, from reading the file and scaling to a tuned model and a lower threshold, with a hint and a hidden solution for each step.
topic-32-practice.ipynb, 18 KB
Data file: the bank customers
10,000 customers of a bank with 12 columns, the file of Topics 27 to 30: the data of the lesson, the solved problems and the practice. A public data set (Bank Customer Churn Dataset, Kaggle).
Bank Customer Churn Prediction.csv, 548 KB
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.What k-nearest neighbours is, and where it is used
- 2.How it decides for a new row: distances, the k nearest rows, a vote
- 3.How the distance is measured: Euclidean, Manhattan and Minkowski
- 4.Why scaling is essential for this model, shown by hand and on the bank data
- 5.The hyperparameters of
KNeighborsClassifierand their roles - 6.How to choose k: overfitting with a small k, underfitting with a large k, cross-validation, and why k should be odd
- 7.What scaling, encoding, outliers, missing values and useless features mean for k-nearest neighbours and for the models still to come
- 8.A whole project: from the file to a tuned model and its measures
| Word | Meaning |
|---|---|
| k-nearest neighbours (kNN) | a model that predicts the class of a new row from the classes of the k most similar training rows |
| Neighbour | a training row that is close to the new row |
| k | how many neighbours vote: the main hyperparameter |
| Distance | a number that says how different two rows are; small means similar |
| Euclidean distance | the straight-line distance (Topic 13) |
| Manhattan distance | the sum of the differences along each feature, like walking along the streets of a city grid |
| Majority vote | the class that most of the k neighbours have |
| Lazy learner | a model that does no work when it is trained and all the work when it predicts |
| Curse of dimensionality | with 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:
- Keep all the training rows.
- For a new row, measure its distance to every training row.
- Take the k rows with the smallest distances: the k nearest neighbours.
- 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:
KNNImputerfills 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 | Weaknesses |
|---|---|
| Very simple to understand and to explain | Slow predictions on large data: every prediction measures all distances |
| No training time | Needs the whole training data in memory |
| 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 |
| Works for any number of classes | Useless 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
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
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.
| Customer | Tenure (years) | Products | Left the bank? |
|---|---|---|---|
| A | 4 | 3 | leaves |
| B | 2 | 2 | stays |
| C | 5 | 1 | stays |
| D | 6 | 3 | stays |
| E | 1 | 1 | leaves |
| F | 7 | 4 | leaves |
| G | 8 | 1 | stays |
| H | 2 | 4 | leaves |
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):
For N and C = (5, 1):
The same for all eight customers, sorted from the nearest to the farthest:
| Rank | Customer | Differences | Distance | Left the bank? |
|---|---|---|---|---|
| 1 | A | 0 and 1 | leaves | |
| 2 | C | 1 and 1 | stays | |
| 3 | B | 2 and 0 | stays | |
| 4 | D | 2 and 1 | stays | |
| 5 | H | 2 and 2 | leaves | |
| 6 | E | 3 and 1 | leaves | |
| 7 | F | 3 and 2 | leaves | |
| 8 | G | 4 and 1 | stays |
- left the bank
- stayed
- the 3 nearest, ringed
2.2Step 2: the vote of the k nearest
The prediction depends on how many neighbours vote:
| k | The k nearest | Leave | Stay | Share that left | Prediction |
|---|---|---|---|---|---|
| 1 | A | 1 | 0 | leaves | |
| 3 | A, C, B | 1 | 2 | stays | |
| 5 | A, C, B, D, H | 2 | 3 | stays | |
| 7 | A, C, B, D, H, E, F | 4 | 3 | leaves | |
| 8 | all eight | 4 | 4 | a 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_probagives 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.
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 , so close neighbours count more. For k = 3:
1.207 is more than 1: N still stays, but closer than in the plain vote (one against two).
Try it yourself
predict_proba for leaving with ?Show a hint
Show the solution
Answer: (a) 2; (b) stays; (c) 0.4.
With two neighbours stayed (D and G, both at ) and one left (F): "stays". With F and A left, D, G and C stayed.
3How the distance is measured
3.1Euclidean, Manhattan, Minkowski
For two rows with the features and :
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):
Both are members of one family, the Minkowski distance with a power p:
gives the Manhattan distance, 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.
- Euclidean: √5 = 2.236
- Manhattan: 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:
| Customer | Age | Balance (euros) |
|---|---|---|
| N | 40 | 50,000 |
| P | 41 | 120,000 |
| Q | 60 | 52,000 |
Without scaling:
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):
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
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
Show the solution
Answer: (a) 5; (b) 7; (c) 1; (d) they are equal (0.2 and 0.2).
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
| Hyperparameter | Default | Role |
|---|---|---|
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). |
weights | "uniform" | "uniform": every neighbour has one vote. "distance": a vote counts , so close neighbours count more. |
metric | "minkowski" | how the distance is measured; "euclidean" and "manhattan" can also be named directly |
p | 2 | the 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_size | 30 | a setting of the two tree structures: speed and memory only |
n_jobs | None | how 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:
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.
k = 1
a border around single customers
k = 31
a smooth border
- left / area of "leaves"
- stayed / area of "stays"
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".
k = 1: islands around single customers: overfitting.
Small k: low bias, high variance. Large k: high bias, low variance.
4.4How to choose k
- 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.) - A first guess: a common rule of thumb is , the square root of the number of training rows. For 8,000 rows: . It is only a starting point: on the bank data a smaller k is better.
- 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.
- 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
algorithm="brute" change the predictions?Show a hint
Show the solution
Answer: (a) 1; (b) 50; (c) the largest class; (d) no.
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.
| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |
|---|---|---|---|---|
| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |
| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |
| Decision tree, random forest, bagged trees (29, 30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |
| k-nearest neighbours (32, 33) | essential: distances | needed; one-hot for categories | sensitive | fill |
| Naive Bayes (34) | not needed for the usual Gaussian form | needed | sensitive | fill |
| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive | fill |
| 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 |
| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |
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
country be encoded? (c) What must be done with missing values? (d) Do useless features help, hurt or change nothing?Show a hint
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.
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
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
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
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
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
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
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
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
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).
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
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
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
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?
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:
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
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
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
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
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
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.
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.
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()
8.2k chosen with cross-validation
The test data must not choose k. Cross-validation on the training data does (Topic 23):
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
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
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
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:
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?
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
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.
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()
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
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
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
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
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
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
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
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 10,000 customers, 12 columns |
| 2. Check | missing values, repeated rows, text columns | nothing missing; two text columns |
| 3. Drop | columns without information | customer_id |
| 4. Target | the share of each class | 20 percent left: unbalanced |
| 5. Outliers | find them, decide | real customers, kept |
| 6. Encode | text to numbers | gender 0 and 1, country one-hot, products_number a number |
| 7. Split | training and test data | 8,000 and 2,000 |
| 8. Scale | essential for distances; fitted on the training data | StandardScaler |
| 9. Model | k-nearest neighbours | k = 5: accuracy 0.83, AUC 0.76 |
| 10. Look inside | the neighbours of one customer | two of five left: probability 0.4 |
| 11. Measures | confusion matrix, precision, recall, F1, AUC | recall only 0.37 |
| 12. Tune | k with cross-validation; odd k; weights, p | k = 15: accuracy 0.842, AUC 0.80 |
| 13. Threshold | for more recall | 0.3: recall 0.56 |
| 14. Features | fewer, useful features | six features: AUC 0.84 |
Try it yourself
Show a hint
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
| Mistake | Why it is wrong | Right |
|---|---|---|
| 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 : two left, one stayed.
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).
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).
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 ? (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).
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).
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).
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.
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).
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).
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).
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.
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).
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).
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).
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).
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).
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.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 ? (b) What is
predict_probafor leaving with ? Give 1 decimal. (c) What happens with ?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 one left and two stayed: "stays".
With two left and two stayed: a tie.
- 2.Find the Euclidean and the Manhattan distance between and .
Show a hint
The differences are 3, 4 and 0.Show one possible solution
Answer: Euclidean 5; Manhattan 7.
- 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.
After scaling the age difference, three spreads, is the large one.
- 4.(a) Which setting makes close neighbours vote more? (b) Which value of
pgives the Manhattan distance? (c) DoesKNeighborsClassifierneed arandom_state? (d) Is a training accuracy of 1.0 with 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 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.
- 5.Read
Bank Customer Churn Prediction.csvintodf. Print the shape, then the number of customers who left.Show a hint
df = pd.read_csv("Bank Customer Churn Prediction.csv"), thenprint(df.shape)andprint(df["churn"].sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("Bank Customer Churn Prediction.csv") print(df.shape) print(df["churn"].sum())Output
(10000, 12) 2037
- 6.Drop the column
customer_idand encodegenderas 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"])anddf["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 abovedf = df.drop(columns=["customer_id"]) df["gender"] = df["gender"].map({"Female": 0, "Male": 1}) print(df["gender"].sum())Output
5457
- 7.One-hot encode
countryinside the table, withdrop_first=Trueanddtype=int. Print the number of columns.Show a hint
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int), thenprint(len(df.columns)).Show one possible solution
Python, continues from the cells abovedf = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int) print(len(df.columns))Output
12
- 8.Make
X(all columns withoutchurn) andy. Split them withtest_size=0.3andrandom_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), thenlen(y_test)andy_test.sum().Show one possible solution
Python, continues from the cells abovefrom 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.
- 9.Fit a
StandardScaleronX_trainand scale both parts intoX_train_scaledandX_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)andscaler.transform(X_test); thenX_test_scaled[:, 2].mean().Show one possible solution
Python, continues from the cells abovefrom 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
- 10.Train a
KNeighborsClassifiercalledknnwith 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), thenknn.score(X_test_scaled, y_test).Show one possible solution
Python, continues from the cells abovefrom 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
- 11.Put the predictions of
knnfor the test customers intopredictedand print the confusion matrix.Show a hint
predicted = knn.predict(X_test_scaled), thenprint(confusion_matrix(y_test, predicted)).Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import confusion_matrix predicted = knn.predict(X_test_scaled) print(confusion_matrix(y_test, predicted))Output
[[2243 130] [ 410 217]]
- 12.Print the recall, the F1-score and the AUC of
knn, each rounded to 4 decimals.Show a hint
recall_scoreandf1_scorewith(y_test, predicted);roc_auc_scorewithknn.predict_proba(X_test_scaled)[:, 1].Show one possible solution
Python, continues from the cells abovefrom 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.
- 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 abovefrom 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
- 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 fromknn15.predict_proba(X_test_scaled)[:, 1].Show one possible solution
Python, continues from the cells aboveknn15 = 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
- 15.Predict "leaves" when the probability of
knn15is 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), thenrecall_scoreandprecision_score.Show one possible solution
Python, continues from the cells abovefrom 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
- 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 eachscoreto a list;max(...);plt.plot(ks, accuracies)andplt.show().Show one possible solution
Python, continues from the cells aboveimport 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

13Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
14Summary
| Formula or rule | Meaning | |
|---|---|---|
| Euclidean distance | the straight line; p=2, the default | |
| Manhattan distance | the sum of the absolute differences | along each feature; p=1 |
| Prediction | the majority class of the k nearest rows | predict_proba is the share of the votes |
| Weighted vote | each vote counts | weights="distance" |
| Small k | low bias, high variance | k = 1 memorises: training accuracy 1.0 |
| Large k | high bias, low variance | k = n always predicts the largest class |
| Rule of thumb | , odd for two classes | then cross-validation |
| Code | What it does |
|---|---|
KNeighborsClassifier(n_neighbors=15) | k-nearest neighbours with k = 15 |
weights="distance", p=1 | weighted 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
- k-nearest neighbours stores the training rows and votes with the k nearest; the share of the votes is the probability.
- Always scale the features, with the scaler fitted on the training data.
- Small k overfits, large k underfits; choose an odd k with cross-validation.
- One-hot encode categories, fill missing values, look at outliers, and drop useless features.
- Without
class_weight, raise the recall by lowering the threshold. - 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.