TExcelTAD

k-Nearest Neighbours

To guess the price of a flat, an estate agent looks at the few most similar flats that sold recently. k-nearest neighbours (kNN) does exactly that: to predict for a new point, find the kk training points closest to it and let them vote (classification) or average their targets (regression). There is no training at all beyond storing the data, which makes kNN the simplest model to explain and a good check on whether "similar inputs have similar outputs" holds in your data. The Machine Learning course introduces it; this lesson covers the vectorised implementation, the choice of kk, scaling and why kNN struggles in high dimensions.

Definition

Given a distance dd (usually Euclidean), let Nk(x)N_k(\mathbf{x}) be the kk training points nearest to x\mathbf{x}. Then

y^class(x)=arg⁡max⁡c∑i∈Nk(x)[yi=c],y^reg(x)=1k∑i∈Nk(x)yi.\hat{y}_{\text{class}}(\mathbf{x}) = \arg\max_{c} \sum_{i \in N_k(\mathbf{x})} [y_i = c], \qquad \hat{y}_{\text{reg}}(\mathbf{x}) = \frac{1}{k} \sum_{i \in N_k(\mathbf{x})} y_i .

With weights="distance", closer neighbours count more (weight 1/d1/d). Other distances: Manhattan ∑j∣xj−xj′∣\sum_j \lvert x_j - x'_j \rvert, Minkowski (∑j∣xj−xj′∣p)1/p\big(\sum_j \lvert x_j - x'_j \rvert^p\big)^{1/p}, cosine for text and embeddings (Distances, Angles and Orthogonality, Norms).

See it

The lab trains kNN on 80 noisy points (the noise slider starts at its maximum). With k=1k = 1 every training point claims its own region and the boundary is jagged: 80 of 80 training points right, but only 91.5 % of 200 new test points. At k=15k = 15 the boundary smooths, training accuracy drops to 92.5 % and test accuracy rises to 94.5 %. Very large kk blurs real structure; lower the noise to see that small kk is fine when the data is clean.

−2−1012−2−1012feature x₁feature x₂kNN on moonsk = 1class Aclass Bdecision boundaryTraining accuracy80/80100.0 %Test accuracy183/20091.5 %Test set: 200 new points

From scratch, vectorised

The distance from every query to every training point comes from one identity, ∥a−b∥2=∥a∥2−2 a⊤b+∥b∥2\lVert \mathbf{a} - \mathbf{b} \rVert^2 = \lVert \mathbf{a} \rVert^2 - 2\,\mathbf{a}^\top\mathbf{b} + \lVert \mathbf{b} \rVert^2, so a matrix product computes the whole table:

python · try it yourself
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor

X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
sc = StandardScaler().fit(X_tr)
X_tr, X_te = sc.transform(X_tr), sc.transform(X_te)

def pairwise_sq_dist(A, B):
    # ||a - b||^2 = ||a||^2 - 2 a.b + ||b||^2, for all pairs at once
    return (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)[None, :]

def knn_classify(X_tr, y_tr, X, k):
    nearest = np.argsort(pairwise_sq_dist(X, X_tr), axis=1, kind="stable")[:, :k]
    votes = np.apply_along_axis(np.bincount, 1, y_tr[nearest], minlength=y_tr.max() + 1)
    return votes.argmax(axis=1)

def knn_regress(X_tr, y_tr, X, k):
    nearest = np.argsort(pairwise_sq_dist(X, X_tr), axis=1, kind="stable")[:, :k]
    return y_tr[nearest].mean(axis=1)

for k in [1, 5, 15]:
    ours = knn_classify(X_tr, y_tr, X_te, k)
    sk = KNeighborsClassifier(n_neighbors=k).fit(X_tr, y_tr).predict(X_te)
    print(f"k={k:2d}: test accuracy {np.mean(ours == y_te):.3f}, same as sklearn: {bool(np.all(ours == sk))}")

# regression: predict alcohol (column 0) from the other 12 standardised features
r_ours = knn_regress(X_tr[:, 1:], X_tr[:, 0], X_te[:, 1:], 5)
r_sk = KNeighborsRegressor(n_neighbors=5).fit(X_tr[:, 1:], X_tr[:, 0]).predict(X_te[:, 1:])
print("kNN regression matches sklearn:", np.allclose(r_ours, r_sk))
k= 1: test accuracy 1.000, same as sklearn: True
k= 5: test accuracy 0.963, same as sklearn: True
k=15: test accuracy 0.981, same as sklearn: True
kNN regression matches sklearn: True

