Skip to content
E
Educatum

How does KNN classification work?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 xx, KNN measures distances to all training samples (using metrics such as Euclidean or Manhattan distance on appropriately scaled features), selects the kk closest neighbors Nk(x)N_k(x), and assigns the class receiving the largest vote (either uniform majority vote or weighted by inverse distance 1/d(x,xi)1 / d(x, x_i)). Choosing an odd kk 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 O(1)O(1) (or O(Ndlog⁡N)O(Nd \log N) to build a spatial tree), while brute-force inference scales as O(Nd)O(Nd) per query point.
  • Distance Metric: Quantifies similarity in feature space, commonly Euclidean (∥x−x′∥2\|x - x'\|_2), Manhattan (∥x−x′∥1\|x - x'\|_1), Minkowski, or cosine distance.
  • Neighborhood Size (kk): Hyperparameter controlling how many nearest training neighbors vote on the prediction.
  • Majority vs. Distance-Weighted Voting: Uniform voting weights each of the kk neighbors equally, whereas distance-weighted voting gives closer neighbors larger votes wi=1/(d(x,xi)+ϵ)w_i = 1 / (d(x, x_i) + \epsilon).

Example

Imagine classifying a new fruit as Apple or Orange from standardized weight and color features using k=3k = 3:

  1. Compute Distances: Measure Euclidean distance from the query fruit to every training fruit.
  2. Select k=3k = 3 Neighbors: Suppose the three closest neighbors are [Apple, Orange, Orange] at distances 0.1, 0.2, and 0.25.
  3. Vote:
    • Under uniform majority voting, Orange wins 2 votes to 1.
    • Under inverse-distance weighting (wi=1/diw_i = 1 / d_i), Apple receives weight 1/0.1=101 / 0.1 = 10, while the two Orange neighbors receive 1/0.2+1/0.25=5+4=91 / 0.2 + 1 / 0.25 = 5 + 4 = 9, so Apple wins narrowly because it sits much closer to the query point.

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)
  • 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 O(Nd)O(Nd) per query; KD-Trees, Ball Trees, or Approximate Nearest Neighbor (ANN) indexes like HNSW or FAISS accelerate lookup on large datasets.
  • Bias-Variance Tradeoff (kk Choice): Small kk increases variance (sensitive to noise); large kk increases bias (oversmooths local boundaries).
  • Tie Breaking & Imbalanced Classes: Odd kk avoids binary ties, and distance weighting or class-prior adjustment prevents majority classes from dominating when kk is moderate or large.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.