k-Nearest Neighbours Classifier

easy
Unit 3 · Classification II0/2 to milestone

k-NN classifies a point by majority vote among the kk closest training points. There's no training step, just distance calculations.

Implement knn_predict(X_train, y_train, X_test, k) returning a NumPy array with one predicted label per test point.

Rules

  • Use squared Euclidean distance.
  • If two training points are equally far away, the one with the lower index counts as closer.
  • If the vote is tied, choose the tied label whose neighbour is closest.
  • Labels can be any type (ints, strings…). Vectorise the distance calculation rather than looping over pairs.

Example

X = [[0, 0], [1, 0], [0, 1], [5, 5], [6, 5], [5, 6]]
y = [0, 0, 0, 1, 1, 1]
knn_predict(X, y, [[0.2, 0.1], [5.5, 5.5]], k=3)   # array([0, 1])
#classification#numpy3 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
k-Nearest Neighbours Classifier · TechGradify