CLASSIFICATION · 9 MIN
Classification & k-NN
Classification predicts a category; k-nearest neighbours votes among the closest examples.
PIXEL explains
- Measure distance between points, usually Euclidean.
- Take the k closest training examples and pick the most common label.
- Small k is noisy, large k blurs boundaries — choose k with validation data.
Real world: Guessing a fruit by comparing it to the most similar fruits you've seen.
Code
from collections import Counter
data = [((1, 1), "apple"), ((1, 2), "apple"), ((8, 8), "lime"), ((9, 8), "lime"), ((2, 1), "apple")]
def knn(p, k=3):
near = sorted(data, key=lambda d: (d[0][0]-p[0])**2 + (d[0][1]-p[1])**2)[:k]
return Counter(l for _, l in near).most_common(1)[0][0]
print(knn((2, 2)), knn((7, 9)))Output ›
apple limeTry it in the online compiler →Checkpoint quiz
Predicting 'spam' or 'not spam' is…