How does KNN classification work?
k-Nearest Neighbors (k-NN) classification is a non-parametric, instance-based algorithm that stores labeled training data without learning parametric weights. To classify a query point, it computes distances to training samples, selects the k closest neighbors, and predicts the majority (or inverse-distance-weighted) class label.
Study Card: K-Nearest Neighbors (KNN) Classification
Direct Answer
K-Nearest Neighbors (KNN) classification is a non-parametric, lazy (instance-based) supervised algorithm. It performs virtually no parametric training—simply indexing or storing the training dataset—and defers computation until prediction time. Given a query point , KNN measures distances to all training samples (using metrics such as Euclidean or Manhattan distance on appropriately scaled features), selects the closest neighbors , and assigns the class receiving the largest vote (either uniform majority vote or weighted by inverse distance ). Choosing an odd in binary classification helps break ties cleanly.
Key Terms
- Instance-Based (Lazy) Learning: Stores training examples directly rather than fitting explicit parametric decision weights; training is (or to build a spatial tree), while brute-force inference scales as per query point.
- Distance Metric: Quantifies similarity in feature space, commonly Euclidean (), Manhattan (), Minkowski, or cosine distance.
- Neighborhood Size (): Hyperparameter controlling how many nearest training neighbors vote on the prediction.
- Majority vs. Distance-Weighted Voting: Uniform voting weights each of the neighbors equally, whereas distance-weighted voting gives closer neighbors larger votes .
Example
Imagine classifying a new fruit as Apple or Orange from standardized weight and color features using :
- Compute Distances: Measure Euclidean distance from the query fruit to every training fruit.
- Select Neighbors: Suppose the three closest neighbors are
[Apple, Orange, Orange]at distances0.1,0.2, and0.25. - Vote:
- Under uniform majority voting,
Orangewins2votes to1. - Under inverse-distance weighting (),
Applereceives weight , while the twoOrangeneighbors receive , soApplewins narrowly because it sits much closer to the query point.
- Under uniform majority voting,
Code Implementation
import numpy as np
from collections import Counter
def euclidean_distance(x1, x2):
return np.sqrt(np.sum((x1 - x2) ** 2))
class KNN:
def __init__(self, k=3):
self.k = k
def fit(self, X, y):
# Convert to NumPy arrays so positional indexing works for lists or pandas Series
self.X_train = np.asarray(X, dtype=float)
self.y_train = np.asarray(y)
def predict(self, X):
X_arr = np.asarray(X, dtype=float)
return np.array([self._predict(x) for x in X_arr])
def _predict(self, x):
distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
k_indices = np.argsort(distances)[:self.k]
k_nearest_labels = self.y_train[k_indices]
most_common = Counter(k_nearest_labels).most_common(1)
return most_common[0][0]
# Sample Data (0: Class A, 1: Class B)
X = np.array([[1, 2], [2, 3], [3, 1], [6, 5], [7, 7], [8, 6]])
y = np.array([0, 0, 0, 1, 1, 1])
knn = KNN(k=3)
knn.fit(X, y)
X_new = np.array([[3, 2], [7, 6]])
predictions = knn.predict(X_new)
print("Predictions:", predictions)
Related Concepts
- Feature Scaling: Mandatory before applying Euclidean or Manhattan distance so large-magnitude features (e.g., income in dollars vs. age in years) do not dominate distance rankings.
- Curse of Dimensionality: In high dimensions, distances between nearest and farthest points concentrate, degrading neighbor quality unless dimensionality reduction or feature selection is applied.
- Computational Acceleration: Brute-force search costs per query; KD-Trees, Ball Trees, or Approximate Nearest Neighbor (ANN) indexes like HNSW or FAISS accelerate lookup on large datasets.
- Bias-Variance Tradeoff ( Choice): Small increases variance (sensitive to noise); large increases bias (oversmooths local boundaries).
- Tie Breaking & Imbalanced Classes: Odd avoids binary ties, and distance weighting or class-prior adjustment prevents majority classes from dominating when is moderate or large.