PythiloLesson 4 of 8 · progress kept in this browser

Classify with nearest neighbours

Nearest-neighbour classification stores examples rather than fitting weights. Distance chooses nearby observations, and a vote chooses their label. Ties need deterministic rules: equal distances follow training order here, and equal vote counts choose the smaller label. Squared distance is sufficient because square root preserves the order of nonnegative distances.

point = (2, 3)
other = (5, 7)
print(sum((a-b)**2
          for a,b in zip(point, other)))
Your task

Write nearest_label(points, labels, query, k) for numeric vectors of equal dimension and integer labels. Use up to k nearest points (stable training order for distance ties), majority vote, then smaller label for vote ties. Reject k <= 0 or empty training data.