Asiman Data School

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.

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. 1.What stays the same and what changes when k-nearest neighbours predicts a number
  2. 2.How it predicts: the mean of the k nearest training values, plain or weighted by distance
  3. 3.Why an odd k is not needed for regression, and what a very small and a very large k do
  4. 4.The hyperparameters of KNeighborsRegressor
  5. 5.Why scaling and the choice of the features matter even more with many one-hot columns
  6. 6.What k-nearest neighbours cannot predict
  7. 7.A whole project on the raw car data: from the file to a tuned model and its measures
The words of this lesson
WordMeaning
k-nearest neighbours regressiona model that predicts a number as the mean of the values of the k most similar training rows
Weighted meana mean in which close neighbours count more: each value is weighted by 1distance\frac{1}{\text{distance}}
R²the share of the variance of the target that the model explains (Topic 22)
MAEmean absolute error: the typical error, in manats
RMSEroot mean squared error: in manats too, large errors count more
Curse of dimensionalitywith many features, all rows become almost equally far apart, and "nearest" loses its meaning
Extrapolationpredicting outside the range of the training data; k-nearest neighbours cannot do it

1From a class to a number

1.1What stays the same

What stays the same
IdeaIn shortWhere in Topic 32
Lazy learnerfit only stores the training rows; all the work happens in predictPart 1
The k nearestfor a new row, measure the distance to every training row and take the k smallestPart 2
DistancesEuclidean (p=2, the default), Manhattan (p=1), MinkowskiPart 3
Scaling is essentialwithout it the feature with the largest numbers decides every distancePart 3
Hyperparametersn_neighbors, weights, metric, p, algorithm, leaf_size, n_jobs; no random_statePart 4
Small k overfits, large k underfitsk = 1 memorises the training data; the gap closes as k growsPart 4
k is chosen with cross-validationnever with the test dataPart 4
Preprocessingscaling, one-hot encoding, filled gaps, a look at outliers, no useless featuresPart 5

If one of these is not clear, read its place in Topic 32 first: this lesson uses all of them.

1.2What changes

What changes
Classification (Topic 32)Regression (this topic)
Targeta class: leaves or staysa number: the price of a car
The k neighboursvotegive their values
The predictionthe class with the most votesthe mean of the neighbours' values
predict_probathe share of the votesdoes not exist
weights="distance"a weighted votea weighted mean
Odd kneeded for two classes, to avoid tiesnot needed: a mean never ties
A very large kalways predicts the largest classalways predicts the mean of all training values
Measuresaccuracy, recall, F1, AUC (Topic 28)R², MAE, RMSE (Topic 22)
In scikit-learnKNeighborsClassifierKNeighborsRegressor

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: KNNImputer fills 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

(a) What does 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
Look at the table "What changes".
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.

How it predicts: an example with eight cars
CarAge (years)Engine (litres)Price (thousand AZN)
A22.030
B31.622
C52.018
D81.610
E13.045
F62.520
G101.46
H41.824

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

distance(N,H)=(4−4)2+(2.0−1.8)2=0+0.04=0.04=0.2\begin{aligned} & \text{distance}(N, H) \\[4pt] &= \sqrt{(4 - 4)^2 + (2.0 - 1.8)^2} \\[4pt] &= \sqrt{0 + 0.04} = \sqrt{0.04} = 0.2 \end{aligned}

For N and B = (3, 1.6):

distance(N,B)=(4−3)2+(2.0−1.6)2=1+0.16=1.16=1.077\begin{aligned} & \text{distance}(N, B) \\[4pt] &= \sqrt{(4 - 3)^2 + (2.0 - 1.6)^2} \\[4pt] &= \sqrt{1 + 0.16} = \sqrt{1.16} = 1.077 \end{aligned}

All eight, from the nearest to the farthest:

