Lensa ML
Lensa ML

K-Nearest Neighbors

Step 1 of 6

The Nearest Neighbor

Classification by proximity

-3-2-10123-3-2-10123xyquery
x = -3x = 0.0x = 3
y = -3y = 0.3y = 3
QUERY
(0.0, 0.3)
NEAREST
Class C
DISTANCE
0.39
PREDICTION
C

k-NN classifies a point by looking at its closest neighbors. With k=1, the query point is assigned the class of its single nearest neighbor — here, class C at distance 0.39. Drag the sliders to move the query point and see how the nearest neighbor changes.

Step 1 of 6: The Nearest Neighbor

Classification by proximity

-3-2-10123-3-2-10123xyquery
x = -3x = 0.0x = 3
y = -3y = 0.3y = 3
QUERY
(0.0, 0.3)
NEAREST
Class C
DISTANCE
0.39
PREDICTION
C

k-NN classifies a point by looking at its closest neighbors. With k=1, the query point is assigned the class of its single nearest neighbor — here, class C at distance 0.39. Drag the sliders to move the query point and see how the nearest neighbor changes.

Step 2 of 6: Choosing k

How many neighbors to ask

-3-2-10123-3-2-10123xyVotesA: 0B: 2C: 1
k = 1k = 3k = 15
K
3
MAJORITY
Class B
VOTES
0/2/1
CONFIDENCE
67%

With k=3, the prediction takes a majority vote among 3 neighbors, balancing local detail with some smoothing.

Step 3 of 6: Distance Metrics

Euclidean vs. Manhattan

-3-2-10123-3-2-10123xyd=0.49d=0.51d=0.74query
x = -3x = 0.5x = 3
y = -3y = 0.8y = 3
METRIC
Euclidean
NEAREST D
0.49
FARTHEST D
0.86
PREDICTION
B

Euclidean distance measures the straight-line path — √(Δx² + Δy²). The equal-distance boundary is a circle. Toggle to Manhattan to see how grid-walk distance picks different neighbors.

Step 4 of 6: Decision Boundaries

The Voronoi landscape

-3-2-10123-3-2-10123xy
k = 1k = 1k = 15
K
1
TRAIN ACC
100%
EDGES
91
SMOOTHNESS
Low

With k=1, the boundary hugs every point — notice the isolated islands around outliers. Train accuracy is 100% but this overfits badly.

Step 5 of 6: Distance Weighting

Closer neighbors matter more

14%A · d=1.014%B · d=3.014%A · d=6.014%C · d=10.014%B · d=15.014%A · d=22.014%C · d=30.0query
WEIGHTED VOTE
A
43%
B
29%
C
28%
uniform (0)exp = 0.0sharp (5)
EXPONENT
0.0
PREDICTION
A
CONFIDENCE
43%
RATIO
1:1

Uniform weighting: all 7 neighbors vote equally. The vote is purely a headcount — a distant neighbor counts the same as the closest one.

Step 6 of 6: The Curse of High Dimensions

When distance loses meaning

querynearestfarthestDistance from query0.300.310.671.191.201.211.241.271.271.281.401.431.491.621.6281%
2D2 dimensions200D
DIMENSIONS
2
NEAREST
0.30
FARTHEST
1.62
GAP
81%

In 2D, the nearest point (0.30) is much closer than the farthest (1.62) — a 81% gap. k-NN can clearly tell neighbors apart.