Supervised Learning
k-Nearest Neighbors
Change the distance metric or neighbour count and watch the votes reshape the decision boundary.
44 synthetic observations: 26 class A and 18 class B.
- Class A
- Class B
The plot can crop points or the query. Under the hood lists raw coordinates and distances. Leave-one-out evaluates all 44 displayed observations, using at most 43 neighbours per held-out observation; it is exploratory, not a final test.
How much the two classes intrude on each other.
Change the overlap to explore the observations.
Which observations will influence a query?
Two classes, drawn as different shapes as well as different colours — the shape is the part that survives a greyscale print. There are more of class A than class B, which matters later.
Neighbour
A stored observation ranked by its distance from the query.
Check this stage
This model has no equation and learns nothing when you train it. Its decision boundary is a shape nobody drew — it is whatever the rule leaves behind. Drag the query point around and watch it appear.
What you are looking at
Two classes of labelled examples, and one diamond that has no label. The question is what class the diamond should be, and k-nearest-neighbors answers it in one sentence: look at the nearest few examples and take whichever label most of them have.
That is the whole algorithm. There is no line to fit and no weights to solve for.
Training does nothing
Every other model in this section has a training step that produces something — a slope
and an intercept, a set of weights, a set of centroids. k-NN produces nothing. Training is
store the data.
All the work moves to prediction time instead. That is a real tradeoff, not a curiosity: free to train, expensive to answer. A model with a million examples has to consult a million distances for every single query, which is why the practical versions of this algorithm are mostly clever data structures for avoiding that.
Asking the neighbours
You move into a street and want to know which bin day it is. You could look up the council schedule, or you could ask the nearest few houses and go with the majority.
Ask one house and you inherit whatever mistake that one household makes. Ask everyone on the street and you get the answer for the street as a whole, which may be wrong for your end of it. Ask five nearby, and you have smoothed out the individual errors without losing the local pattern.
The number of neighbours, distance metric and feature scales are choices to assess on appropriate validation data.
The boundary is not drawn
Turn to the third stage and the plot fills with shading. Nothing about that shading was computed as a boundary. Every cell was asked the same question the diamond was asked — "what do your nearest neighbours say?" — and shaded by the answer.
The frontier that appears between the two colours is the set of positions where the vote happens to flip. It is a consequence, not a definition. That is worth sitting with, because it explains the shape: k-NN boundaries are jagged and locally irregular in a way a fitted line never is, and their shape depends on the observations and distance rule.
Notice the shading is not uniform. Where a region is washed out, the vote is close — a position that was nearly classified the other way. Opacity shows the winning vote fraction, not an empirically calibrated probability. Each cell reports its centre; the grid is a sampled approximation, not every possible query.
The one dial, and both ways it fails
controls how far the model looks, and both extremes are broken in opposite ways.
At every training point owns the territory closest to itself. The boundary threads between individual examples, so one mislabelled point carves out its own little island of wrong answers. The model has memorised the data, including its noise.
At every query consults every example. This lab has a unique majority, so every query receives that label. With tied overall counts, this lab’s nearest-member tie rule can still produce different answers.
An intermediate value can work better, but the best choice depends on the data and evaluation protocol.
Accuracy on the training set is meaningless here
With unique feature coordinates, scoring k-NN on its own training data at gives 100%: each observation is its own nearest neighbour. Duplicate coordinates with conflicting labels need a tie rule.
This is not a good model. It is a lookup table reporting that it can look things up. The readout in this lab uses leave-one-out instead — each point classified by all the others — which is the cheapest honest alternative and which can be high or low at , depending on the observations. It is an exploratory score when you use it to choose settings, not an untouched final test.
Ties are real
Set to an even number and watch for the callout. With two classes and an even , the vote can split exactly, and at that point the rule has no answer.
Something still has to be returned, so implementations impose a tiebreak — this one gives it to whichever tied class owns the single closest point. That is deterministic and defensible, and it is still a decision made outside the data. An odd makes the situation impossible, which is the entire reason odd values are conventional.
Distance is a modelling choice
Euclidean distance treats feature differences according to their numerical scale. They rarely do. Measure one feature in metres and another in kilometres and the the numerically larger feature can dominate distance, making the other less influential — not because it is uninformative, but because of the units it was recorded in.
Try the feature-one divisor and switch between Euclidean and Manhattan distance. The same observations can have different nearest neighbours under each convention. Scaling is a modelling choice: it does not prove that both features are equally useful. If scaling is learned from data, learn it within each training fold. In high dimensions, sparse coverage and distance concentration can make neighbours less informative; the outcome depends on the data and metric.
What to take away
There is no fitted model here, only a rule and a dataset. The boundary is emergent, so it is shaped by where the examples happen to be. trades sensitivity to local structure against sensitivity to noise, and both ends of that trade are visible on the plot rather than something to take on trust.
Stage recap
Labelled data
Two classes, drawn as different shapes as well as different colours — the shape is the part that survives a greyscale print. There are more of class A than class B, which matters later.
One query
Drag the diamond. Its k nearest neighbours light up, and it takes whichever label most of them carry. That is the entire algorithm.
Every query at once
Run that rule at the centre of each displayed cell and shade it by its answer. The boundary was never drawn — it is what the rule leaves behind.
Reference
- Distance
- d(p, q) = √( (p₁−q₁)² + (p₂−q₂)² )
- Prediction
- the most common label among the k nearest points
- k = 1
- the nearest observation determines the answer; duplicate coordinates need a tie convention
- k = n
- a unique overall majority gives one constant answer; tied counts depend on the tie rule
- Ties
- an even k can split a binary vote; equal distances also need an ordering rule
- Training cost
- stores observations; distance search and voting occur at prediction time
Break it on purpose
Raise k to 44 — the size of the whole dataset — and every query returns the majority class, everywhere. The boundary is gone and the model has become a constant. Note which class it collapses to: the larger one, which is the same mechanism that makes accuracy a misleading score on imbalanced data. Separately, set k to an even number and watch ties appear, where the neighbourhood genuinely cannot decide and a rule has to break the deadlock instead.