The from-scratch version agrees with scikit-learn for every kk, for classification and regression. On 54 test wines the differences between kk values are one or two wines, too few to choose kk from; that is the job of cross-validation below. Prediction costs O(n d)O(n\,d) per query with brute force; scikit-learn can switch to KD-trees or ball trees (algorithm="auto"), which are much faster in low dimensions and lose their advantage beyond about 20.

Choosing k, and why scaling is not optional

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

# 1) choosing k by cross-validation, with and without scaling
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(5, shuffle=True, random_state=0)
print("  k   raw    scaled")
for k in [1, 3, 5, 11, 21, 51]:
    raw = cross_val_score(KNeighborsClassifier(k), X, y, cv=cv).mean()
    scaled = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(k)), X, y, cv=cv).mean()
    print(f"{k:3d}  {raw:.3f}  {scaled:.3f}")

# 2) the curse of dimensionality: distances concentrate
rng = np.random.default_rng(0)
print("dims  nearest/farthest distance from a random point")
for d in [2, 10, 100, 1000]:
    P = rng.uniform(size=(1000, d))
    dist = np.sqrt(((P[1:] - P[0]) ** 2).sum(axis=1))
    print(f"{d:4d}  {dist.min() / dist.max():.3f}")
  k   raw    scaled
  1  0.914  0.958
  3  0.932  0.965
  5  0.932  0.965
 11  0.933  0.967
 21  0.928  0.958
 51  0.914  0.947
dims  nearest/farthest distance from a random point
   2  0.006
  10  0.287
 100  0.699
1000  0.900

Two lessons in one output. First, scaling: the breast-cancer features range from fractions to thousands (the area of a nucleus), so unscaled distances are mostly "difference in area". Standardising inside the pipeline lifts accuracy at every kk. Second, the U-shape in kk: k=1k = 1 has high variance, k=51k = 51 too much bias, and the best values lie around 3 to 11.

The last table shows the curse of dimensionality. For 1000 random points in the unit cube, the nearest point is 0.006 times as far as the farthest in 2 dimensions, but 0.900 times as far in 1000 dimensions: almost every point is about equally far away, so "nearest" carries little information. kNN works when the data really lives in few dimensions (as images and embeddings often do) or after dimensionality reduction (PCA).

Hyperparameters

Hyperparameter Effect
n_neighbors (kk) small: flexible, high variance; large: smooth, high bias. Odd kk avoids ties in binary problems
weights "uniform" or "distance" (closer neighbours count more)
metric, p Euclidean, Manhattan, Minkowski, cosine; must suit the features
algorithm brute force, KD-tree, ball tree: speed only, not results

Strengths, weaknesses, when to use it

Strengths Weaknesses
no training; new data is added instantly slow predictions and memory for the whole training set
any boundary shape; naturally multiclass needs scaling and a meaningful distance
one intuitive hyperparameter degrades in high dimensions and with irrelevant features
explanations by example ("these 5 similar cases") no model to inspect beyond the stored data

Use kNN as a quick baseline on low-dimensional, well-scaled data, for recommendation and retrieval by similarity (with approximate nearest-neighbour indexes for large data), and for imputation (KNNImputer).

Pitfalls

  • Forgetting to scale, or scaling on all the data. Put the scaler in a pipeline so it is fitted on training folds only.
  • Irrelevant features. Every useless feature adds noise to every distance; select or reduce features first.
  • Using kNN's training score. With k=1k = 1 the training accuracy is 100 % by construction (each point is its own neighbour).

Practice

  1. Two features: income in dollars (range 20 000 to 200 000) and age (20 to 70). Without scaling, which feature decides who the neighbours are?
Answer

Income: a difference of a few thousand dollars dwarfs any age difference, so neighbours are simply the people with the closest income and age is ignored. Standardising puts both on a comparable scale.

  1. Why does k=1k = 1 give 100 % training accuracy, and what does that say about the training score of kNN?
Answer

Each training point's nearest neighbour is itself (distance 0), so it predicts its own label. The training score therefore measures nothing about generalisation; only validation or cross-validation scores are meaningful for kNN.

Test yourself

What does kNN do during fit?

  1. Learns a weight per feature
  2. Stores the training data (and maybe builds a search index)
  3. Computes class centroids
  4. Fits a tree

Increasing kk in kNN classification tends to…

  1. increase variance
  2. increase bias and smooth the decision boundary
  3. make training slower
  4. require scaling

In 1000 dimensions, the nearest and farthest random points were at a distance ratio of 0.9. Why is that bad for kNN?

  1. Distances become negative
  2. All points are nearly equally far away, so the nearest neighbours are barely more similar than random points
  3. The computation overflows
  4. kNN needs odd dimensions