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.

New customer ⭐: most of the 5 nearest neighbours are blue → predict blue
KNN looks at the K most similar past examples and copies the majority.

K = 5: which group does the new customer belong to?

● bought size M● bought size L?Inside the circle: 3 teal vs 2 orange → predict size M

How it works, step by step

  1. Store all the labelled examples.
  2. For a new case, measure its distance to every stored example (how different their features are).
  3. Pick the K closest ones, for example K = 5.
  4. Classification: take the majority answer among them. Regression: take their average.
  5. 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 min

Find the nearest neighbours

  1. List 8 friends with two scores: likes action films (1–5) and likes romance (1–5).
  2. Add a new person and find the 3 most similar friends.
  3. 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.

Build it for real · guided projectFind customer groups with K-means clusteringAbout 45 min · Copy-paste code · step by step
Test what you learned

Take a quick quiz, or look up any word in the glossary.