Module 3, topic 33, week 17, Tuesday
k-Nearest Neighbors - Regression
The neighbours of Topic 32 for a number: the mean and the weighted mean of the k nearest prices, why k need not be odd, what a large k and a small k do, and why a few useful features matter more than anything else, on the raw car adverts from the first line of preprocessing to the measures.
Lesson notebook
The lesson as a Jupyter notebook: the car project cell by cell, from the raw file and every preprocessing step to k, the weights, nine features and the measures, and the sixteen solved problems.
topic-33-k-nearest-neighbors-regression.ipynb, 59 KB
Practice notebook
The same project on the car adverts in twelve steps, from reading the raw file and scaling to a tuned model on nine features, with a hint and a hidden solution for each step.
topic-33-practice.ipynb, 19 KB
Data file: the car adverts
10,000 adverts of cars for sale in Azerbaijan with 19 columns, the file of Topic 31: drawn at random from a public data set of car adverts (Kaggle) and translated into English, without any data about the sellers. Not cleaned: repeated adverts, missing values and impossible values are still in it.
car_prices.csv, 965 KB
Introduction: the price of the neighbours
The thirteenth lesson of Module 3. Topic 32 used k-nearest neighbours to predict a class: will a customer leave the bank? This lesson uses the same idea to predict a number: the price of a car. The neighbours no longer vote; the model takes the mean of their prices.
Almost everything else is the same as in Topic 32: the distances, the need for scaling, the hyperparameters, the choice of k with cross-validation. This lesson recalls those parts in one or two sentences and points to the place in Topic 32. The time goes to what is new when the target is a number:
- the prediction as the mean (or the weighted mean) of the neighbours' values, worked by hand;
- why an odd k does not matter any more, and what a very large k predicts;
- the measures of regression: R², MAE and RMSE (Topic 22);
- a data set with many one-hot columns, where the choice of the features decides almost everything (the curse of dimensionality, seen clearly);
- what k-nearest neighbours cannot predict.
The data is car_prices.csv, the 10,000 car adverts of Topic 31, again from the raw file: every preprocessing step is done in the lesson.
You need: k-nearest neighbours for classes (Topic 32), linear regression and the measures R², MAE and RMSE (Topic 22), the train/test split, cross-validation and overfitting (Topic 23), scaling and encoding (Topics 24 and 25), and the cleaning of the car data (Topic 31).
What you will learn
- 1.What stays the same and what changes when k-nearest neighbours predicts a number
- 2.How it predicts: the mean of the k nearest training values, plain or weighted by distance
- 3.Why an odd k is not needed for regression, and what a very small and a very large k do
- 4.The hyperparameters of
KNeighborsRegressor - 5.Why scaling and the choice of the features matter even more with many one-hot columns
- 6.What k-nearest neighbours cannot predict
- 7.A whole project on the raw car data: from the file to a tuned model and its measures
| Word | Meaning |
|---|---|
| k-nearest neighbours regression | a model that predicts a number as the mean of the values of the k most similar training rows |
| Weighted mean | a mean in which close neighbours count more: each value is weighted by |
| R² | the share of the variance of the target that the model explains (Topic 22) |
| MAE | mean absolute error: the typical error, in manats |
| RMSE | root mean squared error: in manats too, large errors count more |
| Curse of dimensionality | with many features, all rows become almost equally far apart, and "nearest" loses its meaning |
| Extrapolation | predicting outside the range of the training data; k-nearest neighbours cannot do it |
1From a class to a number
1.1What stays the same
| Idea | In short | Where in Topic 32 |
|---|---|---|
| Lazy learner | fit only stores the training rows; all the work happens in predict | Part 1 |
| The k nearest | for a new row, measure the distance to every training row and take the k smallest | Part 2 |
| Distances | Euclidean (p=2, the default), Manhattan (p=1), Minkowski | Part 3 |
| Scaling is essential | without it the feature with the largest numbers decides every distance | Part 3 |
| Hyperparameters | n_neighbors, weights, metric, p, algorithm, leaf_size, n_jobs; no random_state | Part 4 |
| Small k overfits, large k underfits | k = 1 memorises the training data; the gap closes as k grows | Part 4 |
| k is chosen with cross-validation | never with the test data | Part 4 |
| Preprocessing | scaling, one-hot encoding, filled gaps, a look at outliers, no useless features | Part 5 |
If one of these is not clear, read its place in Topic 32 first: this lesson uses all of them.
1.2What changes
| Classification (Topic 32) | Regression (this topic) | |
|---|---|---|
| Target | a class: leaves or stays | a number: the price of a car |
| The k neighbours | vote | give their values |
| The prediction | the class with the most votes | the mean of the neighbours' values |
predict_proba | the share of the votes | does not exist |
weights="distance" | a weighted vote | a weighted mean |
| Odd k | needed for two classes, to avoid ties | not needed: a mean never ties |
| A very large k | always predicts the largest class | always predicts the mean of all training values |
| Measures | accuracy, recall, F1, AUC (Topic 28) | R², MAE, RMSE (Topic 22) |
| In scikit-learn | KNeighborsClassifier | KNeighborsRegressor |
1.3Where k-nearest neighbours regression is used
- Prices: what similar flats, houses or cars sold for (the project of this lesson).
- Recommendations with a score: the rating a user would give a film, from the ratings of similar users.
- Filling missing numbers:
KNNImputerfills a gap with the mean of the nearest rows (Topic 32). - Science and engineering: a measurement estimated from the most similar earlier measurements, for example the energy use of a building from similar buildings.
- As a simple baseline: a quick model to compare the others with.
Try it yourself
KNeighborsRegressor predict from the k nearest training rows? (b) Does it have predict_proba? (c) Must k be odd for regression? (d) What does it predict when k is the number of training rows?Show a hint
Show the solution
Answer: (a) the mean of their values; (b) no; (c) no; (d) the mean of all training values.
A mean of k numbers is one number: there are no votes, no probabilities and no ties.
2How it predicts: an example with eight cars
Eight cars, described by two features: their age in years and their engine volume in litres. The target is the price in thousands of manats.
| Car | Age (years) | Engine (litres) | Price (thousand AZN) |
|---|---|---|---|
| A | 2 | 2.0 | 30 |
| B | 3 | 1.6 | 22 |
| C | 5 | 2.0 | 18 |
| D | 8 | 1.6 | 10 |
| E | 1 | 3.0 | 45 |
| F | 6 | 2.5 | 20 |
| G | 10 | 1.4 | 6 |
| H | 4 | 1.8 | 24 |
A new car N is 4 years old and has a 2.0-litre engine. What is its price?
2.1Step 1: the distances
Exactly as in Topic 32, the Euclidean distance. For N = (4, 2.0) and H = (4, 1.8):
For N and B = (3, 1.6):
All eight, from the nearest to the farthest:
| Rank | Car | Distance | Price |
|---|---|---|---|
| 1 | H | 24 | |
| 2 | C | 18 | |
| 3 | B | 22 | |
| 4 | A | 30 | |
| 5 | F | 20 | |
| 6 | E | 45 | |
| 7 | D | 10 | |
| 8 | G | 6 |
- the 3 nearest
- the other cars
- the new car N
2.2Step 2: the mean of the k nearest
| k | The k nearest | Their prices | Prediction |
|---|---|---|---|
| 1 | H | 24 | 24 |
| 3 | H, C, B | 24, 18, 22 | |
| 5 | H, C, B, A, F | 24, 18, 22, 30, 20 | |
| 8 | all eight | all prices |
With k = 3:
N is predicted at about 21,333 manats. Four lessons are in this table:
- The answer depends on k, as for classes.
- k = 1 copies one car. N gets exactly H's price, with every accident of H's advert: overfitting.
- k = all eight gives the mean of all training prices, 21.875, for every new car whatever its age or engine: the model has stopped looking at the features. That is underfitting, the regression version of "always the largest class".
- No ties. A mean is always one number, so k = 2, 4 or 8 is as good a choice as an odd k. The rule "odd k" of Topic 32 was only about votes.
2.3The weighted mean
H is five times closer to N than C. With weights="distance" each price is weighted by :
The very close H pulls the prediction towards its own price, 24. The weighted mean trusts close cars more than far ones, which is often right for prices. Its weakness is the same as in Topic 32: every training car is its own neighbour at the distance 0, so the training R² becomes almost 1 and says nothing.
Choose k and the kind of mean. The ringed cars are the k nearest to N; the prediction is the mean of their prices.
The 3 nearest: H (distance 0.2, price 24), C (distance 1, price 18), B (distance 1.077, price 22).
Prediction for N: 21.333 thousand manats.
Even k is fine: a mean never ties. Try k = 1, 3, 5 and 8.
2.4A second kind of tie
Two training cars can be at exactly the same distance at the edge of the k nearest. scikit-learn then takes the car that comes first in the training data, as in Topic 32. In real data with many cars that have the same year, engine and mileage, this happens more often than one would think.
Try it yourself
weights="distance"? Give 3 decimals.Show a hint
Show the solution
Answer: (a) 20.667; (b) 23; (c) 19.231.
An even k such as 4 gives one number, as every k does. The weighted mean is pulled towards the closer car (20).
3The hyperparameters, and what is different for regression
KNeighborsRegressor has the same hyperparameters as KNeighborsClassifier (Topic 32, Part 4):
| Hyperparameter | Default | Role in regression |
|---|---|---|
n_neighbors | 5 | k, the number of neighbours whose values are averaged. Small: overfitting; large: underfitting, up to the mean of all training values. |
weights | "uniform" | "uniform": a plain mean. "distance": a mean weighted by . |
metric, p | "minkowski", 2 | the distance: Euclidean with p=2, Manhattan with p=1 |
algorithm, leaf_size | "auto", 30 | how the neighbours are searched: speed only |
n_jobs | None | processor cores for the search |
There is no random_state (nothing is random), no class_weight and no predict_proba (there are no classes).
3.1Choosing k for regression
- Even or odd does not matter: a mean cannot tie.
- A first guess of is again only a starting point; on the car data a small k is better.
- Cross-validation chooses k (Topic 23), and here it also chooses
weightsand the features. - The training score with k = 1 or with
weights="distance"is close to 1 and means nothing.
3.2Small and large k in one picture
- k = 1
- k = 25
The picture uses only the year of 300 cars. With k = 1 the prediction jumps from the price of one car to the price of the next: every accident of a single advert is copied. With k = 25 it is a smooth curve: the mean of 25 cars of about the same year. After the newest year in the data both lines are flat, which is the next point.
A model that knows only the year of 300 cars. Choose k and watch its prediction curve.
k = 1: the curve jumps from one car's price to the next: overfitting.
Every curve is flat after the newest year: a mean of training prices cannot go further.
3.3What k-nearest neighbours cannot predict
A prediction is a mean of training prices. A mean is never higher than the highest of its values. So, exactly like the random forest of Topic 31, k-nearest neighbours cannot predict outside the range of the training prices: a new car newer or more expensive than all training cars gets about the price of the most similar training cars. With k = 5 it is even stricter: a prediction is a mean of five prices, so it can reach the most expensive training price only if the five nearest cars are all that expensive.
Which hyperparameter is it?
1 of 6
With 1 every prediction copies one training car; with the number of rows every prediction is the mean of all prices.
Try it yourself
KNeighborsRegressor is k? (b) Which setting gives a weighted mean? (c) The training prices lie between 1,200 and 160,000 manats. Can the model predict 170,000? (d) Does algorithm change the predictions?Show a hint
Show the solution
Answer: (a) n_neighbors; (b) weights="distance"; (c) no; (d) no.
A prediction is a mean of training prices and stays inside their range. The search algorithm changes only the speed.
4Preprocessing for k-nearest neighbours regression, and for the models still to come
The rules of Topic 32 (Part 5) hold, and the car data shows two of them more strongly than the bank data:
- Scaling: essential. The mileage is counted in hundreds of thousands of kilometres, the engine in litres. Without scaling, the mileage decides every distance alone.
- Encoding: needed, but it brings many columns. One-hot encoding of eight text columns gives 83 features, most of them 0 or 1. After scaling, every one of them counts in the distance as much as the year.
- Useless features and the curse of dimensionality. With 83 features, two cars that are alike in year, engine and mileage can still look far apart because they differ in colour, city and market. The true neighbours are hidden. For k-nearest neighbours the choice of a few useful features is often the largest improvement of all (Part 7).
- Missing values: must be filled. A distance cannot be computed with a gap. The training medians fill them after the split, as in Topic 31.
- Repeated rows and impossible values. A repeated advert in the training and the test data would be its own nearest neighbour; it is dropped before the split. A year 0 would make a car far from everything; such rows are removed (Topic 31).
- Outliers in the target. A very expensive car pulls the mean of its neighbours up; with a small k one such neighbour changes a prediction a lot. They are real cars and stay.
| 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; few, useful columns | 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 preprocessing and the model into one object, so that every step is fitted on the right rows.
Try it yourself
Show a hint
Show the solution
Answer: (a) yes; (b) useless columns add noise to every distance; (c) it finds itself as its neighbour; (d) yes.
Scaling makes every feature count in units of its spread; useless columns hide the similar cars; a copy in the test data gets its own price; real expensive cars are part of the market.
5The project: from the raw file to the scaled data
Now the data: car_prices.csv, the 10,000 car adverts of Topic 31.
The data file: car_prices.csv
10,000 car adverts, 19 columns, not cleaned: repeated adverts, missing values and impossible values are still in it. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
The file is the raw data: the repeated adverts, the missing values, the impossible values, the outliers and the text columns are all still in it. Every step is done again and explained as if it were new; Topic 31 (Part 6) gives the longer reasons for each one. The cells continue from each other like the cells of a notebook.
5.1Step 1: read and look
import pandas as pd
df = pd.read_csv("car_prices.csv")
print(df.shape)
print(df.head())Output
(10000, 19)
brand model year engine_l ... painted market city price_azn
0 Mercedes C 220 d 2002 2.2 ... 0 NaN Sumgait 11800
1 Changan Uni-Z 2024 1.5 ... 0 NaN Sumgait 41400
2 Volkswagen Passat 2014 1.8 ... 0 America other 14900
3 Toyota Prius 2008 1.5 ... 0 Japan Baku 13700
4 BMW 528 1999 2.8 ... 0 NaN Baku 8500
[5 rows x 19 columns]10,000 adverts and 19 columns: the brand and model, the year, the engine volume and horsepower, the fuel, the mileage, the gearbox, the driven wheels, the body, the colour, the seats, the owners, three yes/no columns (new, damaged, painted), the market, the city, and the target price_azn, the price in manats.
5.2Step 2: check
print(df.isna().sum().sum())
print(df.duplicated().sum())Output
12240 691
Missing values in several columns, and 691 adverts that appear twice.
5.3Step 3: drop the repeated rows
df = df.drop_duplicates()
print(df.shape)Output
(9309, 19)
For k-nearest neighbours a repeated advert is the worst kind of leak: if one copy lands in the training data and the other in the test data, the test copy finds itself as its nearest neighbour at the distance 0 and gets its own price.
5.4Step 4: remove the impossible rows
df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)]
print(df.shape)Output
(9259, 19)
A year 0 and a mileage of three million kilometres are mistakes in the adverts (Topic 31, Steps 4 and 5).
5.5Step 5: drop the column with too many categories
print(df["model"].nunique())
df = df.drop(columns=["model"])Output
797
797 different models would become 796 one-hot columns: far too many for a model that measures distances.
5.6Step 6: the target
print(df["price_azn"].describe().round(0))Output
count 9259.0 mean 23399.0 std 14083.0 min 1200.0 25% 13500.0 50% 21600.0 75% 29900.0 max 160000.0 Name: price_azn, dtype: float64
Prices from 1,200 to 160,000 manats; the mean is above the median, because a few expensive cars pull it up. They are real cars and stay.
The features have outliers too:
for column in ["mileage_km", "engine_l", "horsepower"]:
q1 = df[column].quantile(0.25)
q3 = df[column].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)
print(column, upper, (df[column] > upper).sum())Output
mileage_km 489516.25 238 engine_l 3.1000000000000005 710 horsepower 287.5 218
Hundreds of cars with a long mileage, a large engine or a strong motor: real taxis, trucks and sports cars. For k-nearest neighbours they matter more than for a forest (Topic 32, Part 5): after scaling, a 15-litre truck is far from almost every car, and its neighbours are the few other trucks. That is right, so they stay; but they also stretch the scale of their feature for everybody else.
5.7Step 7: group the rare brands and fill the missing market
counts = df["brand"].value_counts()
rare = counts[counts < 50].index
df.loc[df["brand"].isin(rare), "brand"] = "other"
df["market"] = df["market"].fillna("unknown")
print(df["brand"].nunique())
print((df["market"] == "unknown").sum())Output
19 2869
Brands with fewer than 50 cars become "other", and a missing market becomes a category of its own.
5.8Step 8: encode
text_columns = ["brand", "fuel", "gearbox", "drive", "body", "colour", "market", "city"]
df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)
print(df.shape)Output
(9259, 84)
83 features and the target. Keep this number in mind: for k-nearest neighbours every one of these columns takes part in every distance.
5.9Step 9: split
from sklearn.model_selection import train_test_split
X = df.drop(columns=["price_azn"])
y = df["price_azn"]
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
(7407, 83) (1852, 83)
Change it and run: change test_size to 0.3 and run: about 2,780 cars become test data.
7,407 cars for training (the neighbours that will be searched) and 1,852 for the test, the same cars as in Topic 31.
5.10Step 10: fill the missing numbers with the training medians
medians = X_train[["horsepower", "seats", "owners"]].median()
X_train = X_train.fillna(medians)
X_test = X_test.fillna(medians)
print(X_train.isna().sum().sum(), X_test.isna().sum().sum())Output
0 0
k-nearest neighbours cannot measure a distance with a gap. The medians come from the training cars only (Topic 23).
5.11Step 11: scale
print(X_train[["year", "engine_l", "mileage_km"]].std().round(1))Output
year 7.6 engine_l 1.0 mileage_km 127831.5 dtype: float64
The mileage spreads about 100,000 times more than the engine volume: without scaling it would decide every distance alone.
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)Output
(7407, 83) (1852, 83)
The scaler learns the mean and the standard deviation of every feature from the training cars and applies them to both parts (Topic 24).
6The model
6.1Train and judge
from sklearn.neighbors import KNeighborsRegressor
knn = KNeighborsRegressor()
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.7572 0.6447
Change it and run: write KNeighborsRegressor(n_neighbors=1) and run: the training R² becomes almost 1.
KNeighborsRegressor lives in sklearn.neighbors, next to the classifier, and score gives the R². With k = 5 and all 83 features the model explains about 64 percent of the variance of the test prices: far below the random forest of Topic 31 (0.865 on the same test cars). The rest of the lesson finds out why, and how to do better.
6.2The measures of regression
from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error
predicted = knn.predict(X_test_scaled)
print(round(r2_score(y_test, predicted), 4))
print(round(mean_absolute_error(y_test, predicted)))
print(round(root_mean_squared_error(y_test, predicted)))Output
0.6447 5201 8357
A typical error of about 5,200 manats (the MAE), and an RMSE of about 8,400: some cars are predicted very badly.
6.3How it predicts one car
car = X_test_scaled[[0]]
distances, positions = knn.kneighbors(car)
print(distances.round(3))
print(y_train.iloc[positions[0]].tolist())
print(knn.predict(car))
print(y_test.iloc[0])Output
[[0.61 0.859 0.894 0.913 0.925]] [27400, 27500, 23700, 23900, 23500] [25200.] 42500
Change it and run: change both [[0]] and iloc[0] to the position 5 and look at the neighbours of another car.
The five nearest training cars, their distances and their prices. The prediction, 25,200 manats, is exactly the mean of the five prices. The car really costs 42,500: its five "nearest" cars all cost between 23,500 and 27,500. With 83 features, the cars that are nearest in all columns together are not necessarily the most similar in what decides a price.
6.4How much do the neighbours agree?
The five prices say more than their mean. When they are close to each other, the neighbours agree and the prediction is trustworthy; when they spread widely, it is not. Their standard deviation (Topic 18) measures it:
import numpy as np
prices = y_train.iloc[positions[0]]
print(round(np.std(prices)))Output
1842
The five prices of this car lie close together (a spread of about 1,800 manats), and yet the true price is far away: the neighbours agree with each other, but they are the wrong neighbours. A small spread is a good sign only when the features that decide the distance are the right ones; Part 7 comes back to this.
6.5Without scaling
unscaled = KNeighborsRegressor()
unscaled.fit(X_train, y_train)
print(round(unscaled.score(X_test, y_test), 4))Output
0.3878
On the unscaled features the R² falls to 0.39: the neighbours were chosen almost only by the mileage, the feature with the largest numbers.
6.6The model cannot go beyond the training prices
print(y_train.max())
print(round(predicted.max()))Output
160000 85060
The most expensive training car costs 160,000 manats, but the highest prediction for a test car is far below it: a mean of five prices is pulled towards the middle.
Try it yourself
Show a hint
car = X_test_scaled[[1]], distances, positions = knn.kneighbors(car), then y_train.iloc[positions[0]].tolist(), knn.predict(car) and y_test.iloc[1].Show the solution
car = X_test_scaled[[1]]
distances, positions = knn.kneighbors(car)
print(y_train.iloc[positions[0]].tolist())
print(knn.predict(car))
print(y_test.iloc[1])Output
[21800, 20900, 19500, 29368, 19400] [22193.6] 19300
7Choosing k, the features and the other hyperparameters
7.1k from 1 to 51
for k in [1, 3, 5, 7, 10, 15, 25, 51]:
model = KNeighborsRegressor(n_neighbors=k)
model.fit(X_train_scaled, y_train)
train_r2 = round(model.score(X_train_scaled, y_train), 4)
test_r2 = round(model.score(X_test_scaled, y_test), 4)
print(k, train_r2, test_r2)Output
1 0.9991 0.5933 3 0.8204 0.6469 5 0.7572 0.6447 7 0.7221 0.6291 10 0.685 0.6134 15 0.6496 0.5881 25 0.6071 0.5544 51 0.5612 0.5183
Change it and run: add 101 and 501 to the list and run: very large k drift towards the mean.
Every line shows k, the training R² and the test R².
- k = 1 has a training R² of almost 1 (not exactly 1: a few training cars have exactly the same features but different prices) and a low test R²: overfitting.
- The test R² is highest around k = 3 to 5, then falls: with many neighbours the prediction drifts towards the mean of all prices.
- k = 10 (even) is a perfectly good value here: there is nothing to tie.
The car model of the project with k from 1 to 51: the training and the test R², with all features or with nine.
k = 5 with 83 features: training R² 0.7572, test R² 0.6447.
The upper line: training, teal: test. With nine features the test R² is about 0.15 higher for almost every k: the useless columns hid the true neighbours.
import matplotlib.pyplot as plt
ks = [1, 2, 3, 5, 7, 10, 15, 20, 30, 40, 51]
train_scores = []
test_scores = []
for k in ks:
model = KNeighborsRegressor(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 R²")
plt.plot(ks, test_scores, marker="o", label="test R²")
plt.xlabel("k (n_neighbors)")
plt.ylabel("R²")
plt.title("Small k overfits; large k drifts towards the mean")
plt.legend()
plt.show()
7.2k chosen with cross-validation
from sklearn.model_selection import cross_val_score
for k in [3, 5, 7, 10, 15]:
model = KNeighborsRegressor(n_neighbors=k)
scores = cross_val_score(model, X_train_scaled, y_train, cv=5)
print(k, round(scores.mean(), 4))Output
3 0.5818 5 0.5975 7 0.5983 10 0.5871 15 0.5795
For a regressor cross_val_score uses the R² by default. k = 5 and k = 7 are about equally good, and both are far below the random forest.
7.3weights and p
for weights in ["uniform", "distance"]:
for p in [1, 2]:
model = KNeighborsRegressor(n_neighbors=5, weights=weights, p=p)
model.fit(X_train_scaled, y_train)
train_r2 = round(model.score(X_train_scaled, y_train), 4)
test_r2 = round(model.score(X_test_scaled, y_test), 4)
print(weights, p, train_r2, test_r2)Output
uniform 1 0.7928 0.6892 uniform 2 0.7572 0.6447 distance 1 0.9996 0.7153 distance 2 0.9996 0.6727
Every line shows the weights, p, the training R² and the test R². Both changes help: the weighted mean trusts the closest cars more, and the Manhattan distance (p=1) is less dominated by a single large difference. Each alone lifts the test R² from 0.64 to about 0.67 or 0.69; together they reach 0.72. With weights="distance" the training R² is almost 1 again: ignore it.
7.4Fewer, better features
The real problem is the 83 features. Which ones matter for a price? The random forest of Topic 31 found the year, the engine volume, the horsepower and the mileage most important, then a few yes/no columns. Take only these nine:
columns = ["year", "engine_l", "horsepower", "mileage_km", "is_new", "gearbox_manual", "drive_front", "fuel_petrol", "body_sedan"]
scaler_few = StandardScaler()
X_train_few = scaler_few.fit_transform(X_train[columns])
X_test_few = scaler_few.transform(X_test[columns])
knn_few = KNeighborsRegressor()
knn_few.fit(X_train_few, y_train)
print(round(knn_few.score(X_test_few, y_test), 4))Output
0.8051
Change it and run: remove "body_sedan" and "fuel_petrol" from the list and run.
With nine features instead of 83 the test R² jumps from 0.64 to 0.81, with the same k = 5. The 74 columns that were left out (colours, cities, markets, rare body types, most brands) were noise in every distance: two cars of the same year, engine and mileage looked far apart because one was white and the other black. This is the curse of dimensionality, and on this data it is the most important lesson of the topic. (A real project would choose the features with cross-validation, without the test data; Topic 42 shows tools for it.)
7.5k and weights on the nine features
for k in [3, 5, 7, 10, 15]:
model = KNeighborsRegressor(n_neighbors=k, weights="distance")
scores = cross_val_score(model, X_train_few, y_train, cv=5)
print(k, round(scores.mean(), 4))Output
3 0.7867 5 0.7962 7 0.7988 10 0.7963 15 0.7941
On the nine features, with the weighted mean, k = 7 has the highest cross-validated R².
7.6The tuned model
tuned = KNeighborsRegressor(n_neighbors=7, weights="distance")
tuned.fit(X_train_few, y_train)
tuned_predicted = tuned.predict(X_test_few)
print(round(r2_score(y_test, tuned_predicted), 4))
print(round(mean_absolute_error(y_test, tuned_predicted)))
print(round(root_mean_squared_error(y_test, tuned_predicted)))Output
0.8195 3300 5958
Change it and run: change n_neighbors=7 to n_neighbors=10 and run.
The tuned model explains 82 percent of the variance of the test prices, with a typical error of about 3,300 manats: much better than the 0.64 and 5,200 of the first model. The random forest of Topic 31 is still a little better (R² 0.865 with its defaults), because trees choose their own features at every split and are not disturbed by useless ones.
import matplotlib.pyplot as plt
plt.scatter(y_test, tuned_predicted, s=6, alpha=0.5)
plt.plot([0, 160000], [0, 160000], color="gray")
plt.xlabel("true price (AZN)")
plt.ylabel("predicted price (AZN)")
plt.title("The tuned model: predicted against true prices")
plt.show()
Most cars lie close to the grey line of perfect predictions. The expensive cars lie below it: few training cars are as expensive, so their neighbours are cheaper and the mean is too low.
7.7The scores of every model
models = [
("k = 5, unscaled", unscaled, X_test),
("k = 5, 83 features", knn, X_test_scaled),
("k = 5, nine features", knn_few, X_test_few),
("k = 7, distance, nine features", tuned, X_test_few),
]
for name, model, X_part in models:
model_predicted = model.predict(X_part)
r2 = round(r2_score(y_test, model_predicted), 4)
mae = round(mean_absolute_error(y_test, model_predicted))
print(name, r2, mae)Output
k = 5, unscaled 0.3878 7683 k = 5, 83 features 0.6447 5201 k = 5, nine features 0.8051 3472 k = 7, distance, nine features 0.8195 3300
Every line shows a model, its test R² and its MAE on the same 1,852 cars. Each model gets the test data in the form it was trained on.
import matplotlib.pyplot as plt
names = [name for name, model, X_part in models]
r2s = [r2_score(y_test, model.predict(X_part)) for name, model, X_part in models]
plt.barh(names, r2s)
plt.xlim(0, 0.9)
plt.xlabel("test R²")
plt.title("Scaling, the features and k")
plt.show()
What the comparison shows:
- Without scaling the model is poor.
- Scaling helps, but 83 features keep it far from good.
- Choosing nine useful features is the largest step; the weighted mean and a tuned k add the last part.
Try it yourself
Show a hint
[4, 6]; KNeighborsRegressor(n_neighbors=k), fit on the scaled data, then score on the test data.Show the solution
for k in [4, 6]:
model = KNeighborsRegressor(n_neighbors=k)
model.fit(X_train_scaled, y_train)
print(k, round(model.score(X_test_scaled, y_test), 4))Output
4 0.6386 6 0.6331
Try it yourself
year, engine_l, horsepower and mileage_km with a new scaler, train a default model on them and print its test R², rounded to 4 decimals.Show a hint
four = ["year", "engine_l", "horsepower", "mileage_km"]; a new StandardScaler() with fit_transform(X_train[four]) and transform(X_test[four]); then KNeighborsRegressor().Show the solution
four = ["year", "engine_l", "horsepower", "mileage_km"]
scaler_four = StandardScaler()
X_train_four = scaler_four.fit_transform(X_train[four])
X_test_four = scaler_four.transform(X_test[four])
model = KNeighborsRegressor()
model.fit(X_train_four, y_train)
print(round(model.score(X_test_four, y_test), 4))Output
0.7233
Try it yourself
weights="distance" and p=1 on the nine features (X_train_few). Print its test R² rounded to 4 decimals, then its MAE as a whole number.Show a hint
KNeighborsRegressor(n_neighbors=7, weights="distance", p=1), fit(X_train_few, y_train), then r2_score and mean_absolute_error on X_test_few.Show the solution
model = KNeighborsRegressor(n_neighbors=7, weights="distance", p=1)
model.fit(X_train_few, y_train)
model_predicted = model.predict(X_test_few)
print(round(r2_score(y_test, model_predicted), 4))
print(round(mean_absolute_error(y_test, model_predicted)))Output
0.8262 3228
8The workflow, step by step
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 10,000 adverts, 19 columns |
| 2. Check | missing values, repeated rows | gaps in four columns, 691 copies |
| 3. Repeated rows | drop them before the split | a copy would be its own neighbour |
| 4. Impossible values | remove them | year 0, three million kilometres |
| 5. Too many categories | drop | model (797 values) |
| 6. Target | its range and outliers | real expensive cars, kept |
| 7. Rare categories, missing text | group, fill | brands under 50 cars, market "unknown" |
| 8. Encode | one-hot | 83 features |
| 9. Split | training and test data | 7,407 and 1,852 |
| 10. Missing numbers | training medians, after the split | horsepower, seats, owners |
| 11. Scale | essential for distances | StandardScaler |
| 12. Model | k-nearest neighbours, k = 5 | R² 0.64 |
| 13. Tune | k, weights, p with cross-validation | R² about 0.72 |
| 14. Features | a few useful ones | nine features: R² 0.81 |
| 15. Judge | R², MAE, RMSE on the same test data | tuned: R² 0.82, MAE about 3,300 |
Try it yourself
Show a hint
Show the solution
Answer: (a) dropping the repeated rows; (b) the training data; (c) choosing nine features; (d) the MAE.
Copies go before the split; medians and the scaler come from the training cars; the nine features lifted the R² from 0.64 to 0.81.
9Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Training on unscaled features. | The mileage decides every distance alone. | StandardScaler, fitted on the training data. |
| Keeping repeated rows. | A copy in the test data finds itself as its neighbour. | drop_duplicates() before the split. |
| Using all one-hot columns without thinking. | Useless columns hide the true neighbours. | Choose a few useful features. |
| Choosing an odd k "to avoid ties". | A mean cannot tie; odd and even k are both fine. | Choose k with cross-validation. |
| Trusting a training R² of almost 1. | With k = 1 or weighted means every training car is its own neighbour. | Judge on cross-validation or test data. |
| Choosing k with the test data. | The test data then helps to build the model. | Cross-validation on the training data. |
| Leaving missing values in. | A distance cannot be computed with a gap. | Fill them, with training values, after the split. |
| Expecting predictions above the highest training price. | A prediction is a mean of training prices. | Know the range of the training data. |
| Using accuracy or recall for prices. | They are measures for classes. | R², MAE, RMSE. |
10Solved problems
The first four problems are short and solved by hand. Problems 5 to 16 are one project on car_prices.csv, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.
Problem 1: The mean of the neighbours
A new car has the distances 0.4, 1.3, 0.9, 2.1 and 0.6 to five training cars with the prices 18, 25, 20, 40 and 16 thousand manats. What does k-nearest neighbours predict (a) with k = 1, (b) with k = 3, (c) with k = 5?
Idea. Sort by distance, take the k nearest, take the mean of their prices (Part 2).
Sorted: 0.4 (18), 0.6 (16), 0.9 (20), 1.3 (25), 2.1 (40).
Why: (a) 18 thousand, the price of the nearest car. (b) 18 thousand. (c) 23.8 thousand: the far and expensive car pulls the mean up.
Problem 2: The weighted mean
The three nearest cars have the distances 0.5, 1 and 2 and the prices 20, 30 and 40 thousand manats. Find the prediction with weights="distance".
Idea. Each price is weighted by (Part 2).
Why: the plain mean would be 30 thousand; the weighted mean, 25.714 thousand, is pulled towards the closest car.
Problem 3: A very large k
A training set has 6,000 cars with a mean price of 23,500 manats. What does k-nearest neighbours predict for every new car with k = 6,000? Is this overfitting or underfitting?
Idea. All training cars are neighbours of every new car (Part 2).
Why: 23,500 manats for every car, whatever its age or engine: the model no longer looks at the features. That is underfitting, the regression version of "always the largest class".
Problem 4: Odd or even
(a) Can k = 4 give a tie in k-nearest neighbours regression? (b) In classification with two classes? (c) What does KNeighborsRegressor have instead of predict_proba?
Idea. A mean against a vote (Parts 2 and 3).
Why: (a) No: the mean of four prices is one number. (b) Yes: two neighbours of each class. (c) Nothing: a regressor predicts a number with predict; there are no classes and no probabilities.
Problem 5: Read and check
Read the file. Print its shape, the number of repeated rows and the number of missing values in the whole table.
Idea. The first steps of the workflow (Part 5).
import pandas as pd
df = pd.read_csv("car_prices.csv")
print(df.shape)
print(df.duplicated().sum())
print(df.isna().sum().sum())Output
(10000, 19) 691 12240
Why: copies to drop and gaps to fill before any distance can be measured.
Problem 6: Copies, impossible rows and the model column
Drop the repeated rows, keep only the cars made in 1950 or later with at most 1,000,000 km, and drop the column model. Print the shape.
Idea. Clean before anything else (Part 5).
df = df.drop_duplicates()
df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)]
df = df.drop(columns=["model"])
print(df.shape)Output
(9259, 18)
Why: 9,259 cars and 18 columns.
Problem 7: Categories and encoding
Group the brands with fewer than 50 cars as "other", fill the missing market with "unknown", and one-hot encode the eight text columns with drop_first=True and dtype=int. Print the number of columns.
Idea. Text to numbers (Part 5).
counts = df["brand"].value_counts()
rare = counts[counts < 50].index
df.loc[df["brand"].isin(rare), "brand"] = "other"
df["market"] = df["market"].fillna("unknown")
text_columns = ["brand", "fuel", "gearbox", "drive", "body", "colour", "market", "city"]
df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)
print(len(df.columns))Output
84
Why: 83 features and the target.
Problem 8: Split and fill
Make X and y, split them with test_size=0.25 and random_state=7, and fill horsepower, seats and owners with the training medians. Print the shapes of X_train and X_test.
Idea. The medians come from the training data, after the split (Part 5).
from sklearn.model_selection import train_test_split
X = df.drop(columns=["price_azn"])
y = df["price_azn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)
medians = X_train[["horsepower", "seats", "owners"]].median()
X_train = X_train.fillna(medians)
X_test = X_test.fillna(medians)
print(X_train.shape, X_test.shape)Output
(6944, 83) (2315, 83)
Why: 6,944 cars to search for neighbours and 2,315 to judge with.
Problem 9: Scale
Fit a StandardScaler on the training data and scale both parts. Print the shape of the scaled training data.
Idea. Fit on training, transform both (Part 5).
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)Output
(6944, 83)
Why: the same 83 columns, now each with the mean 0 and the standard deviation 1 on the training cars.
Problem 10: The default model
Train a KNeighborsRegressor with its default settings on the scaled data. Print its training R² and its test R², rounded to 4 decimals.
Idea. k = 5 (Part 6).
from sklearn.neighbors import KNeighborsRegressor
knn = KNeighborsRegressor()
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.7693 0.6148
Why: a clear gap between training and test, and a test R² far below the random forest.
Problem 11: Its errors in manats
Print the MAE and the RMSE of the model on the test data, as whole numbers.
Idea. The measures of regression (Topic 22).
from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error
predicted = knn.predict(X_test_scaled)
print(round(mean_absolute_error(y_test, predicted)))
print(round(root_mean_squared_error(y_test, predicted)))Output
5347 9237
Why: a typical error of over 5,000 manats.
Problem 12: The neighbours of one car
For the first test car, print the prices of its 5 nearest training cars as a list, then the prediction.
Idea. The prediction is the mean of these prices (Part 6).
car = X_test_scaled[[0]]
distances, positions = knn.kneighbors(car)
print(y_train.iloc[positions[0]].tolist())
print(knn.predict(car))Output
[24900, 22000, 24700, 25500, 26500] [24720.]
Why: the mean of the five prices is the second line.
Problem 13: k with cross-validation
For k = 3, 5 and 10, print k and the mean R² of a 5-fold cross-validation on the scaled training data, rounded to 4 decimals.
Idea. The test data does not choose k (Part 7).
from sklearn.model_selection import cross_val_score
for k in [3, 5, 10]:
scores = cross_val_score(KNeighborsRegressor(n_neighbors=k), X_train_scaled, y_train, cv=5)
print(k, round(scores.mean(), 4))Output
3 0.615 5 0.6177 10 0.6
Why: k = 5 is the best of the three; an even k is as possible as an odd one.
Problem 14: Nine features
Scale only the nine features year, engine_l, horsepower, mileage_km, is_new, gearbox_manual, drive_front, fuel_petrol and body_sedan with a new StandardScaler, train a default KNeighborsRegressor on them, and print its test R², rounded to 4 decimals.
Idea. Fewer, useful features against the curse of dimensionality (Part 7).
columns = ["year", "engine_l", "horsepower", "mileage_km", "is_new", "gearbox_manual", "drive_front", "fuel_petrol", "body_sedan"]
scaler_few = StandardScaler()
X_train_few = scaler_few.fit_transform(X_train[columns])
X_test_few = scaler_few.transform(X_test[columns])
knn_few = KNeighborsRegressor()
knn_few.fit(X_train_few, y_train)
print(round(knn_few.score(X_test_few, y_test), 4))Output
0.7611
Why: far better than with 83 features, with the same k.
Problem 15: The tuned model
Train a model with k = 7 and weights="distance" on the nine features. Print its test R², its MAE and its RMSE, the last two as whole numbers.
Idea. The settings chosen in the lesson (Part 7).
tuned = KNeighborsRegressor(n_neighbors=7, weights="distance")
tuned.fit(X_train_few, y_train)
tuned_predicted = tuned.predict(X_test_few)
print(round(r2_score(y_test, tuned_predicted), 4))
print(round(mean_absolute_error(y_test, tuned_predicted)))
print(round(root_mean_squared_error(y_test, tuned_predicted)))Output
0.7957 3583 6727
Why: the best of the project on this split too.
Problem 16: Scaled against unscaled
Train a default KNeighborsRegressor on the unscaled nine features. Print its test R² and the test R² of knn_few, rounded to 4 decimals.
Idea. Scaling matters even with few features (Part 4).
raw = KNeighborsRegressor()
raw.fit(X_train[columns], y_train)
print(round(raw.score(X_test[columns], y_test), 4))
print(round(knn_few.score(X_test_few, y_test), 4))Output
0.4159 0.7611
Why: without scaling the mileage decides alone, even among nine features.
11Practice
Sixteen problems. The first four are solved on paper. Problems 5 to 16 are one project in Python on car_prices.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the raw file to a tuned model. Under every problem there is a hint and a solution.
11.1Group A: by hand
- 1.A new car has the distances 1.2, 0.3, 0.8, 2.5 and 0.5 to five training cars with the prices 30, 12, 16, 50 and 14 thousand manats. (a) What is predicted with ? (b) With ?
Show a hint
Sort the distances first; then take the mean of the k nearest prices.Show one possible solution
Answer: (a) 14; (b) 18.
Sorted: 0.3 (12), 0.5 (14), 0.8 (16), 1.2 (30), 2.5 (50).
- 2.The two nearest cars have the distances 0.25 and 1 and the prices 20 and 30 thousand manats. Find the prediction with (a) as a plain mean, (b) as a weighted mean.
Show a hint
The weights are and .Show one possible solution
Answer: (a) 25; (b) 22.
- 3.(a) A training set has 5,000 cars with a mean price of 24,000 manats. What is predicted for every car with ? (b) The most expensive training car costs 90,000 manats. Can k-nearest neighbours predict 100,000?
Show a hint
With all cars as neighbours the prediction is their mean; every prediction is a mean of training prices.Show one possible solution
Answer: (a) 24,000; (b) no.
The mean of all training prices for every car is underfitting. A mean of prices up to 90,000 cannot exceed 90,000.
- 4.(a) Must k be odd in k-nearest neighbours regression? (b) Which setting makes close cars count more? (c) Why can useless one-hot columns hurt k-nearest neighbours?
Show a hint
A mean cannot tie; every feature takes part in every distance.Show one possible solution
Answer: (a) no; (b)
weights="distance"; (c) they add noise to every distance.A mean of k values is always one number. Each value is weighted by . Columns that say nothing about the price hide the truly similar cars.
11.2Group B: one project in Python
The same workflow as in the lesson, on the same raw 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 raw file to the split
Read the file, drop the copies, the impossible rows and the model column, the categories and the encoding, the split.
- 5.Read
car_prices.csvintodf. Print the shape, then the number of repeated rows.Show a hint
df = pd.read_csv("car_prices.csv"), thenprint(df.shape)andprint(df.duplicated().sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("car_prices.csv") print(df.shape) print(df.duplicated().sum())Output
(10000, 19) 691
- 6.Drop the repeated rows, keep only the cars made in 1950 or later with at most 1,000,000 km, and drop the column
model. Print the number of rows. This step continues from Step 5.Show a hint
df = df.drop_duplicates(), thendf = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)], thendf.drop(columns=["model"])andlen(df).Show one possible solution
Python, continues from the cells abovedf = df.drop_duplicates() df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)] df = df.drop(columns=["model"]) print(len(df))Output
9259
- 7.Group the brands with fewer than 50 cars as
"other", fill the missingmarketwith"unknown", and one-hot encode the columns oftext_columnswithdrop_first=Trueanddtype=int. Print the number of columns.Show a hint
counts = df["brand"].value_counts(),rare = counts[counts < 50].index,df.loc[df["brand"].isin(rare), "brand"] = "other"; thenfillna("unknown")andpd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int).Show one possible solution
Python, continues from the cells abovecounts = df["brand"].value_counts() rare = counts[counts < 50].index df.loc[df["brand"].isin(rare), "brand"] = "other" df["market"] = df["market"].fillna("unknown") text_columns = ["brand", "fuel", "gearbox", "drive", "body", "colour", "market", "city"] df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int) print(len(df.columns))Output
84
- 8.Make
X(all columns withoutprice_azn) andy. Split them withtest_size=0.3andrandom_state=1. Print the number of test cars, then their mean price rounded to 1 decimal.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)andround(y_test.mean(), 1).Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import train_test_split X = df.drop(columns=["price_azn"]) y = df["price_azn"] 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(round(y_test.mean(), 1))Output
2778 23117.4
Steps 9 to 12: fill, scale, the model and k
The training medians, the scaler, k-nearest neighbours, the MAE and the RMSE, and three values of k.
- 9.Fill
horsepower,seatsandownersin both parts with the training medians. Then fit aStandardScaleronX_trainand scale both parts intoX_train_scaledandX_test_scaled. Print the shape ofX_test_scaled.Show a hint
medians = X_train[["horsepower", "seats", "owners"]].median(),fillna(medians)on both parts; thenscaler.fit_transform(X_train)andscaler.transform(X_test).Show one possible solution
Python, continues from the cells abovefrom sklearn.preprocessing import StandardScaler medians = X_train[["horsepower", "seats", "owners"]].median() X_train = X_train.fillna(medians) X_test = X_test.fillna(medians) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) print(X_test_scaled.shape)Output
(2778, 83)
- 10.Train a
KNeighborsRegressorcalledknnwith its default settings on the scaled data. Print its test R², rounded to 4 decimals.Show a hint
knn = KNeighborsRegressor(),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 KNeighborsRegressor knn = KNeighborsRegressor() knn.fit(X_train_scaled, y_train) print(round(knn.score(X_test_scaled, y_test), 4))Output
0.6296
- 11.Put the predictions of
knnintopredicted. Print the MAE and the RMSE as whole numbers.Show a hint
predicted = knn.predict(X_test_scaled), thenround(mean_absolute_error(y_test, predicted))and the same withroot_mean_squared_error.Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import mean_absolute_error, root_mean_squared_error predicted = knn.predict(X_test_scaled) print(round(mean_absolute_error(y_test, predicted))) print(round(root_mean_squared_error(y_test, predicted)))Output
5178 8284
- 12.For k = 1, 5 and 25, print k, the training R² and the test R², rounded to 4 decimals.
Show a hint
A loop over[1, 5, 25];KNeighborsRegressor(n_neighbors=k),fit, thenscoreon both parts.Show one possible solution
Python, continues from the cells abovefor k in [1, 5, 25]: model = KNeighborsRegressor(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 0.9991 0.5287 5 0.7554 0.6296 25 0.6021 0.5564
Steps 13 to 16: weights, nine features and the tuned model
A weighted mean with the Manhattan distance, nine useful features, k with cross-validation, and a chart.
- 13.Train a model with k = 5,
weights="distance"andp=1on the scaled data. Print its test R², rounded to 4 decimals.Show a hint
KNeighborsRegressor(n_neighbors=5, weights="distance", p=1),fit, thenscore.Show one possible solution
Python, continues from the cells abovemodel = KNeighborsRegressor(n_neighbors=5, weights="distance", p=1) model.fit(X_train_scaled, y_train) print(round(model.score(X_test_scaled, y_test), 4))Output
0.7048
- 14.Scale only the nine features of
columnswith a newStandardScalerintoX_train_fewandX_test_few, train a defaultKNeighborsRegressorcalledknn_fewon them, and print its test R², rounded to 4 decimals.Show a hint
scaler_few = StandardScaler(),X_train_few = scaler_few.fit_transform(X_train[columns]),X_test_few = scaler_few.transform(X_test[columns]), thenfitandscore.Show one possible solution
Python, continues from the cells abovecolumns = ["year", "engine_l", "horsepower", "mileage_km", "is_new", "gearbox_manual", "drive_front", "fuel_petrol", "body_sedan"] scaler_few = StandardScaler() X_train_few = scaler_few.fit_transform(X_train[columns]) X_test_few = scaler_few.transform(X_test[columns]) knn_few = KNeighborsRegressor() knn_few.fit(X_train_few, y_train) print(round(knn_few.score(X_test_few, y_test), 4))Output
0.7934
- 15.On the nine features, for k = 5, 7 and 10 with
weights="distance", print k and the mean R² of a 5-fold cross-validation, rounded to 4 decimals.Show a hint
A loop over[5, 7, 10];cross_val_score(KNeighborsRegressor(n_neighbors=k, weights="distance"), X_train_few, y_train, cv=5).mean().Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import cross_val_score for k in [5, 7, 10]: scores = cross_val_score(KNeighborsRegressor(n_neighbors=k, weights="distance"), X_train_few, y_train, cv=5) print(k, round(scores.mean(), 4))Output
5 0.7811 7 0.7831 10 0.781
- 16.Train a model with k = 7 and
weights="distance"on the nine features. Print its test R² rounded to 4 decimals, then draw its predicted prices against the true test prices as a scatter plot.Show a hint
tuned.predict(X_test_few);plt.scatter(y_test, tuned_predicted)andplt.show().Show one possible solution
Python, continues from the cells aboveimport matplotlib.pyplot as plt tuned = KNeighborsRegressor(n_neighbors=7, weights="distance") tuned.fit(X_train_few, y_train) tuned_predicted = tuned.predict(X_test_few) print(round(tuned.score(X_test_few, y_test), 4)) plt.scatter(y_test, tuned_predicted, s=6) plt.xlabel("true price (AZN)") plt.ylabel("predicted price (AZN)") plt.show()Output
0.8251

12Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
13Summary
| Formula or rule | Meaning | |
|---|---|---|
| Prediction | the mean of the k nearest training values | no vote, no probability |
| Weighted prediction | with | close neighbours count more |
| Small k | low bias, high variance | k = 1 copies one training row |
| Large k | high bias, low variance | k = n predicts the mean of all training values |
| Odd or even k | both are fine | a mean cannot tie |
| Range | between the smallest and the largest training value | no extrapolation |
| Code | What it does |
|---|---|
KNeighborsRegressor(n_neighbors=7, weights="distance") | the weighted mean of the 7 nearest values |
knn.kneighbors(row) | the distances and positions of the k nearest training rows |
knn.score(X_test, y_test) | the test R² |
r2_score, mean_absolute_error, root_mean_squared_error | the measures of regression |
cross_val_score(knn, X_train_scaled, y_train, cv=5) | k chosen with the R² of five folds |
Rules to keep
- k-nearest neighbours regression predicts the mean (or weighted mean) of the k nearest training values.
- Always scale; drop repeated rows before the split; fill missing values after it with training values.
- Choose a few useful features: with many one-hot columns the true neighbours disappear.
- Choose k with cross-validation; even and odd k are both fine for regression.
- Judge with R², MAE and RMSE on the test data; a training R² near 1 means nothing for this model.
- Predictions stay inside the range of the training values.
What comes next
Topic 34 brings Naive Bayes, a classifier that measures no distances at all: it calculates probabilities with Bayes' rule (Topic 16), feature by feature.