Skip to content
StackDecode
AI & ML Atlas
Machine LearningalgorithmInteractive simulation

K-Nearest Neighbours (KNN)

Classifies a point by the majority label among its k closest examples.

The idea

There is no training step: the data itself is the model. To classify a new point, measure its distance to every stored point, take the k nearest and let them vote. A small k gives a jagged boundary that follows noise; a large k gives a smooth one that can blur small classes.

distance = √Σ (xᵢ − yᵢ)²

Watch it run

This is a real computation, not a drawing. Pause, step, change the settings, or try new random data.

  • class 0
  • class 1

All the data starts in one box. The tree will ask yes/no questions to separate the classes.

impurity:
0.5
1/4

Every cut is axis-aligned, so each region is a rectangle. Deeper trees carve finer boxes and can overfit.

Step by step

  1. 1Choose k and a distance measure (usually Euclidean).
  2. 2Compute the distance from the new point to every training point.
  3. 3Take the k closest.
  4. 4Return the majority class (or the average for regression).

Where it is used

Small datasets, recommendation, anomaly checks, a baseline.

Watch out for

Slow on big data and badly hurt by irrelevant or unscaled features.

Related