Home Knowledge Base K-Nearest Neighbors (KNN)

K-Nearest Neighbors (KNN) is a "lazy learning" algorithm that makes predictions by finding the K most similar training examples to a new data point and using their labels to vote on the prediction — requiring no training phase at all (the entire dataset IS the model), making it the simplest conceptual algorithm in machine learning but also one of the slowest at inference time because every prediction requires computing distances to every stored example.

What Is KNN?

How KNN Works

StepProcessExample
1. StoreSave all training data10,000 labeled examples in memory
2. New point arrivesCalculate distance to ALL stored pointsCompare against every example
3. Find K nearestSort by distance, take top KK=5: find 5 closest neighbors
4. Vote (Classification)Majority label wins3 "Cat" + 2 "Dog" → predict "Cat"
4. Average (Regression)Mean of K neighbor values($400K + $420K + $450K) / 3 = $423K

Distance Metrics

MetricFormulaBest ForIntuition
Euclidean$sqrt{sum(x_i - y_i)^2}$General numeric dataStraight-line distance
Manhattan$sumx_i - y_i$Grid-like data, sparse features"Taxi cab" distance
Cosine$1 - frac{A cdot B}{AB}$Text / embeddingsAngle between vectors
Minkowski$(sumx_i - y_i^p)^{1/p}$Generalizes Euclidean/ManhattanParameterized by p

Choosing K

K ValueBehaviorRisk
K = 1Nearest single point decidesHigh variance — sensitive to noise and outliers
K = 3-7Good balance for most datasetsSweet spot for many practical problems
K = largeOver-smoothed decision boundariesHigh bias — ignores local patterns
K = NPredicts the majority class alwaysUseless (just predicts the most common label)

Scaling is Critical: KNN uses distance — if Age (0-100) and Salary (0-100,000) are both features, Salary dominates all distances. Always standardize features before using KNN.

Limitations and Solutions

LimitationImpactSolution
Slow inference O(N×D)Every prediction scans all dataApproximate Nearest Neighbor (HNSW, Annoy, FAISS)
Curse of dimensionalityDistances become meaningless in 100+ dimsDimensionality reduction (PCA, UMAP) first
Memory-intensiveMust store entire training setKD-Trees or Ball Trees for efficient indexing
Feature scaling requiredUnscaled features bias distancesStandardScaler before KNN

K-Nearest Neighbors is the conceptually simplest algorithm in machine learning — requiring no training, no parameter optimization, and no mathematical complexity, making it the perfect teaching algorithm and a surprisingly effective baseline, with its inference speed limitation solved by approximate nearest neighbor libraries like FAISS and HNSW that power production search and recommendation systems.

knnnearest neighborinstance

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.