Curriculum02. Supervised LearningLesson 3 of 7

K-Nearest Neighbors

Non-parametric instance memory and geometric majority voting.

16 min readBeginnerModule 02
01 // CORE INTUITION

Core Intuition: Birds of a Feather

Suppose you move to an unfamiliar city and want to estimate the rent of an apartment without reading market formulas. You inspect the five closest comparable apartments on the same block and take their median rent.

K-Nearest Neighbors (KNN) applies that exact principle in feature space. Rather than compressing data into a global equation, it stores every training point and predicts new queries by polling their kk closest spatial neighbors.

Takeaway:KNN predicts a query point by polling the labels or values of its kk nearest training examples.
02 // THE PROBLEM IT SOLVES

The Problem It Solves: Arbitrary Non-Linear Pockets

Parametric models like logistic regression assume a single global boundary shape across the entire domain. When classes form interlocking spirals, scattered islands, or multimodal clusters, global linear equations fail.

KNN adapts its boundary locally around every neighborhood, drawing arbitrarily curved decision frontiers with zero training optimization.

Takeaway:Use KNN when local spatial similarity predicts outcomes better than a single global parametric equation.
03 // STEP-BY-STEP MECHANISM

Step-by-Step Mechanism: Distance, Sort, Ballot

KNN is a lazy learner: .fit() merely indexes the training matrix in memory. All computation happens at prediction time:

1. Measure Distance: Compute distance d(xq,x(i))d(\mathbf{x}_q, \mathbf{x}^{(i)}) from query xq\mathbf{x}_q to every stored training point.

2. Select Top-K: Sort distances ascending and collect the kk closest indices Nk(xq)\mathcal{N}_k(\mathbf{x}_q).

3. Aggregate Vote: Return majority class label for classification (or mean target value for regression). Using odd kk avoids binary tie votes.

Takeaway:Training stores the dataset; inference measures distances, extracts the kk closest points, and tallies their votes.
04 // INTERACTIVE SANDBOX

Interactive Sandbox: Neighborhood Radius & K Voting

Adjust neighborhood size $k$ (1, 3, 5, 7), switch between Euclidean ($L_2$) and Manhattan ($L_1$) metrics, and select different query locations.

Watch the dashed neighborhood boundary expand to enclose the kk closest points. Notice how k=1k = 1 flips prediction near a single noisy outlier, while larger kk smooths out local noise.

Instance Neighborhood & Ballot Visualizer
VOTES: C0=1 / C1=2PREDICTED: CLASS 1 (67%)
K:
QUERY x₁175
QUERY x₂115
Feature x₁Feature x₂
Class 0
Class 1
k=3 radius (40.0)
Takeaway:Small kk creates jagged overfit islands around outliers; large kk smooths boundaries toward global class priors.
05 // MATHEMATICAL FORMULATION

Mathematical Formulation: Minkowski Distance & Majority Rule

With p=2p = 2, d2d_2 measures straight-line Euclidean distance, producing circular neighborhoods in 2D. With p=1p = 1, d1d_1 measures taxicab Manhattan distance along coordinate axes, forming diamond-shaped neighborhoods that resist single-coordinate outliers slightly better.

PRIMARY OBJECTIVE FORMULATION
Variable & Symbol Definitions
dp(x,z)d_p(\mathbf{x}, \mathbf{z})Minkowski distance of order pp (p=1p=1 gives Manhattan, p=2p=2 gives Euclidean)
Nk(xq)\mathcal{N}_k(\mathbf{x}_q)Index set of the kk training observations closest to query xq\mathbf{x}_q
I(y(i)=c)\mathbb{I}(y^{(i)} = c)Indicator equal to 11 if neighbor ii belongs to class cc, else 00
y^(xq)\hat{y}(\mathbf{x}_q)Predicted class maximizing vote count inside the kk-neighborhood
Takeaway:KNN predicts the modal class inside the kk-nearest neighborhood defined by Minkowski metric dpd_p.
06 // KEY ASSUMPTIONS

