LearnCoding

k-nearest-neighbour classifier

EasyK-NN, NumPy

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']
True

Solve it in your own editor; nothing on this page runs code.

Hints

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 out

What 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).

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.