K-Nearest Neighbors (KNN) is one of the simplest yet remarkably powerful machine learning algorithms. Unlike parametric algorithms (like Linear or Logistic Regression) that learn mathematical weights w during an explicit training step, KNN is a Non-Parametric, Lazy Learning algorithm that memorizes the entire training dataset and defers all computation until prediction time.
x_new arrives, compute its distance to every single point in the historical training set.k closest training data points.The performance of KNN depends heavily on the geometric distance function selected for the feature space:
| Distance Metric | Mathematical Formula | Geometric Properties |
|---|---|---|
| Euclidean Distance (L2) | d(p, q) = √∑(pᵢ - qᵢ)² |
Straight-line "as the crow flies" shortest distance. Most common default. |
| Manhattan Distance (L1) | d(p, q) = ∑|pᵢ - qᵢ| |
Grid-like city block navigation. Better than L2 for higher-dimensional spaces. |
| Minkowski Distance (L_p) | d(p, q) = (∑|pᵢ - qᵢ|^p)^(1/p) |
Generalization: p=1 yields Manhattan; p=2 yields Euclidean. |
| Cosine Distance | 1 - (p · q) / (||p|| ||q||) |
Measures angular orientation rather than magnitude; ideal for text NLP. |
Selecting the number of neighbors K controls the Bias-Variance tradeoff of the classifier:
K = √N (where N is the sample size). Always choose an odd number for binary classification to prevent tied votes!1. O(N · d) Prediction Latency: Because KNN must compute distances to every sample for each query, inference is extremely slow on large databases. Use KD-Trees or Ball-Trees to accelerate search.
2. Curse of Dimensionality: In spaces with hundreds of features, all points become almost equidistant from each other, rendering distance metrics meaningless.
Broaden your foundational and advanced Machine Learning knowledge across our curriculum:
Ensure equal distance weighting across dimensions in KNN.
Compare instance-based lazy learning with parametric boundary models.
Compare supervised KNN classification with unsupervised K-Means clustering.
Euclidean vs Manhattan vs Minkowski distance interview questions.