Implement k-nearest neighbors with efficient distance computation
Written by the mlprep team · Updated
Implement k-nearest neighbors classification from scratch in NumPy. Focus on making the distance computation vectorized and efficient — no for loops over data points. Then discuss: what's the computational bottleneck and how would you address it at scale?
Vectorized KNN implementation#
The key insight: computing pairwise Euclidean distances can be done with matrix multiplication instead of loops.
For vectors a and b:
||a - b||² = ||a||² + ||b||² - 2·a·b
This means: compute all squared norms, do one big matrix multiply, and combine.
import numpy as np
from collections import Counter
class KNN:
def __init__(self, k=5):
self.k = k
def fit(self, X_train, y_train):
self.X_train = X_train # (n_train, d)
self.y_train = y_train # (n_train,)
def predict(self, X_test):
dists = self._compute_distances(X_test) # (n_test, n_train)
# Get indices of k nearest neighbors
k_nearest_idx = np.argpartition(dists, self.k, axis=1)[:, :self.k]
# Get labels of k nearest neighbors
k_nearest_labels = self.y_train[k_nearest_idx] # (n_test, k)
# Majority vote
predictions = np.array([
Counter(row).most_common(1)[0][0]
for row in k_nearest_labels
])
return predictions
def _compute_distances(self, X_test):
# ||a - b||² = ||a||² + ||b||² - 2·a·b
# Shapes: X_test (n_test, d), X_train (n_train, d)
test_sq = np.sum(X_test ** 2, axis=1, keepdims=True) # (n_test, 1)
train_sq = np.sum(self.X_train ** 2, axis=1) # (n_train,)
cross = X_test @ self.X_train.T # (n_test, n_train)
dists_sq = test_sq + train_sq - 2 * cross # (n_test, n_train)
# Clamp numerical errors that produce tiny negatives
np.maximum(dists_sq, 0, out=dists_sq)
return dists_sq # Return squared distances (ranking is preserved)Why this works#
X_test @ X_train.Tcomputes all pairwise dot products in one BLAS call — O(n_test × n_train × d) but with hardware-optimized matrix multiplication- No Python loops over data points
argpartitionfinds the k smallest elements in O(n) per row, faster than full sort O(n log n)- We return squared distances since sqrt is monotonic and doesn't change the ranking
Shape walkthrough#
X_test: (1000, 784) — 1000 test images, 784 pixels each
X_train: (60000, 784) — 60000 training images
test_sq: (1000, 1) — squared norm of each test vector
train_sq: (60000,) — squared norm of each train vector (broadcasts)
cross: (1000, 60000) — all pairwise dot products
dists_sq: (1000, 60000) — all pairwise squared distances
Computational analysis#
- Time: O(n_test × n_train × d) for the matrix multiply
- Memory: O(n_test × n_train) for the distance matrix
- For MNIST (60K training, 784 dims): the distance matrix is 60K × 784 × 4 bytes ≈ 180MB per batch of 1000 test points
Scaling problems and solutions#
-
Memory: the full (n_test × n_train) distance matrix may not fit in RAM. Fix: process test points in batches and only keep the top-k indices.
-
Computation: brute-force is O(n × d) per query. For millions of points:
- KD-trees: partition space recursively. O(log n) per query in low dimensions. Degrades to O(n) when d > ~20.
- Ball trees: like KD-trees but use hyperspheres. Better for moderate dimensions.
- Approximate nearest neighbors (ANN): FAISS, ScaNN, Annoy. Use locality-sensitive hashing or graph-based search. O(log n) per query even in high dimensions, at the cost of occasionally missing the true nearest neighbor.
-
Dimensionality: high-d spaces make distances meaningless ("curse of dimensionality" — all points become equidistant). Fix: PCA or learned embeddings before KNN.
Interview red flags#
- Computing distances with nested Python loops instead of the ‖a‖² + ‖b‖² − 2a·b matrix identity.
- Fully sorting all distances (O(n log n)) when argpartition finds the k smallest in O(n).
- Forgetting feature scaling, so one large-range feature dominates the distance.
- Claiming brute-force KNN scales to millions of points instead of reaching for approximate nearest neighbor indexes.
Good. Now: your argpartition finds the k nearest neighbors, but then you do a Python loop for majority voting. Can you vectorize the majority vote too?
Yes. If we know the number of classes, we can use one-hot encoding and sum:
def predict_vectorized(self, X_test):
dists = self._compute_distances(X_test)
k_nearest_idx = np.argpartition(dists, self.k, axis=1)[:, :self.k]
k_nearest_labels = self.y_train[k_nearest_idx] # (n_test, k)
# Vectorized majority vote using bincount
n_classes = int(self.y_train.max()) + 1
n_test = X_test.shape[0]
# One-hot encode the k nearest labels and sum across k
# For each test point, count votes per class
votes = np.zeros((n_test, n_classes), dtype=np.int32)
for c in range(n_classes):
votes[:, c] = np.sum(k_nearest_labels == c, axis=1)
return np.argmax(votes, axis=1)This replaces the Python Counter loop with NumPy operations. The loop over n_classes is typically tiny (10 classes for MNIST) vs. the loop over n_test (thousands of points) that we eliminated.
For an even more vectorized approach (no loop at all):
def predict_fully_vectorized(self, X_test):
dists = self._compute_distances(X_test)
k_nearest_idx = np.argpartition(dists, self.k, axis=1)[:, :self.k]
k_nearest_labels = self.y_train[k_nearest_idx] # (n_test, k)
n_classes = int(self.y_train.max()) + 1
n_test = X_test.shape[0]
# Create (n_test, k, n_classes) one-hot, sum over k axis
one_hot = np.eye(n_classes)[k_nearest_labels] # (n_test, k, n_classes)
votes = one_hot.sum(axis=1) # (n_test, n_classes)
return np.argmax(votes, axis=1)The np.eye(n_classes)[labels] trick creates one-hot vectors for all labels simultaneously. Summing over the k dimension gives vote counts per class per test point. Memory cost: (n_test × k × n_classes), which is small.
Distance-weighted voting#
A better approach weights closer neighbors more heavily:
weights = 1.0 / (dists_of_k_nearest + 1e-8) # inverse distance
weighted_votes = (one_hot * weights[:, :, None]).sum(axis=1)
return np.argmax(weighted_votes, axis=1)This prevents ties and makes the classifier more robust to the choice of k.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Vectorized KNN uses the identity ||a-b||² = ||a||² + ||b||² - 2a·b to compute all pairwise distances via matrix multiplication. Use argpartition (O(n)) instead of full sort (O(n log n)) to find k nearest. At scale, brute-force KNN fails — use approximate nearest neighbor structures (FAISS, ScaNN) for sub-linear query time. Vectorize majority voting with one-hot encoding and summation over the k axis.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you adapt this implementation to handle weighted features — where some dimensions matter more than others?
- Explain the curse of dimensionality for KNN — why does KNN break down in high dimensions, and at what dimension count does this become a problem in practice?
- How would you implement an online KNN that can add new training points without recomputing all distances?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
Implement softmax and cross-entropy loss from scratch
Implement scaled dot-product attention from scratch
Implement gradient descent for linear regression from scratch
Explain cross-entropy loss — binary vs categorical, and why it works for classification