Skip to content

k-nearest neighbours

learning

Level 1 of 3

Also called k-NN and Nearest neighbour classification.

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.

024681002468104.244.473.162.833.614.125.66
Seven points and a new one at 5 across, 5 up, each distance written by its point. The ring holds the 3 nearest, two circles and a square, so the new point becomes a circle.
05100246810
Hold out the triangle at 1 across, 8 up. Its shape is hidden, and its nearest others vote. A noisy square at 2 across, 8 up is 1 away. With k = 3 the ring holds that square and two triangles, so the triangle gets its own shape back. Right. With k = 1 the square alone would decide. Wrong.
02468100246810
051013579111315kpoints wrongpoints given the wrong class

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.

Three groups of six and a new point at 5 across, 5 up, every part of the plane shaded by the class a new point there would get. At k = 3 the ring holds one of each shape. The triangle at 3, 6 and the circle at 4, 3 are both 2.24 away. The points are listed triangles, then squares, then circles, so the triangle counts as nearer and wins. The chart counts the points given the wrong class when each is held out. With the noise added, k = 1 gets 15 wrong, k = 3 only the 3 noisy points, and k = 15 gets 9.
Three nearest vote: 7 moments of its 11 steps, the steps between them left for the watch page
  1. step 1 of 11

    02468100246810

    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.

    watch from here

  2. step 2 of 11

    024681002468104.24

    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.

    watch from here

  3. step 5 of 11

    024681002468104.244.473.162.83

    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.

    watch from here

  4. step 8 of 11

    024681002468104.244.473.162.833.614.125.66

    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.

    watch from here

  5. step 9 of 11

    024681002468103.162.833.61

    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.

    watch from here

  6. step 10 of 11

    024681002468103.162.833.61

    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

    watch from here

  7. step 11 of 11

    024681002468103.162.833.61

    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

    watch from here

the steps, in plain words
  1. for the new pointPython line 4
  2. measure how far each point is from itPython lines 11, 12 and 13
  3. take the k nearestPython line 14
  4. count each class among themPython lines 15, 16 and 17
  5. 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 nn points measures exactly nn, so the points sit on the line.

distances measured, ten times more at each mark up

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, 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
what a set of points costs, at a billion distances measured a second
nndistances measuredtime
1,0001,000about 1 microsecond
100,000100,000about 100 microseconds
10,000,00010,000,000about 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
averageevery set of points, wherever they stand
distances measurednn
how the distances measured grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)
ceiling, OOO(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)

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.

pointskdistances
414
434
636
Four points with k = 1 and k = 3, and six points with k = 3. The distances follow the points, never k.

where the formula comes from

The count above, worked out in small steps, each naming the line it comes from.

Why does k-nearest neighbours measure exactly nn distances, on every set of points?
  1. the move: see the measuring

    the line:
    each point is measuredonce from the new point\begin{gathered} \text{each point is measured} \\ \text{once from the new point} \end{gathered}
    0246810024681054.472.242.83
    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.

  2. the move: one for each point

    the line:
    D=1+1+⋯+1D = 1 + 1 + \dots + 1

    why it is allowed: DD is the distances measured. By line 1, one for each of the nn points.

  3. the move: add the ones

    the line:
    D=nD = n

    why it is allowed: By line 2, nn ones add up to nn. For the four points, 4.

  4. the move: any set, any k

    the line:
    the same for every setof n points and every k\begin{gathered} \text{the same for every set} \\ \text{of } n \text{ points and every } k \end{gathered}

    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.

  5. the move: a ceiling

    the line:
    D≤nD \le n

    why it is allowed: By line 3, DD is nn, so it is at most nn.

  6. the move: read it as a bound

    the line:
    D∈O(n)D \in O(n)

    why it is allowed: By line 5, DD is at most 1 times nn.

  7. the move: a floor

    the line:
    D≥nD \ge n

    why it is allowed: By line 3, DD is at least nn too.

  8. the move: read it as a bound

    the line:
    D∈Ω(n)D \in \Omega(n)

    why it is allowed: By line 7, DD never drops below 1 times nn.

  9. the move: ceiling and floor together

    the line:
    D∈Θ(n)D \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound DD by the same growth, nn.

try it on small inputs: over every set of 4 points, wherever they stand, the average is D=4D = 4

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.

2 8 t, 7 8 s, 6 2 c, 3 2 c; 5 4; 3, every step written down
stepwhat happensdistances measured
14 points already have a class. The new point, ringed in ink, has none yet. The 3 nearest points vote.0
2This point is 5 from the new one, measured in a straight line.1
3This point is 4.47 from the new one, measured in a straight line.2
4This point is 2.24 from the new one, measured in a straight line.3
5This point is 2.83 from the new one, measured in a straight line.4
6The ring reaches out 4.47, just far enough to hold the 3 nearest points. The others are ruled out.4
7Inside the ring: 0 triangles, 1 square and 2 circles.4
8There 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, nn, gives D=4D = 4 at n=4n = 4: 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.

02468100246810
With k = 1 the nearest point alone decides. The triangle at 4 across, 6 up is 1.41 away, so the new point becomes a triangle.
02468100246810
The same plane with k = 3. Two circles outvote one triangle, so the new point becomes a circle.

race them on one row of your own