Step 1: the distances
RankCarDistancePrice
1H0.04=0.2\sqrt{0.04} = 0.224
2C1=1\sqrt{1} = 118
3B1.16=1.077\sqrt{1.16} = 1.07722
4A4=2\sqrt{4} = 230
5F4.25=2.062\sqrt{4.25} = 2.06220
6E10=3.162\sqrt{10} = 3.16245
7D16.16=4.02\sqrt{16.16} = 4.0210
8G36.36=6.03\sqrt{36.36} = 6.036
1.52.02.53.00246810age (years)engine (litres)A: 30B: 22C: 18D: 10E: 45F: 20G: 6H: 24N: ?
  • the 3 nearest
  • the other cars
  • the new car N
The eight cars by age and engine volume; the size of a dot and its label show the price in thousands of manats. The new car N sits at (4, 2.0). Its three nearest neighbours, H, C and B, are ringed: with k = 3 the model predicts the mean of their prices 24, 18 and 22: 21.333 thousand.

2.2Step 2: the mean of the k nearest

Step 2: the mean of the k nearest
kThe k nearestTheir pricesPrediction
1H2424
3H, C, B24, 18, 2224+18+223=21.333\frac{24 + 18 + 22}{3} = 21.333
5H, C, B, A, F24, 18, 22, 30, 2024+18+22+30+205=22.8\frac{24 + 18 + 22 + 30 + 20}{5} = 22.8
8all eightall prices1758=21.875\frac{175}{8} = 21.875

With k = 3:

prediction=24+18+223=643=21.333\text{prediction} = \frac{24 + 18 + 22}{3} = \frac{64}{3} = 21.333

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 1distance\frac{1}{\text{distance}}:

wH=10.2=5wC=11=1wB=11.077=0.929\begin{aligned} w_H &= \tfrac{1}{0.2} = 5 \\[4pt] w_C &= \tfrac{1}{1} = 1 \\[4pt] w_B &= \tfrac{1}{1.077} = 0.929 \end{aligned}
prediction=5×24+1×18+0.929×225+1+0.929=158.4386.929=22.866\begin{aligned} & \text{prediction} \\[4pt] &= \frac{5 \times 24 + 1 \times 18 + 0.929 \times 22}{5 + 1 + 0.929} \\[4pt] &= \frac{158.438}{6.929} = 22.866 \end{aligned}

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.

1.52.02.53.00246810age (years)engine (litres)A: 30B: 22C: 18D: 10E: 45F: 20G: 6H: 24N: ?

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

Five training cars have the distances 0.5, 1.5, 1, 2 and 0.8 to a new car and the prices 20, 30, 24, 50 and 18 thousand manats. (a) What is the prediction with k=3k = 3? Give 3 decimals. (b) With k=4k = 4? (c) With k=2k = 2 and weights="distance"? Give 3 decimals.

Show a hint
Sorted: 0.5 (20), 0.8 (18), 1 (24), 1.5 (30), 2 (50). The weights for k=2k = 2 are 10.5=2\frac{1}{0.5} = 2 and 10.8=1.25\frac{1}{0.8} = 1.25.
Show the solution

Answer: (a) 20.667; (b) 23; (c) 19.231.

k=3:20+18+243=623=20.667k=4:20+18+24+304=924=23weighted:2×20+1.25×182+1.25=62.53.25=19.231\begin{aligned} k = 3:\quad & \frac{20 + 18 + 24}{3} = \frac{62}{3} = 20.667 \\[8pt] k = 4:\quad & \frac{20 + 18 + 24 + 30}{4} = \frac{92}{4} = 23 \\[8pt] \text{weighted:}\quad & \frac{2 \times 20 + 1.25 \times 18}{2 + 1.25} \\[4pt] & = \frac{62.5}{3.25} = 19.231 \end{aligned}

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

