Vectorized KNN Classifier in NumPy

Quick Overview

Implement a k-nearest neighbors classifier in NumPy with fit, kneighbors, predict_proba and predict, computing Euclidean distances without looping over training points. It tests vectorized distance math, top-k selection with argpartition, deterministic tie-breaking and input validation.

Vectorized KNN Classifier in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a `KNNClassifier(k=5)` class in NumPy with `fit`, `kneighbors`, `predict_proba` and `predict`, using Euclidean distance and uniform voting. Distances must be computed without Python loops over training points (broadcasting or the expanded norm identity), and top-k selection must use `np.argpartition`. The methods must behave as follows: - `fit(X, y)` returns `self`. It raises `ValueError` if `X` is not 2-D, if `y` is not 1-D with one label per row of `X`, or if `k` does not satisfy `1 <= k <= n_train`. - `kneighbors(X)` returns `(dist, idx)`, each of shape `(m, k)`, sorted by ascending distance. Equal distances break to the lower training index. - `predict_proba(X)` returns an `(m, n_classes)` array of neighbour vote fractions, with columns ordered by the sorted unique training labels. - `predict(X)` returns the majority label using the original label values. A vote tie goes to the smallest label. - Queries that are not 2-D, or that have a different feature count from the training data, raise `ValueError`. Labels may be any sortable type, such as ints or strings. ```python X = [[1.0], [-2.0], [10.0]] y = [5, 2, 2] m = KNNClassifier(k=2).fit(X, y) m.kneighbors([[0.0]]) # (array([[1., 2.]]), array([[0, 1]])) m.predict_proba([[0.0]]) # array([[0.5, 0.5]]); columns are classes [2, 5] m.predict([[0.0]]) # array([2]); the 1-1 vote tie goes to the smaller label ``` When no two training points tie at the k-th neighbour distance, your results should match scikit-learn's `KNeighborsClassifier(algorithm="brute")`, which makes a good test oracle (compare distances with a small tolerance). scikit-learn does not define an order for ties at that boundary, so the lower-index rule above is part of this task's specification. ```hint Distances in one product Write the squared distance as $\|q\|^2 + \|x\|^2 - 2\,q \cdot x$. Think about what that buys you in memory compared with broadcasting the differences, and what floating-point rounding can do to the result when $q$ and $x$ are close. ``` ```hint What argpartition guarantees `np.argpartition` puts the k-th smallest value in its sorted position but leaves both sides unordered, and it gives no rule for equal values. Work out which training points have to be considered so that the lower-index tie rule still holds at the k-th distance. ``` ### Constraints & Assumptions - `X` has shape `(n_train, d)` and queries have shape `(m, d)`. Values are finite numbers. - `k` is an integer with `1 <= k <= n_train`. - The full `(m, n_train)` distance matrix fits in memory for this exercise. Bounding memory is a follow-up. ### What a Strong Answer Covers - A distance computation with no loop over training points, with its time and memory cost stated - Handling of the small negative squared distances that the expanded identity can produce - Top-k selection with `np.argpartition` that still returns ascending distances and honors the lower-index tie rule at the k-th boundary - Label encoding that keeps `predict_proba` columns sorted, returns original label values from `predict`, and sends vote ties to the smallest label - The input validation listed in the requirements ### Follow-up Questions - The expanded identity can produce small negative squared distances. Why does that happen, and how do you handle it? - How would you keep memory bounded for ${10^6}$ queries against ${10^6}$ training points? - How would you add distance-weighted voting?

Overview: Implement a k-nearest neighbors classifier in NumPy with fit, kneighbors, predict_proba and predict, computing Euclidean distances without looping over training points. It tests vectorized distance math, top-k selection with argpartition, deterministic tie-breaking and input validation.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement a KNNClassifier(k=5) class in NumPy with fit, kneighbors, predict_proba and predict, using Euclidean distance and uniform voting. Distances must be computed without Python loops over training points (broadcasting or the expanded norm identity), and top-k selection must use np.argpartition.

The methods must behave as follows:

  • fit(X, y) returns self . It raises ValueError if X is not 2-D, if y is not 1-D with one label per row of X , or if k does not satisfy 1 <= k <= n_train .
  • kneighbors(X) returns (dist, idx) , each of shape (m, k) , sorted by ascending distance. Equal distances break to the lower training index.
  • predict_proba(X) returns an (m, n_classes) array of neighbour vote fractions, with columns ordered by the sorted unique training labels.
  • predict(X) returns the majority label using the original label values. A vote tie goes to the smallest label.
  • Queries that are not 2-D, or that have a different feature count from the training data, raise ValueError .

Labels may be any sortable type, such as ints or strings.

X = [[1.0], [-2.0], [10.0]]
y = [5, 2, 2]
m = KNNClassifier(k=2).fit(X, y)
m.kneighbors([[0.0]])     # (array([[1., 2.]]), array([[0, 1]]))
m.predict_proba([[0.0]])  # array([[0.5, 0.5]]); columns are classes [2, 5]
m.predict([[0.0]])        # array([2]); the 1-1 vote tie goes to the smaller label

When no two training points tie at the k-th neighbour distance, your results should match scikit-learn's KNeighborsClassifier(algorithm="brute"), which makes a good test oracle (compare distances with a small tolerance). scikit-learn does not define an order for ties at that boundary, so the lower-index rule above is part of this task's specification.

Constraints & Assumptions

  • X has shape (n_train, d) and queries have shape (m, d) . Values are finite numbers.
  • k is an integer with 1 <= k <= n_train .
  • The full (m, n_train) distance matrix fits in memory for this exercise. Bounding memory is a follow-up.

What a Strong Answer Covers Guidance

  • A distance computation with no loop over training points, with its time and memory cost stated
  • Handling of the small negative squared distances that the expanded identity can produce
  • Top-k selection with np.argpartition that still returns ascending distances and honors the lower-index tie rule at the k-th boundary
  • Label encoding that keeps predict_proba columns sorted, returns original label values from predict , and sends vote ties to the smallest label
  • The input validation listed in the requirements

Follow-up Questions Guidance

  • The expanded identity can produce small negative squared distances. Why does that happen, and how do you handle it?
  • How would you keep memory bounded for 106{10^6} queries against 106{10^6} training points?
  • How would you add distance-weighted voting?