Machine Learning from Scratch · Classifying

k-Nearest Neighbours: Judge by the Company

Classify a new fruit as an apple or a lemon by measuring how far it is from every known fruit and letting its nearest neighbours vote.

knn.py

# Each fruit has a size and a sweetness, both from 1 to 10.
xs = [7, 8, 6, 3, 2, 4, 5]
ys = [8, 6, 7, 2, 4, 3, 5]
labels = ["apple", "apple", "apple", "lemon", "lemon", "lemon", "lemon"]

new_x, new_y = 6, 5   # a new fruit: is it an apple or a lemon?
k = 3                 # ask its 3 nearest neighbours

distances = []
for i in range(len(xs)):
    d = ((xs[i] - new_x) ** 2 + (ys[i] - new_y) ** 2) ** 0.5
    distances.append((d, i))

distances.sort()
nearest = distances[:k]

votes = {}
for d, i in nearest:
    label = labels[i]
    votes[label] = votes.get(label, 0) + 1

prediction = max(votes, key=votes.get)
print("Prediction:", prediction)

Step by step

  1. Seven fruits we already know. xs holds the size of each one, from 1 to 10.
  2. ys holds how sweet each one is. Together, xs[i] and ys[i] place fruit i on the chart: size across, sweetness up.
  3. labels holds the answer for each known fruit. On the chart, apples are red and lemons are amber. Apples are big and sweet (top right); lemons are small and sour (bottom left).
  4. A new fruit arrives: size 6, sweetness 5. It is the star on the chart, with a "?" because we do not know what it is yet.
  5. k is how many neighbours get a vote. With k = 3, the 3 known fruits closest to the star will decide.
  6. An empty list to collect one distance per known fruit.
  7. Fruit 0 next: the apple at (7, 8). The ring on the chart marks the fruit being measured.
  8. The distance from the new fruit, with Pythagoras: √((7−6)² + (8−5)²) = √10 ≈ 3.16. It is the length of a straight line between them on the chart.
  9. (3.16, 0) is added to the list: the distance and which fruit it belongs to. A dashed line now joins the star to fruit 0, labelled with its length.
  10. Fruit 1 next: the apple at (8, 6). The ring on the chart marks the fruit being measured.
  11. √((8−6)² + (6−5)²) = √5 ≈ 2.24.
  12. (2.24, 1) is stored. One more dashed line on the chart.
  13. Fruit 2 next: the apple at (6, 7). The ring on the chart marks the fruit being measured.
  14. √((6−6)² + (7−5)²) = √4 = 2.
  15. (2.0, 2) is stored. One more dashed line on the chart.
  16. Fruit 3 next: the lemon at (3, 2). The ring on the chart marks the fruit being measured.
  17. √((3−6)² + (2−5)²) = √18 ≈ 4.24.
  18. (4.24, 3) is stored. One more dashed line on the chart.
  19. Fruit 4 next: the lemon at (2, 4). The ring on the chart marks the fruit being measured.
  20. √((2−6)² + (4−5)²) = √17 ≈ 4.12.
  21. (4.12, 4) is stored. One more dashed line on the chart.
  22. Fruit 5 next: the lemon at (4, 3). The ring on the chart marks the fruit being measured.
  23. √((4−6)² + (3−5)²) = √8 ≈ 2.83.
  24. (2.83, 5) is stored. One more dashed line on the chart.
  25. Fruit 6 next: the lemon at (5, 5). The ring on the chart marks the fruit being measured.
  26. √((5−6)² + (5−5)²) = √1 = 1. Only 1 away: this lemon is the closest fruit of all.
  27. (1.0, 6) is stored. One more dashed line on the chart.
  28. All seven fruits are measured, so the loop ends. The chart shows a line from the star to every fruit.
  29. sort() puts the list in order of distance, nearest first: (1, 6), (2, 2), (2.24, 1), (2.83, 5)...
  30. distances[:k] keeps the first 3: the lemon at 1, and the apples at 2 and 2.24. On the chart they get bold lines, inside a dashed circle.
  31. An empty dictionary to count votes, one count per kind of fruit.
  32. The first neighbour: fruit 6, at distance 1. Its ring lights up on the chart.
  33. labels[6] is "lemon".
  34. One vote for lemon. votes.get(label, 0) reads the count so far, or 0 if there is none yet, then adds 1.
  35. The second neighbour: fruit 2, at distance 2.
  36. Fruit 2 is an apple.
  37. One vote for apple. It is 1 to 1 so far.
  38. The third neighbour: fruit 1, at distance 2.24.
  39. Another apple.
  40. Apple now has 2 votes, lemon 1.
  41. All 3 neighbours have voted, so the loop ends.
  42. max(votes, key=votes.get) picks the kind with the most votes: apple, 2 to 1. The star turns red: the new fruit is classified as an apple.
  43. It prints the answer. The closest fruit was a lemon, but its neighbourhood is mostly apples, and with k = 3 the neighbourhood decides. Try k = 1 above to see the other answer.