The hyperparameters, and what is different for regression
HyperparameterDefaultRole in regression
n_neighbors5k, 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 1distance\frac{1}{\text{distance}}.
metric, p"minkowski", 2the distance: Euclidean with p=2, Manhattan with p=1
algorithm, leaf_size"auto", 30how the neighbours are searched: speed only
n_jobsNoneprocessor 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

  1. Even or odd does not matter: a mean cannot tie.
  2. A first guess of k≈nk \approx \sqrt{n} is again only a starting point; on the car data a small k is better.
  3. Cross-validation chooses k (Topic 23), and here it also chooses weights and the features.
  4. 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

025507510019952005201520252035no training carsafter this year
  • k = 1
  • k = 25
A model that knows only the year of 300 cars. With k = 1 the prediction jumps from the price of one car to the next; with k = 25 it is a smooth curve, the mean of 25 cars of about the same year. After 2024, the newest year in the data, both are flat: a prediction is always a mean of training prices.

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.

025507510019952005201520252035no training carsafter this year

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

(a) Which hyperparameter of 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
Look at the table of hyperparameters and at "What k-nearest neighbours cannot predict".
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.
Preprocessing for k-nearest neighbours regression, and for the models still to come
Model (topic)ScalingEncoding of textOutliers in the featuresMissing values
Linear regression (22)not needed for the predictionsneededsensitivefill
Ridge, Lasso, logistic regression (26, 27)neededneededsensitivefill
Decision tree, random forest, bagged trees (29, 30, 31)not neededneededrobustfill (recent scikit-learn can handle them)
k-nearest neighbours (32, 33)essential: distancesneeded; few, useful columnssensitivefill
Naive Bayes (34)not needed for the usual Gaussian formneededsensitivefill
Support vector machines, voting (35, 36)needed for the support vector machine; voting as the models insideneededsensitivefill
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robustXGBoost, LightGBM and CatBoost handle them
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitivefill

Topic 42 will put the preprocessing and the model into one object, so that every step is fitted on the right rows.

Try it yourself

(a) Must the features be scaled? (b) Why can 83 one-hot columns hurt? (c) What happens to a repeated advert that is in both the training and the test data? (d) Do very expensive cars stay in the data?

Show a hint
Everything the model does is measuring distances and taking means.
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.

Download

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

Python
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

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

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

print(X_train_scaled.shape, X_test_scaled.shape)

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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

This task continues from the cells of Parts 5 and 6. Take the test car at position 1. Print the prices of its 5 nearest training cars as a list, then the prediction, then its true price.
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
Python, continues from the cells above
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

Python, continues from the cells above
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.

0.40.60.8111121314151

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.

Python, continues from the cells above
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()
Chart: Small k overfits; large k drifts towards the mean

7.2k chosen with cross-validation

Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

Python, continues from the cells above
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()
Chart: The tuned model: predicted against true prices

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

Python, continues from the cells above
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.

Python, continues from the cells above
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()
Chart: Scaling, the features and k

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

This task continues from the cells of Parts 5 and 6. For k = 4 and k = 6 (two even values), print k and the test R², rounded to 4 decimals. Are they worse than the odd values around them?
Show a hint
A loop over [4, 6]; KNeighborsRegressor(n_neighbors=k), fit on the scaled data, then score on the test data.
Show the solution
Python, continues from the cells above
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

This task continues from the cells of Parts 5 and 6. Scale only the four features 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
Python, continues from the cells above
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

This task continues from the cells of Parts 5 to 7. Train a model with k = 7, 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
Python, continues from the cells above
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

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns10,000 adverts, 19 columns
2. Checkmissing values, repeated rowsgaps in four columns, 691 copies
3. Repeated rowsdrop them before the splita copy would be its own neighbour
4. Impossible valuesremove themyear 0, three million kilometres
5. Too many categoriesdropmodel (797 values)
6. Targetits range and outliersreal expensive cars, kept
7. Rare categories, missing textgroup, fillbrands under 50 cars, market "unknown"
8. Encodeone-hot83 features
9. Splittraining and test data7,407 and 1,852
10. Missing numberstraining medians, after the splithorsepower, seats, owners
11. Scaleessential for distancesStandardScaler
12. Modelk-nearest neighbours, k = 5R² 0.64
13. Tunek, weights, p with cross-validationR² about 0.72
14. Featuresa few useful onesnine features: R² 0.81
15. JudgeR², MAE, RMSE on the same test datatuned: R² 0.82, MAE about 3,300

