k-nearest-neighbour classifier
Problem
Classify each test point by majority vote among its k nearest training points (Euclidean). Break distance ties by the lower training index, and vote ties by the smallest label.
Signature
def knn_predict(X_train, y_train: list, X_test, k: int) -> list: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> knn_predict([[0.0],[1.0],[10.0]], ['a','a','b'], [[0.4],[9.0]], 1) == ['a', 'b']
True
>>> knn_predict([[0.0],[1.0],[10.0]], ['a','a','b'], [[9.0]], 3) == ['a']
TrueHints
For each test point, compute vectorised distances to all training points.
Take the k nearest; break distance ties by lower training index.
Vote ties by the smallest label — keep it deterministic.
Reference solution
from collections import Counter
import numpy as np
def knn_predict(X_train, y_train, X_test, k):
Xtr = np.asarray(X_train, float)
out = []
for x in np.asarray(X_test, float):
d = ((Xtr - x) ** 2).sum(1)
order = np.argsort(d, kind="stable")[:k]
votes = Counter(y_train[i] for i in order)
best = max(votes.values())
out.append(min(l for l, c in votes.items() if c == best))
return outWhat a strong solution covers
- Stable sort or argpartition plus deterministic tie handling.
- Complexity O(n_test · n_train · d).
- Mentions KD-trees/ANN for scale, feature scaling, and distance weighting.
Common mistakes
- a non-stable sort giving nondeterministic neighbours
- forgetting to scale features (discussion point).