Lesson 3.4foundation2 h 30 min⚡ live demo

k-Nearest Neighbors

Learning by remembering — and the ancestor of vector search

kNN has no training step and no parameters, which makes it the clearest model of what "similar inputs have similar outputs" means — and the clearest demonstration of why raw high-dimensional data breaks that assumption. It is also, almost literally, the retrieval step of a RAG system (9.1 Why RAG, and the canonical pipeline, 9.3 Vector search and indexes): find the nearest stored vectors to a query. Understand kNN and you understand what vector databases do and why they need approximate indexes.

You'll be able to

  • Implement kNN classification and regression, including distance weighting, from scratch
  • Choose a distance metric and explain why feature scaling is mandatory
  • Explain how k trades bias against variance and select it with cross-validation
  • Derive three quantitative consequences of the curse of dimensionality and state why learned embeddings escape it
  • Describe the cost of brute-force search and how KD-trees and approximate indexes (HNSW) change it
  • Connect kNN to retrieval, few-shot classification on embeddings and anomaly detection

Key ideas

  1. kNN stores the data and predicts by majority vote (or mean) over the k nearest points; the model is the data plus a distance.
  2. Features must be scaled with training statistics before computing distances, or the largest-scale feature decides everything.
  3. Small k → low bias, high variance (jagged boundary); large k → smooth, tends to the majority class; pick k by cross-validation, odd for binary.
Show 5 more key ideas
  1. Curse of dimensionality: a 1% neighbourhood spans 95% of each axis at d = 100; relative distance spread shrinks like 1/√d; almost all volume is near the boundary.
  2. kNN works on learned embeddings because real data have low intrinsic dimension; representation learning makes the locality assumption true.
  3. Brute force is O(nd) per query; KD/ball trees help for d ≲ 20; HNSW and other approximate indexes power vector search at scale.
  4. kNN is the retrieval step of RAG, the engine of few-shot classification on embeddings, KNN imputation and distance-based anomaly detection.
  5. Lazy (instant train, slow predict) is the mirror image of parametric models (slow train, instant predict).

Suggested path through this lesson