Skip to content
AI360XpertBeta
Core ML

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-NN retains labeled examples for future queries.
k-NN retains labeled examples for future queries.

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

Euclidean distance ranks A nearest to the query.
Euclidean distance ranks A nearest to the query.

For this example, calculate Euclidean distance d(q,x)=(x1−q1)2+(x2−q2)2d(q,x)=\sqrt{(x_1-q_1)^2+(x_2-q_2)^2}. A is 2 away. B is 1+4=5≈2.2361\sqrt{1+4}=\sqrt5\approx2.2361; C is 8≈2.8284\sqrt8\approx2.8284; D is 10≈3.1623\sqrt{10}\approx3.1623; E is 13≈3.6056\sqrt{13}\approx3.6056. 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

The nearest three give the square class two votes.
The nearest three give the square class two votes.

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 408≈113.13740\sqrt8\approx113.137 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

Changing k from one to three flips this prediction.
Changing k from one to three flips this prediction.

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

A larger vote can resist one nearby wrong label.
A larger vote can resist one nearby 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

Four neighbors can leave a binary vote tied.
Four neighbors can leave a binary vote tied.

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

An irrelevant feature can reverse the nearest neighbor.
An irrelevant feature can reverse the nearest neighbor.

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 101≈10.0499\sqrt{101}\approx10.0499 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

Distance weighting can reverse a uniform vote.
Distance weighting can reverse a uniform 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 1/0.5=21/0.5=2, while the circles contribute 1+1/1.5=5/31+1/1.5=5/3. 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

Moving the query can change which samples vote.
Moving the query can change which samples vote.

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=10\sqrt{10}, C=13\sqrt{13}, D=17\sqrt{17}. 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 4010≈126.49140\sqrt{10}\approx126.491 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 unanimous vote can still come from distant examples.
A unanimous vote can still come from distant examples.

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.