🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
Search courses…
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

K-Nearest Neighbors — Complete Guide

ML FoundationsClassification🟢 Free Lesson

Advertisement

Supervised Learning

Instance-Based Learning — Your Neighbors Tell the Story

KNN classifies new points by looking at the K closest training examples. It is simple, intuitive, and requires no training phase.

  • Lazy Learner — No training phase, all computation at prediction time
  • Distance Metrics — Euclidean, Manhattan, and cosine similarity
  • Curse of Dimensionality — Why KNN struggles with too many features

"Tell me who your neighbors are, and I'll tell you who you are."

K-Nearest Neighbors — Complete Guide

KNN is the simplest ML algorithm — it classifies a point by looking at its K closest neighbors.


How KNN Works

KNN Classification: K=5 Neighbors VoteFeature x₁?x_qC₀C₀C₁C₀C₁Class 0 (3 votes)Class 1 (2 votes)Predicted: Class 0KNN AlgorithmStep 1: Store all training data{(x⁽ⁱ⁾, y⁽ⁱ⁾)} for i = 1..NStep 2: For query point x_q:a. Compute d(x_q, x⁽ⁱ⁾) for all ib. Sort by distancec. Select K nearest: N_K(x_q)Step 3: Majority voteŷ = argmax_c Σ 𝟙[y⁽ⁱ⁾=c]Complexity:O(Nd) per prediction — no training!

Distance Metrics

Distance Metrics ComparisonManhattan (L1)d = |80−220| + |180−85| = 240Grid-aligned paths onlyEuclidean (L2)d = √(140² + 95²) = 169.3Straight-line distanceCosine Similarityθcos(θ) = x·y / (‖x‖‖y‖)Direction only, not magnitude

Choosing K

Effect of K on Decision BoundaryK=1 (Overfitting)Complex, jagged boundaryK=5 (Good Fit)Smooth, reasonable boundaryK=50 (Underfitting)Straight line, too simple

Weighted KNN


Curse of Dimensionality

# Demonstration: distances converge in high dimensions
import numpy as np
for d in [2, 5, 10, 50, 100, 500]:
    pts = np.random.rand(100, d)
    dists = np.sqrt(((pts[:,None] - pts[None,:])**2).sum(2))
    np.fill_diagonal(dists, np.inf)
    ratio = dists.max(axis=1).mean() / dists.min(axis=1).mean()
    print(f"d={d:3d}: d_max/d_min = {ratio:.2f}")
# Output: d_max/d_min → 1 as d → ∞

Key Takeaways


What to Learn Next

-> Decision Trees If-then rules that learn — the most interpretable algorithm.

-> Clustering Grouping the ungrouped — finding hidden structure in data.

-> Dimensionality Reduction Reduce features while preserving information with PCA and t-SNE.

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement