Visual explainer
K-Nearest Neighbors
Predict a new point's class by looking at the k training points closest to it and taking a majority vote.
k-nearest neighbors predicts a query's class from nearby labeled examples. A simple version stores the training samples, finds the nearest k under a chosen distance, and gives each one a vote. It is instance-based learning: choosing the features, metric, k and weighting still defines a model. Fitting may also build a search index; it is not necessarily zero work.
Use this synthetic two-feature fixture throughout the spatial scenes: circles A=(2,0), D=(−3,−1), E=(2,−3), and squares B=(1,2), C=(−2,2). The diamond query q=(0,0) is not a stored training sample. Both axes use 40 SVG units per coordinate unit. The implied decision boundary exists even though the method does not fit a separate line.
Measure and Rank
For this example, calculate Euclidean distance . A is 2 away. B is ; C is ; D is ; E is . Their order is A, B, C, D, E.
The five rays represent center-to-center measurements, shortened slightly to leave the glyphs readable. Their directions and underlying lengths come from the coordinates. The picture illustrates a small exhaustive search; exact tree-based searches can avoid measuring every sample. Search strategy and prediction rule are separate choices.
Let Three Vote
At k=3, A, B and C vote. Two are squares and one is a circle, so the query's double square marks the predicted class. The dashed circle has radius SVG units; C's center lies exactly on the inclusion boundary. D and E lie outside by center distance. The 2:1 tally describes these three votes, not a calibrated probability of correctness.
Change k
The ranked samples are now laid out schematically, rather than spatially. Brackets select the voting set. One nearest neighbor copies A's circle label; three neighbors predict square. The same query and data can therefore produce different answers under different k values. Choose k using training-only model selection and held-out validation, rather than assuming one value suits every dataset.
Resist a Wrong Label
Switch to a one-dimensional illustration: q=0, a square at 0.5, and circles at 1, 1.5, 2 and 2.5. The top axis uses 120 SVG units per unit; the bottom row is a grouped tally. Suppose the square label is known to be a labeling mistake. With k=1, the query copies it; with k=5, the circles win 4:1.
This demonstrates resistance to one isolated mistake, not an ability to identify erroneous labels from distance. A larger neighborhood can also cross a real class boundary or bury a minority class.
Handle Ties Explicitly
Return to the original ranking. A, B, C and D contain two circles and two squares. Grouped glyphs and equal-length bars show the tie; each vote contributes 60 SVG units to its class bar. A classifier needs a tie policy.
An odd k prevents equal class counts for two classes with uniform votes. It does not prevent multiclass ties, weighted-vote ties or equal distances at the neighbor-selection cutoff. None of those is resolved just by drawing a larger radius.
Check the Representation
Here is an explicit representation failure rather than a claim that all high-dimensional distances are equal. With one useful coordinate, let q=0, circle A=1 and square B=2. A is nearer. Add a nuisance coordinate z: q=(0,0), A=(1,10), B=(2,0). The distances become for A and 2 for B, so B is now nearer.
All four bars use 35 SVG units per distance unit. Circle and square glyphs keep identity across rows; mint marks the nearer sample. Extra features and incompatible scales can distort a neighborhood. Scaling, feature selection or a learned metric should reflect the task, with any fitted preprocessing learned from training data.
Weight the Vote
Use the three closest points from the one-dimensional wrong-label example: a square at distance 0.5 and circles at 1 and 1.5. Uniform voting totals one square versus two circles. With inverse-distance weights, the square contributes , while the circles contribute . Square now wins.
The bars encode numeric vote weight at 100 SVG units per unit; they do not encode distance. The official neighbors guide distinguishes uniform and distance-weighted voting. The zero-distance case needs an explicit implementation policy; this fixture has no coincident query and sample. Weighting is a different model choice and can amplify a nearby mistake.
Move the Query
Restore the original five training points and their 40-unit spatial scale. Move q from (0,0), marked by the faint cross, to (1,0). The training coordinates stay fixed. Distances now rank A=1, B=2, E=, C=, D=. The selected neighbors are A, B and E, giving circle two votes against square one. The enlarged circle at right is the outcome symbol, not a sixth sample. Its neighborhood radius is SVG units.
Prediction changes because the query changes the ranking. There is no refitting of a global separator between these two queries.
Where It Breaks
A final one-dimensional counterexample uses circle samples at 0, 1 and 2, with q=10. The common scale is 40 SVG units per unit. The nearest observed sample is still 8 units away, shown by the upper bracket, but a k=3 vote is unanimously circle. The lower row repeats the three votes schematically; it adds no data.
k-NN always has nearest examples when enough samples exist, even when every example is too distant to support a useful inference. Unanimity alone cannot establish that the query belongs to the training distribution or that the prediction is correct. Inspect distance and coverage, validate under expected conditions, and define when an application should abstain. Neither a bigger k nor fewer features guarantees a repair.
The Quick Version
- k-NN stores labeled examples and predicts from a local neighborhood.
- The metric determines which points are nearest.
- Uniform voting gives each selected sample one vote.
- Changing k can change the predicted class.
- Larger neighborhoods can resist isolated errors and erase real detail.
- Ties require a policy beyond a blanket odd-k rule.
- Irrelevant features can reverse neighbor rankings.
- Distance weighting can amplify the nearest sample's influence.
- Moving a query changes its voting neighborhood.
- Unanimous distant votes do not prove reliable support.