← All animations

📍 K-Nearest Neighbours

One of the simplest ideas in machine learning: to classify something new, just look at the k labelled examples nearest to it and let them vote. There is no real "training" — the algorithm only memorises the data, then measures distances when you ask it to predict. Scroll through to drag a query point around, watch its neighbours decide its label, and see how the choice of k reshapes the entire decision boundary.

1. The vote — your label is whatever your neighbours mostly are

The coloured dots are labelled training points (three classes). Drag the white query point anywhere. We draw a line to each of its k nearest neighbours by straight-line (Euclidean) distance, then colour the query by the majority vote of those neighbours. Nudge k and watch the verdict flip — and notice that an even k can tie.

k = 3 verdict…
Class A Class B Class C Query point

2. The decision boundary — colour every spot by who would win there

Now run the vote at every location and tint the background by the class that wins. That shaded map is the decision boundary. Drag k: small k gives a jagged, noise-chasing boundary that wraps tightly around stray points (overfitting); large k gives a smooth one that can blur real structure (underfitting). Somewhere in between is the sweet spot.

k = 1 k = 1 → jagged (overfit)

Distance metric & scale matter: kNN measures raw distance, so a feature in big units (e.g. salary in dollars) drowns out one in small units (e.g. age in years). You almost always standardise / scale features first, and the choice of metric (Euclidean vs. Manhattan vs. cosine) changes which points count as "near".

3. What's really going on