Understanding AI · lesson 14 of 60 · about 6 minutes
Nearest Neighbour
The simplest learning method there is: to label something new, copy the label of its closest example.
What you'll learn
- Explain the nearest neighbour method
- Find the closest example by hand
- Use nearest neighbour to label a new example
Copy your closest neighbour
Here's a real machine learning method that fits in one sentence: to label a new example, find the training example most like it, and copy its label.
It's called nearest neighbour. New fruit with smoothness 8? The closest example is an apple with 8, so: apple.
Nearest neighbour on one feature. `abs()` gives the size of a difference, ignoring minus signs.
examples = [(9, "apple"), (8, "apple"), (3, "orange"), (2, "orange")]
new_smooth = 7
best_label = ""
best_gap = 100
for smooth, label in examples:
gap = abs(smooth - new_smooth)
if gap < best_gap:
best_gap = gap
best_label = label
print(best_label)Output
appleTip
The loop keeps track of the smallest gap so far, and the label that went with it.
Now try it yourself
This lesson is free in Codiqo, with 6 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.