Sub topic 3
Classifying with the k nearest neighbours
This chapter assumes you know what features, labels and a train/test split are, and that you can compute Euclidean distance between two vectors. It also assumes basic Python and NumPy. Here you will turn distance into a working classifier.
The idea
k-nearest neighbours (k-NN) classifies a new point by looking at the k training points closest to it. Each neighbour votes with its label, and the most common label wins.
There is no training phase that fits parameters. The "model" is the stored training set. All the work happens at prediction time, which is why k-NN is called a lazy learner.
The algorithm
For a query point x:
- Compute the distance from
xto every training point. - Sort the distances and keep the indices of the k smallest.
- Look up the labels at those indices.
- Return the most frequent label.
Implementation from scratch
import numpy as np
from collections import Counter
def knn_predict(X_train, y_train, x, k=3):
# Euclidean distance from x to every training point
dists = np.linalg.norm(X_train - x, axis=1)
# Indices of the k smallest distances
nearest = np.argsort(dists)[:k]
# Majority vote among the neighbours' labels
return Counter(y_train[nearest]).most_common(1)[0][0]
X_train = np.array([[1.0, 1.0], [1.2, 0.8], [4.0, 4.2], [3.8, 4.0], [4.1, 3.9]])
y_train = np.array([0, 0, 1, 1, 1])
print(knn_predict(X_train, y_train, np.array([1.1, 0.9]), k=3)) # 0Walk through the query [1.1, 0.9]:
X_train - xsubtracts the query from every row, using NumPy broadcasting.np.linalg.norm(..., axis=1)gives one Euclidean distance per row.np.argsort(dists)[:k]returns the positions of the three closest points. These are the two class-0 points and one class-1 point.Countertallies the labels. Label 0 appears twice and label 1 once, so the prediction is 0.
The query sits right next to the two class-0 points, so even with a third neighbour from class 1 the vote is clear.
What the code costs
The function computes a distance to every training point for every query. With n training points and d features, one prediction costs about O(n·d) time. The stored data also costs O(n·d) memory. Training is free, but prediction gets slower as the dataset grows. Later chapters cover tree structures and approximate search that reduce this cost.
Using scikit-learn
In practice you use KNeighborsClassifier. It follows the usual fit and predict pattern, though fit only stores the data (and may build a search index).
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
clf = KNeighborsClassifier(n_neighbors=5)
clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))This runs, but the wine features have very different ranges, so the distances are dominated by a few columns. The accuracy will be lower than it could be. A later chapter on feature scaling fixes this.
Common errors
- Ties in the vote. With an even k and two classes, the vote can split evenly. An odd k avoids ties in binary problems. With more than two classes ties can still happen, and
Counter.most_commonthen returns whichever label it counted first among the tied ones. - Setting k larger than the training set. There are not enough neighbours, and scikit-learn raises an error at prediction time.
- Evaluating on training data. If a training point is its own query, its nearest neighbour is itself at distance 0. With k=1 you get 100% training accuracy, which says nothing about generalisation. Always score on held-out data.
- Ignoring feature ranges. A feature measured in thousands swamps one measured in fractions. This is the most common cause of poor k-NN results.
Exercise
In the from-scratch example, suppose you call knn_predict with k=1 and the query [3.9, 4.0]. Which label is returned, and why?
Show answer
Label 1. The closest training point to [3.9, 4.0] is [3.8, 4.0] (distance 0.1), which has label 1. With k=1 that single neighbour decides the vote.
Exercise
Why does k-NN have no training phase that fits parameters, and where does its computational cost appear instead?
Show answer
k-NN stores the training set and uses it directly as the model, so nothing is fitted. The cost appears at prediction time, when each query needs a distance to every stored point, roughly O(n·d) per query.