k-nearest neighbours
how it works
The idea in a few sentences and three pictures, then one new point placed step by step.
To give a new point a class, k-nearest neighbours measures how far every point is from it, keeps the k nearest, and lets them vote. Below, the new point stands at 5 across, 5 up among seven points, and k is 3. The circle at 7, 3 is 2 across and 2 down. 2 squared is 4, so its distance is the root of 4 + 4 = 8, about 2.83. The three nearest are that circle, a square 3.16 away and a circle 3.61 away. Two circles beat one square, so the new point becomes a circle. A tie between shapes goes to the nearest of them; equally near, the point that comes first in the list of points counts as nearer. Every point is measured, so n points cost n distances, whatever k is. The next picture holds one point out, to see whether the vote gets its shape right. The last lets you choose k, and add three noisy points.
With k = 3, the ring reaches 2.83 and the new point becomes a triangle. Each point held out in turn, 0 get the wrong class.
With scripts on, a slider moves k from 1 to 15 and a switch adds three noisy points. The plane, the chart and this line change with them.
step 1 of 11
7 points already have a class. The new point, ringed in ink, has none yet. The 3 nearest points vote.
what it remembers to know where it is
- distance in hand
- not yet
- triangles among the nearest
- not yet
- squares among the nearest
- not yet
- circles among the nearest
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 11
This point is 4.24 from the new one, measured in a straight line.
what it remembers to know where it is
- distance in hand
- 4.24
- triangles among the nearest
- not yet
- squares among the nearest
- not yet
- circles among the nearest
- not yet
Where it says not yet, nothing is held there at that moment.
step 5 of 11
This point is 2.83 from the new one, measured in a straight line.
what it remembers to know where it is
- distance in hand
- 2.83
- triangles among the nearest
- not yet
- squares among the nearest
- not yet
- circles among the nearest
- not yet
Where it says not yet, nothing is held there at that moment.
step 8 of 11
This point is 5.66 from the new one, measured in a straight line.
what it remembers to know where it is
- distance in hand
- 5.66
- triangles among the nearest
- not yet
- squares among the nearest
- not yet
- circles among the nearest
- not yet
Where it says not yet, nothing is held there at that moment.
step 9 of 11
The ring reaches out 3.61, just far enough to hold the 3 nearest points. The others are ruled out.
what it remembers to know where it is
- distance in hand
- 3.61
- triangles among the nearest
- not yet
- squares among the nearest
- not yet
- circles among the nearest
- not yet
Where it says not yet, nothing is held there at that moment.
step 10 of 11
Inside the ring: 0 triangles, 1 square and 2 circles.
what it remembers to know where it is
- distance in hand
- 3.61
- triangles among the nearest
- 0
- squares among the nearest
- 1
- circles among the nearest
- 2
step 11 of 11
There are more circles than any other shape, so the new point becomes a circle.
what it remembers to know where it is
- distance in hand
- 3.61
- triangles among the nearest
- 0
- squares among the nearest
- 1
- circles among the nearest
- 2
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- for the new pointPython line 4
- measure how far each point is from itPython lines 11, 12 and 13
- take the k nearestPython line 14
- count each class among themPython lines 15, 16 and 17
- give it the class with the most votesPython lines 18, 19, 20 and 21
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from math import dist
def k_nearest_neighbours(points, new_point, k):
"""The shape most of the k points nearest to new_point have.
Each point is a tuple (across, up, shape), the shape "triangle",
"square" or "circle"; new_point is (across, up). Distance is measured
in a straight line. A tie between shapes goes to the nearest of them.
"""
measured = []
for place, (x, y, shape) in enumerate(points): # every point
measured.append((dist((x, y), new_point), place, shape)) # one distance
nearest = sorted(measured)[:k] # nearest first; equally near, the first written
votes = {}
for _, _, shape in nearest: # count each shape among the k
votes[shape] = votes.get(shape, 0) + 1
most = max(votes.values())
for _, _, shape in nearest: # the nearest shape with the most votes
if votes[shape] == most:
return shape
how it scales
How the distances grow, from ten points to a hundred thousand.
Each step across or up is ten times the one before, a log-log plot. The line climbs one step up for each step across: ten times the points, ten times the distances. Every set of points measures exactly , so the points sit on the line.
distances measured, ten times more at each mark up
, how many points have a class, ten times more at each mark to the right
- every set of points, wherever they standsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
| distances measured | time | |
|---|---|---|
| 1,000 | 1,000 | about 1 microsecond |
| 100,000 | 100,000 | about 100 microseconds |
| 10,000,000 | 10,000,000 | about 10 milliseconds |
The distances measured are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count k-nearest neighbours' distances yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n it scatters n points with a
shape each over a square of whole-numbered spots, places a new point on a
spot of its own, and prints how many distances the method measures with k = 3,
up to n = 100,000. The counts are the same on any computer; only the time
differs.
"""
import random
from math import dist
def k_nearest_neighbours(points, new_point, k):
"""The shape most of the k points nearest to new_point have.
Each point is a tuple (across, up, shape), the shape "triangle",
"square" or "circle"; new_point is (across, up). Distance is measured
in a straight line. A tie between shapes goes to the nearest of them.
"""
measured = []
for place, (x, y, shape) in enumerate(points): # every point
measured.append((dist((x, y), new_point), place, shape)) # one distance
nearest = sorted(measured)[:k] # nearest first; equally near, the first written
votes = {}
for _, _, shape in nearest: # count each shape among the k
votes[shape] = votes.get(shape, 0) + 1
most = max(votes.values())
for _, _, shape in nearest: # the nearest shape with the most votes
if votes[shape] == most:
return shape
def count(points, new_point, k):
"""The same method on points, counting each distance it measures."""
distances = 0
for x, y, _ in points:
dist((x, y), new_point)
distances += 1 # one distance for each point
return distances
def scatter(n, seed):
"""n points with a shape each on distinct spots, and a new point on a spot of its own."""
rng = random.Random(seed)
side = max(10, int((2 * (n + 1)) ** 0.5) + 1)
spots = rng.sample(range((side + 1) ** 2), n + 1)
at = [(s % (side + 1), s // (side + 1)) for s in spots]
shapes = ("triangle", "square", "circle")
return [(x, y, rng.choice(shapes)) for x, y in at[:n]], at[n]
if __name__ == "__main__":
print(f"{'n':>7} {'distances':>10}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
points, new_point = scatter(n, n)
print(f"{n:>7} {count(points, new_point, 3):>10}")
best, worst and average
No set of points is cheaper or dearer than another, so the grid has one column.
A case is one kind of input, the thing the method is given, such as a set of points. A bound says how fast that case's cost grows as more points come in.
The count is in the grid: one distance for each point, n in all, on every set of points, so the three bounds all grow as n.
| averageevery set of points, wherever they stand | |
|---|---|
| distances measured | |
| how the distances measured grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: the n distances, kept and sorted to find the k nearest
Extra memory is the room it needs on top of the input itself, while it runs.
| points | k | distances |
|---|---|---|
| 4 | 1 | 4 |
| 4 | 3 | 4 |
| 6 | 3 | 6 |
where the formula comes from
The count above, worked out in small steps, each naming the line it comes from.
the move: see the measuring
the line:Four points and a new one at 5 across, 4 up. Each point's distance is written beside it, 5, 4.47, 2.24 and 2.83. Four distances. why it is allowed: The run measures every point in turn, once, before any vote. The picture measures four.
the move: one for each point
the line:why it is allowed: is the distances measured. By line 1, one for each of the points.
guess it, thenthe move: add the ones
the line:why it is allowed: By line 2, ones add up to . For the four points, 4.
guess it, thenthe move: any set, any k
the line:why it is allowed: In line 1, how many points are measured never depends on where they stand or on k, only on their being there.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, is , so it is at most .
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, is at most 1 times .
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, is at least too.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, never drops below 1 times .
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it on small inputs: over every set of 4 points, wherever they stand, the average is
count it yourself
Count every step on four points, k = 3. A point such as 2 8 t is a triangle at 2 across, 8 up (s is a square, c a circle). After the semicolons come the new point, then k. The first row only starts; then come 4 distances, the ring, the vote and the verdict. Then check the distances against the formula.
| step | what happens | distances measured |
|---|---|---|
| 1 | 4 points already have a class. The new point, ringed in ink, has none yet. The 3 nearest points vote. | 0 |
| 2 | This point is 5 from the new one, measured in a straight line. | 1 |
| 3 | This point is 4.47 from the new one, measured in a straight line. | 2 |
| 4 | This point is 2.24 from the new one, measured in a straight line. | 3 |
| 5 | This point is 2.83 from the new one, measured in a straight line. | 4 |
| 6 | The ring reaches out 4.47, just far enough to hold the 3 nearest points. The others are ruled out. | 4 |
| 7 | Inside the ring: 0 triangles, 1 square and 2 circles. | 4 |
| 8 | There are more circles than any other shape, so the new point becomes a circle. | 4 |
In all, 4 distances measured. The formula from section 4, , gives at : the same.
where you meet it
The method is old, simple, and still offered by toolkits such as scikit-learn.
scikit-learn, a Python library for machine learning
Its k-nearest neighbours tool asks 5 neighbours unless told otherwise, and by default each vote counts the same; it can instead let nearer points count more. To find the nearest it can sort the points into regions ahead of time, so a search skips the regions far from the new point, rather than measure every one.
source: scikit-learn's documentation, the user guide's section on nearest neighbours and the KNeighborsClassifier reference
where it began
Evelyn Fix and Joseph Hodges described the method in a 1951 report for the US Air Force School of Aviation Medicine. In 1967 Thomas Cover and Peter Hart proved that, with enough points, one nearest neighbour is wrong at most twice as often as the best possible rule. That rule knows exactly how each shape's points are spread.
source: Fix and Hodges, Discriminatory Analysis, Nonparametric Discrimination, USAF School of Aviation Medicine, 1951; Cover and Hart, Nearest Neighbor Pattern Classification, IEEE Transactions on Information Theory, 1967
what is used instead
With many points, measuring every one is slow. A k-d tree, from Jon Bentley's 1975 paper, cuts the plane in two, then each half in two again, and so on. A search then skips the parts far from the new point. Its k counts directions, 2 on a plane, across and up, not neighbours. When the classes split along a line, a rule that learns the line once answers each new point in a few steps.
how it compares
k-nearest neighbours beside itself with another k. One plane, two answers.