Every classifier so far — logistic regression, a decision tree, an SVM — short for support vector machine — spends real effort during training, fitting weights or splits before it can predict anything. What's the classifier that skips training entirely and just... looks at what's nearby?
Two clusters, and one deliberately mislabeled-looking point sitting right inside the wrong cluster's territory. Toggle — with , the query's prediction comes from whichever single point is closest, noisy point included. Raise , and that one stray point gets outvoted by its genuine neighbors.
-nearest neighbors has no training phase and no parameters to fit — the "model" is just the dataset itself:
- — the predicted class for the query point .
- — the query point being classified.
- — how many nearest neighbors get consulted for the vote.
- — the set of the points closest to .
- — the true label of training point .
- — one candidate class, ranging over whatever labels appear among the neighbors.
- Vote among the k closest points
Find the closest points to the query by ordinary distance, then predict whichever class shows up most among them.
- Learning happens at prediction time
All the "learning" happens when a query comes in, not during training — the opposite of every other model built so far in this course.
Drag the query and check the ranked list of nearest neighbors at every position. The prediction is entirely a local vote — it never looks at the shape of either cluster as a whole, only at whichever handful of points happen to be closest to wherever you're asking about.
A query point sits at , right at the edge of the B cluster — except for one noisy A point planted at :
- k=1: fooled by the noisy point
The single nearest neighbor is the stray A point, at distance — closer than any real B point. The prediction is A, which is wrong.
- k=3: the noisy point gets outvoted
The three nearest are the stray A point plus two genuine B points. That's votes for B against for A — the majority correctly overrides the single noisy neighbor.
- k=5: even more confident
Extending to the five nearest adds two more B points, for a -to- vote. The noisy point never goes away — it just matters less as more real evidence gets counted alongside it.
Pick a k whose prediction actually disagrees with k=1's.
is kNN's one real hyperparameter, and it trades off exactly the way -means' cluster count or a tree's depth did: too small and a single noisy point can swing the answer; too large and it starts averaging in points from an entirely different neighborhood that shouldn't count at all. This same nearest-neighbor idea has already shown up all over this course — word embeddings, joint embedding spaces, retrieval — but this is the first time it's the entire classifier by itself, with nothing trained on top of it.