K-nearest neighbours (KNN)
Supervised · Classification & regression KNN predicts by finding the K most similar past examples (the nearest neighbours) and going with their majority answer, or their average for numbers. "Similar" is measured as distance between data points. KNN doesn't really train; it simply remembers all the examples.
Everyday analogy
You're new in town and want a good restaurant. You ask the 5 neighbours whose taste is most like yours and go where most of them recommend.
Example
Used for: "customers like you also bought" recommendations, finding similar products or documents, filling in missing values, simple medical similarity checks.
K = 5: which group does the new customer belong to?
How it works, step by step
- Store all the labelled examples.
- For a new case, measure its distance to every stored example (how different their features are).
- Pick the K closest ones, for example K = 5.
- Classification: take the majority answer among them. Regression: take their average.
- Return that as the prediction.
Worked example
An online clothes store wants to suggest a T-shirt size. A new customer is 170 cm and 65 kg. The 5 most similar past customers bought M, M, L, M and S. Majority: M, so the store pre-selects size M.
✓ Good for
- Very simple to understand and set up
- No training step; new examples can be added any time
- Works for both categories and numbers
⚠ Watch out for
- Slow when there are millions of examples to compare
- Features must be on similar scales (cm vs kg), or one dominates the distance
- You must choose K: too small is noisy, too large is blurry
Try it yourself
About 10 minFind the nearest neighbours
- List 8 friends with two scores: likes action films (1–5) and likes romance (1–5).
- Add a new person and find the 3 most similar friends.
- Recommend the films those 3 liked.
What you should see: KNN predicts from the most similar past examples.
Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.