Zero Labs
Industry News / AI

Beyond .predict(): Building a KNN From Scratch

Source · Towards AI By Pruthil Prajapati

From the publisher’s feed, collected in the ZeroLabs newsroom.

In the world of Scikit-Learn, implementing K-Nearest Neighbors (KNN) is as trivial as three lines of code. But in a production environment, “simple” is a trap. If you don’t understand the distance geometry or the computational bottleneck of O(nd), your model will fail the moment it hits a high-dimensional dataset.As an engineer, I believe we don’t truly own an algorithm until we’ve derived its logic from first principles. Today, we’re moving past the “black box” to build a KNN that handles both classification and regression from the ground upMathematical FoundationKNN is a non-parametric, lazy learner. It doesn’t “learn” a set of weights; it stores the entire training set and performs a local interpolation at inference time.1. Distance Metrics (The L_p Norm)The soul of KNN lies in how we define “closeness.” The general form is the Minkowski Distance:Euclidean (p=2): The straight-line distance, most common for continuous features.Manhattan (p=1): The “Taxicab” distance, more robust to outliers in high dimensions.2. The Decision RuleFor Classification: We use the Majority Vote (Mode) of the k neighbors.For Regression: We use the Arithmetic Mean of the k neighbors’ targets.The K-Nearest Neighbors (KNN) algorithm is a non-parametric, “lazy” learning technique that does not involve a traditional training phase; instead, it stores the entire training dataset and performs computations only during the prediction phase.The Core Process: Distance and NeighborsFor both classification and regression, the fundamental process begins the same way:Storage: During the “fit” phase, the algorithm simply stores the training feature vectors and their corresponding target labels or values.Distance Calculation: When a new data point needs a prediction, the algorithm calculates the distance between that point and every single point in the training set. Common metrics include Euclidean distance (L2 norm) for straight-line measurement or Manhattan distance (L1 norm) for axis-aligned paths.Neighbor Selection: The algorithm identifies the “k” training points that have the smallest distance to the new point.Code ImplementationBased on the implementations in my GitHub, we treat the two tasks differently in their output phase:1. KNN ClassifierFor classification, we look at the k closest neighbors and take the Mode (the most frequent class).import numpy as npimport statistics as stclass KnnClassifier: def __init__(self, k=5): self.n_neighbors = k self.X_train = None self.y_train = None def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train def predict(self, X_test): y_pred = [] idx = np.arange(0, self.X_train.shape[0]) for x in X_test: # Euclidean distance calculation distances = np.linalg.norm(self.X_train - x, axis=1) dist_with_indices = sorted(list(zip(idx, distances)), key=lambda x: x[1])[:self.n_neighbors] indices = [i[0] for i in dist_with_indices] # Majority vote most_common = st.mode(self.y_train[indices]) y_pred.append(most_common) return np.array(y_pred)2. KNN RegressorFor regression, we take the Mean (average) of the target values of the k closest neighbors.class KnnRegressor: def __init__(self, k=5): self.n_neighbors = k self.X_train = None self.y_train = None def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train def predict(self, X_test): y_pred = [] for x in X_test: distances = np.linalg.norm(self.X_train - x, axis=1) dist_with_idx = list(zip(range(len(distances)), distances)) sorted_index = sorted(dist_with_idx, key=lambda item: item[1])[:self.n_neighbors] n_indices = [item[0] for item in sorted_index] # Average of neighbor values predicted_value = np.mean(self.y_train[n_indices]) y_pred.append(predicted_value) return np.array(y_pred)The Final Mixture: Unified Industrial KNNIn a production environment, we want a unified interface. This “mixture” code uses a task parameter to toggle between modes while sharing the heavy lifting of distance calculations.class KNN: def __init__(self, k=5, task='classification'): self.k = k self.task = task self.X_train = None self.y_train = None def fit(self, X_train, y_train): self.X_train = np.array(X_train) self.y_train = np.array(y_train) def predict(self, X_test): y_pred = [] for x in X_test: # Shared logic: calculate distances distances = np.linalg.norm(self.X_train - x, axis=1) k_indices = np.argsort(distances)[:self.k] k_neighbor_values = self.y_train[k_indices] # Logic branch based on task type if self.task == 'classification': y_pred.append(st.mode(k_neighbor_values)) else: y_pred.append(np.mean(k_neighbor_values)) return np.array(y_pred)The Training vs. Testing DichotomyThe fundamental difference lies in when the algorithm does the heavy lifting: the “Learning Phase” versus the “Inference Phase.”1. K-Nearest Neighbors (The Lazy Learner)The Training Phase (Fit): In your implementation, the fit method essentially does nothing but store data. There is no optimization, no weight updates, and no mathematical "learning". The "model" is simply the training dataset itself.The Testing Phase (Predict): This is where the cost is incurred. For every single test point, the algorithm must scan the entire training set, calculate n distances (L1 or L2 norms), sort them, and aggregate the results.Cost: High Latency (O(nd)) and high memory usage.2. Logistic Regression (The Eager Learner)The Training Phase (Fit): This is the intensive part. The algorithm uses an iterative approach like Gradient Descent to find the optimal coefficients (b(beta)) that minimize a loss function (Log-Loss). Once training is finished, the training data can be discarded.The Testing Phase (Predict): Inference is incredibly fast. To predict a new point, the model simply performs a single dot product.Cost: Low Latency (O(d)) and minimal memory footprint.To truly master KNN for industrial applications, we must address its biggest flaw: the Brute Force Bottleneck. While my scratch implementation calculates distances to every single point, production libraries like Scikit-Learn use tree-based spatial data structures to prune the search space, reducing complexity from O(n) to O(log n).🌳KD-Trees (K-Dimensional Trees)The KD-Tree is a binary search tree where every node is a k-dimensional point. The process involves recursively partitioning the data space into axis-aligned boxes.The Process: At each level of the tree, we choose a specific dimension (e.g., X-axis, then Y-axis) and split the data points based on the median value of that dimension. This creates a hierarchy of regions.The Usage: When searching for the nearest neighbor of a test point, the algorithm first traverses down to the “leaf” node containing the point. It then “backtracks” only to neighboring boxes that could potentially contain a closer point, completely ignoring large sections of the dataset that are geometrically impossible to be the “nearest”.Limitation: KD-Trees perform exceptionally well in low dimensions (d 🏀 Ball TreesTo overcome the limitations of axis-aligned splits in high-dimensional spaces, we use Ball Trees.The Process: Instead of splitting space with lines or planes, Ball Trees partition data into a series of nesting n-dimensional hyperspheres (balls). Each node in the tree defines a centroid and a radius that encloses a subset of the data points.The Usage: During a search, if the distance from the test point to the boundary of a “ball” is greater than the distance to the current best neighbor found, the entire ball (and all its children) is pruned. This spherical geometry is far more efficient than KD-Tree boxes when dealing with high-dimensional data or non-Euclidean metrics.⚙️ Industrial Choice: KD-Tree vs. Ball TreeIn professional ML engineering, the choice depends on your data’s “intrinsic dimensionality.”KD-Trees are your go-to for low-dimensional, structured data where axis-parallel splits are natural.Ball Trees are superior for high-dimensional datasets or when using specialized distance metrics where a “box” doesn’t mathematically make sense.By implementing these, we move from a O(nd) “Lazy Learner” to a highly optimized search engine capable of handling millions of requests with sub-second latency.Scikit-Learn: The Industry StandardFor most general-purpose applications, Scikit-Learn is the preferred choice. It transitions from the “Lazy Learning” brute-force approach to an “Eager” spatial partitioning approach:KD-Trees: This library selection is ideal for low-dimensional data (typically d Ball Trees: Used for higher-dimensional data or complex distance metrics where axis-aligned splits fail. It uses nesting hyperspheres to organize data points.Automatic Selection: Scikit-Learn’s algorithm='auto' parameter will attempt to determine the most efficient search algorithm based on the values passed to fit().Let’s Connect!LinkedIn: pruthil-prajapatiEmail: GmailGitHub: Pruthil-2910Keep exploring the math behind the models!#BuildInPublic #ArtificialIntelligence #DataEngineering #SoftwareEngineering #Mathematics #ProgrammingTips #100DaysOfCode #UnderTheHood #MathForML #FromScratch #CodeNewbie #Vectorization #Optimization #AlgorithmDesign #NumPy #PythonBeyond .predict(): Building a KNN From Scratch was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.