InterviewPrepKit

Home / Coding / Machine Learning Coding / Clustering & Neighbors / k-Nearest-Neighbors Classifier

k-Nearest-Neighbors Classifier

medium 00:00
Solving tips
  • Vectorize the distance computation with broadcasting instead of Python loops over pairs.
  • Pin down your tie-breaking rule up front so the output is deterministic and defensible.

k-Nearest-Neighbors is the simplest non-parametric classifier: to label a query point, look at the k closest labeled examples and take a vote. There is no training step beyond storing the data, which makes the whole problem about computing distances efficiently and resolving votes deterministically.

Task

Implement knn_predict(X_train, y_train, X_test, k). For each row of X_test:

  1. Compute the Euclidean distance to every row of X_train.
  2. Select the k training points with the smallest distances.
  3. Return the majority label among those k neighbors.

Compute the pairwise distances with vectorized NumPy (broadcasting), not nested Python loops. Break ties deterministically: when several training points are equidistant, prefer the one with the smaller index; when two labels receive the same vote count, prefer the smaller label id. Return an integer array of shape (n_test,).

Example

import numpy as np

X_train = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [5.0, 5.0], [6.0, 5.0]])
y_train = np.array([0, 0, 0, 1, 1])
X_test = np.array([[0.5, 0.5], [5.5, 5.0]])

print(knn_predict(X_train, y_train, X_test, k=3))
# [0 1]

Constraints

  • X_train has shape (n_train, d), X_test has shape (n_test, d), y_train has shape (n_train,).
  • 1 <= k <= n_train; labels are non-negative integers.
  • Use only NumPy; do not call scikit-learn, SciPy, or any distance/kNN helper.
  • Distances must be computed in a vectorized manner (no explicit per-pair Python loop).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug