Skip to content
Lambdian

k-nearest neighbours

Predict from the most similar training examples: no training, one knob, and a lesson about distance.

Animated explanation

The idea

"Tell me who your neighbours are and I'll tell you who you are." To classify a new point, find the kk training points closest to it and take a majority vote; for regression, average their values.

There is no training phase: the model is the stored data. That makes k-NN wonderfully flexible (it can carve any boundary shape) but also slow at prediction time and completely dependent on what "close" means. Choosing the distance and scaling the features is most of the work.

k controls bias and variance

With k=1k=1 the boundary hugs every training point, outliers included: zero training error, high variance. Larger kk averages over more neighbours, smoothing the boundary and lowering variance, until it blurs real structure (high bias). Odd kk avoids ties in binary problems. Choose kk by cross-validation; distance-weighted voting makes the choice less sensitive.

Distance is everything

Features on large scales dominate Euclidean distance: income in rupees would swamp age in years. Always standardise. Irrelevant features add noise to every distance, so feature selection helps a lot. Use Hamming or Jaccard distance for categorical data and cosine distance for text embeddings.

The curse of dimensionality

In high dimensions, points become nearly equidistant: the nearest and farthest neighbours are at almost the same distance, so "nearest" carries little information. To have neighbours close by, the data needed grows exponentially with the dimension. k-NN works best in low to moderate dimensions, or on learned embeddings where distance is meaningful. For speed, use KD-trees or ball trees in low dimensions and approximate nearest-neighbour indexes (HNSW) for large embedding collections.

The algorithm, step by step

  1. 1
    Standardise features; store the training set.
  2. 2
    For a query x\mathbf{x}, compute distances to all training points.
  3. 3
    Take the kk smallest (e.g. with np.argpartition).
  4. 4
    Classification: majority vote among their labels. Regression: their (optionally distance-weighted) mean.

The maths

Majority vote

y^(x)=arg⁡max⁡c∑i∈Nk(x)1[yi=c]\hat{y}(\mathbf{x}) = \arg\max_c \sum_{i\in N_k(\mathbf{x})}\mathbb{1}[y_i = c]

Euclidean distance

d(x,z)=∥x−z∥2=∑j(xj−zj)2d(\mathbf{x}, \mathbf{z}) = \lVert \mathbf{x} - \mathbf{z}\rVert_2 = \sqrt{\textstyle\sum_j (x_j - z_j)^2}

Fast squared distances (matrix form)

Dij=∥ai∥2+∥bj∥2−2 ai⊤bjD_{ij} = \lVert\mathbf{a}_i\rVert^2 + \lVert\mathbf{b}_j\rVert^2 - 2\,\mathbf{a}_i^\top\mathbf{b}_j

Asymptotics

err1-NN≤2 errBayes  (n→∞)\text{err}_{1\text{-NN}} \le 2\,\text{err}_{\text{Bayes}}\ \ (n\to\infty)
With infinite data, 1-NN's error is at most twice the best possible error (Cover & Hart).

Strengths and weaknesses

Strengths

  • No training; trivially handles new data
  • Any decision boundary shape; naturally multi-class
  • Easy to explain with concrete similar examples

Weaknesses

  • Prediction is slow: compares with every stored point
  • Needs feature scaling and a meaningful distance
  • Suffers badly in high dimensions

Reach for it when…

Low-dimensional data or good embeddings, moderate dataset size, and when explaining by example matters (recommendations, case-based reasoning).

Check your understanding

Question 1

Q1k-NN with k = 1 has training error…

Question 2

Q2One feature is in metres (0–2), another in rupees (0–1,000,000). Without scaling…

Question 3

Q3Increasing k usually…

Lambdian Lab

Vectorised k-NN

Implement k-NN without Python loops over training points.

  • pairwise_sq_dists(A, B): an (len(A), len(B)) matrix of squared Euclidean distances using ∥a∥2+∥b∥2−2a⊤b\lVert a\rVert^2 + \lVert b\rVert^2 - 2a^\top b (clip tiny negatives to 0).
  • knn_predict(X_train, y_train, X, k): majority vote; break ties towards the smallest class label (np.bincount + argmax does this).
  • best_k(X_tr, y_tr, X_va, y_va, ks): the k with the highest validation accuracy (smallest k on ties).
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.