Sub topic 3
Classifying with the k Nearest Neighbours
What this chapter assumes
You should know what features, labels and a train/test split are. You should be comfortable with Euclidean distance between two vectors and with basic NumPy indexing. The previous chapters covered instance-based learning and distance metrics. This chapter puts them together into a working classifier. Later chapters cover choosing k, scaling, weighted voting and fast search, so here they only get brief mentions.
The working model
The k-nearest neighbours (k-NN) classifier has no fitting step that learns parameters such as weights or thresholds. "Training" means storing the feature matrix and the labels. All the work happens at prediction time, which is why k-NN is called a lazy learner.
To classify one new point x, the algorithm does four things:
- Compute the distance from
xto every stored training point. - Sort the training points by that distance and keep the
kclosest. - Collect the labels of those
kpoints. - Return the most common label (the majority vote).
The model is the training set plus two choices you make: the distance function and the value of k. Nothing else is learned. This makes k-NN easy to reason about. It also means that every weakness of the data, such as noisy labels, badly scaled features and irrelevant features, goes directly into the prediction.
A classifier from scratch
The following function implements the four steps with NumPy.
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)) # 0Three lines carry the logic:
X_train - xuses broadcasting. NumPy subtracts the length-2 vectorxfrom each row of the 5×2 matrix.np.linalg.norm(..., axis=1)then takes the length of each difference row, which gives one distance per training point.np.argsort(dists)returns the indices that would sort the distances. Taking[:k]keeps the positions of thekclosest points. You need indices, not the distances themselves, because the indices let you look up the labels.Counter(y_train[nearest])counts how often each label appears among the neighbours.most_common(1)[0][0]extracts the label with the highest count.
Tracing the example
For the query (1.1, 0.9) the distances are:
| Training point | Label | Distance to query |
|---|---|---|
| (1.0, 1.0) | 0 | 0.141 |
| (1.2, 0.8) | 0 | 0.141 |
| (3.8, 4.0) | 1 | 4.111 |
| (4.1, 3.9) | 1 | 4.243 |
| (4.0, 4.2) | 1 | 4.393 |
The rows are sorted by distance. With k=3 the neighbours are the first three rows, with labels 0, 0, 1. Label 0 wins two votes to one.
Now try k=5. The vote then covers the whole training set, so label 1 wins three to two. Any query, however close to the label-0 cluster, would get label 1. This shows that k controls how local the decision is. The next chapters take that up.
The same model in scikit-learn
In practice you will use KNeighborsClassifier. It follows the usual fit/predict interface.
from sklearn.neighbors import KNeighborsClassifier
X = [[1.0, 1.0], [1.2, 0.8], [4.0, 4.2], [3.8, 4.0], [4.1, 3.9]]
y = [0, 0, 1, 1, 1]
clf = KNeighborsClassifier(n_neighbors=3).fit(X, y)
print(clf.predict([[1.1, 0.9]])) # [0]
print(clf.predict_proba([[1.1, 0.9]])) # [[0.66666667 0.33333333]]
distances, indices = clf.kneighbors([[1.1, 0.9]])
print(indices) # indices of the 3 nearest training pointspredict_proba returns the fraction of the k neighbours that voted for each class. These are vote shares, not calibrated probabilities. With k=3 the only possible values for two classes are 0, 1/3, 2/3 and 1. A model that outputs "0.67" is saying "two of three neighbours agreed", not "67% likely".
kneighbors returns the distances and training-set indices of the neighbours. This is useful for explaining a prediction. You can show the user which stored examples drove the decision.
Cost of prediction
For n training points with d features, one brute-force query costs O(n·d) to compute the distances. Sorting all n distances adds O(n log n). If you only need the k smallest, np.argpartition(dists, k)[:k] selects them in O(n), but it does not return them in sorted order. That matters if you later use the order of neighbours, for example to break ties.
Memory is O(n·d), because the whole training set must stay available. There is no compact model to ship. For a few thousand rows this is trivial. For millions of rows with hundreds of features, both memory and per-query time become real constraints, and a later chapter covers KD-trees, ball trees and approximate search.
Edge cases in the vote
Ties
A tie occurs when two classes get the same number of votes. With two classes, using an odd k avoids ties. With three or more classes, ties can happen at any k. For example, with k=5 the votes might be 2, 2 and 1.
Check how your implementation resolves ties, because the result can be surprising:
- In the from-scratch function,
Counterkeeps labels in the order it first sees them.most_common(1)returns the first of the tied labels. Sinceargsortputs the closest neighbour first, a tie is usually won by the class of the nearest neighbour among those tied. This is a reasonable behaviour, but it depends on that ordering and is not guaranteed when distances are equal. - scikit-learn resolves ties in favour of the class with the lowest label index in the sorted class list. That is arbitrary with respect to the data. Check the documentation for your installed version if this matters.
Ties in distance at the boundary
Suppose the third and fourth nearest points are at exactly the same distance. Only one of them can be in the top k, and which one depends on the sort order. This is common with integer or categorical-like features, and with duplicated rows. The prediction can then change if you reorder the training rows. If reproducibility matters, sort the data into a fixed order before fitting.
k larger than the training set
If k > n, the slice [:k] silently returns all n points in the from-scratch code, and the prediction becomes the global majority class. scikit-learn raises a ValueError instead. Validate k explicitly in your own code.
Querying a point that is in the training set
If the query is itself a stored point, its distance to itself is zero, so it is always its own nearest neighbour. With k=1 the prediction equals the stored label, so accuracy measured on the training data is perfect by construction.
from sklearn.neighbors import KNeighborsClassifier
X = [[1.0, 1.0], [1.2, 0.8], [4.0, 4.2], [3.8, 4.0], [4.1, 3.9]]
y = [0, 0, 1, 1, 1]
clf = KNeighborsClassifier(n_neighbors=1).fit(X, y)
print(clf.score(X, y)) # 1.0, always, because each point finds itselfCommon errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Predictions follow one feature and ignore the rest | Features on very different scales, so one dominates the distance | Scale features, inside a pipeline (see the scaling chapter) |
| Training accuracy 100%, test accuracy much lower | Evaluating on training data, or `k` too small | Hold out data and tune `k` with cross-validation |
| Predictions flip between runs or row orders | Tied votes or tied distances resolved by order | Use odd `k`, fix the row order, consider distance weighting |
| Always predicts the same class | `k` close to `n`, or a strongly imbalanced dataset | Reduce `k`, check class counts |
| Slow predictions on large data | Brute-force search costs O(n·d) per query | Use a tree index or approximate search |
| `ValueError` about `n_neighbors` | `k` exceeds the number of training samples | Lower `k` or add data |
What the vote assumes
Majority voting treats all k neighbours as equally informative, however far away they are. It also assumes that points close in feature space tend to share a label. When that assumption holds, k-NN works well with almost no tuning. When it fails, for example because the distance is dominated by irrelevant features, k-NN fails with it, and no amount of data fixes the problem. The distance function defines the model's idea of similarity, so most of the work in using k-NN well goes into the distance, the features and k.
Exercise
In the from-scratch example, the query is (1.1, 0.9) and k=3. Without running the code, what label does knn_predict return for the query (4.0, 4.0) with k=3? Give the three neighbour labels you used.
Show answer
The nearest points are (3.8, 4.0) at distance 0.2, (4.1, 3.9) at about 0.141, and (4.0, 4.2) at 0.2. All three have label 1, so the vote is 3 to 0 and the function returns 1. The two label-0 points are about 4.2 away and are never among the three nearest.
Exercise
A three-class problem uses k=4. The four nearest neighbours have labels A, A, B, B. The from-scratch function in this chapter returns a label, and the nearest neighbour is labelled B. Which label is returned, and why? Name one change that makes this less arbitrary.
Show answer
It returns B. Counter records labels in the order it sees them, and the nearest neighbour comes first in the argsort order, so B is inserted first. most_common(1) returns the first label among those tied at the top count. One fix is distance-weighted voting, where closer neighbours count more, so the tie is broken by actual distance. Another is to use an odd k, although that does not remove every tie with three or more classes.
Exercise
Why does clf.score(X, y) equal 1.0 for KNeighborsClassifier(n_neighbors=1) fitted on distinct training points, and why does this not show that the model is good?
Show answer
Each training point is at distance zero from itself, so it is its own single nearest neighbour and its prediction is its own label. The score therefore measures memorisation, not the ability to predict new points. To estimate real performance, score on a held-out test set or use cross-validation.