Key Assumptions: Local Smoothness & Equal Feature Scale

KNN assumes two geometric properties hold across the feature space:

1. Local Label Continuity: Nearby points in coordinate space share the same target label.

2. Commensurate Coordinate Units: Every feature axis contributes meaningfully to distance. Unscaled wide-range columns (like income in dollars alongside age in years) overwhelm smaller columns and corrupt neighbor selection.

Takeaway:Standardizing all numeric features via StandardScaler is mandatory before computing KNN distances.
07 // COMMON PITFALLS

Common Pitfalls: Curse of Dimensionality & Outliers

In high dimensions (d≥50d \ge 50), random points grow nearly equidistant from one another, erasing the contrast between nearest and farthest neighbors (Curse of Dimensionality). Irrelevant noisy features dilute true signal distances.

At k=1k = 1, KNN achieves 0 percent training error by memorizing every point, yet a single mislabeled training point creates a wrong classification island in test space.

Algorithmic Checkpoint

Suppose you reduce KNN from k = 7 down to k = 1 on a noisy binary classification dataset. How do Bias and Variance change?

Takeaway:Avoid k=1k = 1 on noisy data, scale all features, and reduce irrelevant dimensions before applying KNN.
08 // COMPLEXITY

Computational Complexity: Zero Training, Heavy Inference

Brute-force KNN has O(1)O(1) training time (storing m⋅dm \cdot d floats in memory) and O(m⋅d)O(m \cdot d) inference cost per single query point, which becomes slow when mm reaches hundreds of thousands.

Spatial index trees (KDTree, BallTree) speed low-dimensional queries (d<20d < 20) toward O(dlog⁡m)O(d \log m), while large-scale embedding retrieval uses Approximate Nearest Neighbor (ANN) indices like HNSW.

Takeaway:KNN shifts computational burden from training (O(1)O(1)) to inference (O(m⋅d)O(m \cdot d) brute force) and memory (O(md)O(md)).
09 // REAL-WORLD USE

Real-World Use: Recommendation & Retrieval Augmentation

Classical brute-force KNN struggles on massive raw tabular tables, yet nearest-neighbor search powers modern semantic search, image similarity, and Retrieval-Augmented Generation (RAG).

Once deep encoders compress images or text passages into dense unit-normalized vectors, cosine similarity nearest-neighbor lookup retrieves matching documents or products in milliseconds.

Takeaway:Nearest-neighbor matching over learned embeddings drives modern visual similarity and RAG retrieval systems.
10 // PRODUCTION CODE

Production Code: Vectorized KNN & Scaled Pipeline

Implement vectorized Euclidean KNN prediction in NumPy and a leak-free scaled pipeline in scikit-learn.

Production Implementation
import numpy as np

def knn_predict(X_train: np.ndarray, y_train: np.ndarray, x_query: np.ndarray, k: int = 3) -> int:
    # Compute L2 distances from query to all training points
    dists = np.linalg.norm(X_train - x_query, axis=1)
    nearest_idx = np.argsort(dists)[:k]
    votes = y_train[nearest_idx]
    values, counts = np.unique(votes, return_counts=True)
    return int(values[np.argmax(counts)])

X = np.array([[1.0, 1.0], [1.5, 2.0], [2.0, 1.2], [5.0, 5.0], [5.5, 4.8], [6.0, 5.5]])
y = np.array([0, 0, 0, 1, 1, 1])
print("Predicted class for [2.2, 1.8]:", knn_predict(X, y, np.array([2.2, 1.8]), k=3))
Implementation Walkthrough:

In NumPy, np.linalg.norm(X_train - x_query, axis=1) broadcasts subtraction across rows and np.argsort(dists)[:k] picks the kk smallest indices without sorting the remaining votes. In scikit-learn, make_pipeline(StandardScaler(), KNeighborsClassifier(...)) ensures distance calculations treat both features symmetrically.

Takeaway:Wrap KNeighborsClassifier with StandardScaler in a pipeline and tune n_neighbors via cross-validation.