Try it yourself

(a) Which step must come before the split: dropping the repeated rows or filling the missing numbers? (b) On which data are the medians and the scaler fitted? (c) Which single change helped most? (d) Which measure gives the typical error in manats?

Show a hint
Look at Steps 3, 10, 11, 14 and 15 of the table.
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

Common mistakes
MistakeWhy it is wrongRight
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).

k=3:18+16+203=543=18k=5:18+16+20+25+405=1195=23.8\begin{aligned} k = 3:\quad & \frac{18 + 16 + 20}{3} = \frac{54}{3} = 18 \\[8pt] k = 5:\quad & \frac{18 + 16 + 20 + 25 + 40}{5} \\[4pt] & = \frac{119}{5} = 23.8 \end{aligned}

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 1distance\frac{1}{\text{distance}} (Part 2).

weights:10.5=2,11=1,12=0.5prediction=2×20+1×30+0.5×402+1+0.5=903.5=25.714\begin{aligned} \text{weights:}\quad & \tfrac{1}{0.5} = 2, \quad \tfrac{1}{1} = 1, \quad \tfrac{1}{2} = 0.5 \\[8pt] \text{prediction} &= \frac{2 \times 20 + 1 \times 30 + 0.5 \times 40}{2 + 1 + 0.5} \\[4pt] &= \frac{90}{3.5} = 25.714 \end{aligned}

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

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

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

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

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

print(X_train_scaled.shape)

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

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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. 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 k=3k = 3? (b) With k=4k = 4?

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

    k=3:12+14+163=423=14k=4:12+14+16+304=724=18\begin{aligned} k = 3:\quad & \frac{12 + 14 + 16}{3} = \frac{42}{3} = 14 \\[8pt] k = 4:\quad & \frac{12 + 14 + 16 + 30}{4} = \frac{72}{4} = 18 \end{aligned}
  2. 2.The two nearest cars have the distances 0.25 and 1 and the prices 20 and 30 thousand manats. Find the prediction with k=2k = 2 (a) as a plain mean, (b) as a weighted mean.

    Show a hint
    The weights are 10.25=4\frac{1}{0.25} = 4 and 11=1\frac{1}{1} = 1.
    Show one possible solution

    Answer: (a) 25; (b) 22.

    plain:20+302=25weighted:4×20+1×304+1=1105=22\begin{aligned} \text{plain:}\quad & \frac{20 + 30}{2} = 25 \\[8pt] \text{weighted:}\quad & \frac{4 \times 20 + 1 \times 30}{4 + 1} = \frac{110}{5} = 22 \end{aligned}
  3. 3.(a) A training set has 5,000 cars with a mean price of 24,000 manats. What is predicted for every car with k=5,000k = 5{,}000? (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. 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 1distance\frac{1}{\text{distance}}. 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.

  1. 5.Read car_prices.csv into df. Print the shape, then the number of repeated rows.
    Show a hint
    df = pd.read_csv("car_prices.csv"), then print(df.shape) and print(df.duplicated().sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("car_prices.csv")
    
    print(df.shape)
    print(df.duplicated().sum())

    Output

    (10000, 19)
    691
  2. 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(), then df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)], then df.drop(columns=["model"]) and len(df).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop_duplicates()
    df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)]
    df = df.drop(columns=["model"])
    
    print(len(df))

    Output

    9259
  3. 7.Group the brands with fewer than 50 cars as "other", fill the missing market with "unknown", and one-hot encode the columns of text_columns with drop_first=True and dtype=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"; then fillna("unknown") and pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int).
    Show one possible solution
    Python, continues from the cells above
    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
  4. 8.Make X (all columns without price_azn) and y. Split them with test_size=0.3 and random_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), then len(y_test) and round(y_test.mean(), 1).
    Show one possible solution
    Python, continues from the cells above
    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.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.

  1. 9.Fill horsepower, seats and owners in both parts with the training medians. Then fit a StandardScaler on X_train and scale both parts into X_train_scaled and X_test_scaled. Print the shape of X_test_scaled.
    Show a hint
    medians = X_train[["horsepower", "seats", "owners"]].median(), fillna(medians) on both parts; then scaler.fit_transform(X_train) and scaler.transform(X_test).
    Show one possible solution
    Python, continues from the cells above
    from 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)
  2. 10.Train a KNeighborsRegressor called knn with 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), then knn.score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    from 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
  3. 11.Put the predictions of knn into predicted. Print the MAE and the RMSE as whole numbers.
    Show a hint
    predicted = knn.predict(X_test_scaled), then round(mean_absolute_error(y_test, predicted)) and the same with root_mean_squared_error.
    Show one possible solution
    Python, continues from the cells above
    from 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
  4. 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, then score on both parts.
    Show one possible solution
    Python, continues from the cells above
    for 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.

  1. 13.Train a model with k = 5, weights="distance" and p=1 on the scaled data. Print its test R², rounded to 4 decimals.
    Show a hint
    KNeighborsRegressor(n_neighbors=5, weights="distance", p=1), fit, then score.
    Show one possible solution
    Python, continues from the cells above
    model = 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
  2. 14.Scale only the nine features of columns with a new StandardScaler into X_train_few and X_test_few, train a default KNeighborsRegressor called knn_few on 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]), then fit and score.
    Show one possible solution
    Python, continues from the cells above
    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.7934
  3. 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 above
    from 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
  4. 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) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import 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
    The chart this code draws

12Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.How does KNeighborsRegressor predict a number for a new row?

Question 2

2.Why does k not have to be odd in regression?

Question 3

3.What does the model predict when k equals the number of training rows?

Question 4

4.Three neighbours at the distances 1, 1 and 2 have the prices 10, 20 and 40. What is the prediction with weights="distance"?

Question 5

5.Why did the car model improve so much with nine features instead of 83?

Question 6

6.What happened to the test R² without scaling?

Question 7

7.A repeated advert is in both the training and the test data. What happens?

Question 8

8.Which value can KNeighborsRegressor never predict, if the training prices lie between 1,200 and 160,000?

Question 9

9.The training R² is 0.9996 with weights="distance". What does it mean?

Question 10

10.Which measure tells the typical error of a predicted price in manats?

Question 11

11.What does KNeighborsRegressor have instead of predict_proba?

Question 12

12.Which preprocessing step matters for k-nearest neighbours but not for a random forest?

0 of 12 answered.

13Summary

Summary
Formula or ruleMeaning
Predictionthe mean of the k nearest training valuesno vote, no probability
Weighted predictionw1y1+w2y2+…w1+w2+…\frac{w_1 y_1 + w_2 y_2 + \dots}{w_1 + w_2 + \dots} with w=1distancew = \frac{1}{\text{distance}}close neighbours count more
Small klow bias, high variancek = 1 copies one training row
Large khigh bias, low variancek = n predicts the mean of all training values
Odd or even kboth are finea mean cannot tie
Rangebetween the smallest and the largest training valueno extrapolation
Summary
CodeWhat 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_errorthe 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

  1. k-nearest neighbours regression predicts the mean (or weighted mean) of the k nearest training values.
  2. Always scale; drop repeated rows before the split; fill missing values after it with training values.
  3. Choose a few useful features: with many one-hot columns the true neighbours disappear.
  4. Choose k with cross-validation; even and odd k are both fine for regression.
  5. Judge with R², MAE and RMSE on the test data; a training R² near 1 means nothing for this model.
  6. 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.