Skip to content
BIASED

Nearest neighbours

Block 1 of 7~3 min

From memorizing to neighbours

The topic Validation and overfitting built a protocol that measures any model honestly: hold-out and KK-fold cross-validation, a test set touched once, nested cross-validation when a model is chosen among many. So far it had little to measure. The only models were thought experiments, such as the memorizer from What machine learning is: it returns yiy_i for a training object xix_i and a default answer for everything else.

The smallest change that makes the memorizer useful is to answer a new question with the answers to the most similar questions seen before. That is the nearest-neighbour method (Fix and Hodges, 1951), the first real model of the course.

It needs a distance ρ(x,x′)≥0\rho(x, x') \ge 0 between objects. For a query xx, let Nk(x)N_k(x) be the indices of the kk training objects nearest to xx; in this topic kk always counts neighbours. For classification, predict the most frequent class among them:

a(x)=arg⁡max⁡c∑i∈Nk(x)[yi=c].a(x) = \arg\max_{c} \sum_{i \in N_k(x)} [y_i = c] .

For regression, predict the mean of their targets:

a(x)=1k∑i∈Nk(x)yi.a(x) = \frac1k \sum_{i \in N_k(x)} y_i .

The topic Conditional expectation showed that the best predictor under squared loss is E[Y∣X=x]\mathbb E[Y \mid X = x]. The regression rule estimates it locally: it averages YY over the training points whose XX lies close to xx. In the same way, the vote shares estimate the class probabilities P(Y=c∣X=x)P(Y = c \mid X = x). "Training" is just storing the sample; all the work happens at prediction time.

A worked example. The query is x=(0,0)x = (0, 0). Two training points have class ++: A=(1,0)A = (1, 0) and C=(−2,0)C = (-2, 0). Three have class −-: B=(0,2)B = (0, 2), D=(2,2)D = (2, 2) and E=(0,−3)E = (0, -3). The Euclidean distances from the query to A,B,C,D,EA, B, C, D, E are 11, 22, 22, 2.832.83 and 33.

  • k=1k = 1: the only neighbour is AA, so the answer is ++.
  • k=3k = 3: AA, BB and CC vote two to one for ++.
  • k=5k = 5: all five points vote three to two for −-.

The answer depends on kk, and so does its quality.

Answers are saved on the server and tied to this browser until you sign in.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • k-NN majority voteoptional

    NumPy: distances, k nearest, majority class. Self-check in the notebook.

    ~15 min · easier on a computer · Nearest neighbours topic read.

    Self-check in the notebook — not part of mastery or the certificate.