K-Nearest Neighbors (KNN)
Predict from local neighborhoods and understand distance metrics and scaling needs.
In plain words
To guess something about a new item, KNN finds the most similar items it has seen and copies what most of them were.
Think of it like…
Asking your five nearest neighbours what restaurant to try: if you define "near" using distance in kilometres and also dollars of annual income on the same ruler, income dominates and you end up asking the wrong people.
Where you’ve seen it
A loan application has age 30 and income $50,000; a candidate neighbour has age 60 and income $51,000. In raw units the Euclidean distance is √(30² + 1,000²) = 1,000.45: income dominates entirely and age barely matters. After standardising (age mean 40, SD 10; income mean $50,000, SD $10,000) the difference is 3.0 in age and 0.1 in income, so the distance is √(3.0² + 0.1²) = 3.0017: now age drives similarity, as it should. For a new customer with k = 5 neighbours at distances 0.5, 0.8, 1.0, 1.2 and 2.0 with labels 1, 1, 0, 1, 0, majority voting gives 3 / 5 = 0.60 for class 1; inverse-distance weighting (weights 2.0, 1.25, 1.0, 0.833, 0.5) gives class 1 a weight of 4.083 out of 5.583, or 0.731. Cross-validation over k = 1 to 51 picks k = 15, and the team notes that with 1 million rows and 100 features a brute-force query costs about 10⁸ distance operations, so for production they use an approximate index (HNSW).
Words you’ll hear
- k
- The number of neighbours that vote; the main complexity control.
- Distance metric
- The definition of closeness: Euclidean, Manhattan, cosine, Minkowski.
- Lazy learner
- A model that stores data and computes at prediction time rather than fitting parameters.
- Curse of dimensionality
- In high dimensions, distances concentrate and all points look about equally far.
Visual diagram
Theory & deep dive
Distance, scaling and choosing k
KNN's prediction depends entirely on the distance metric. Euclidean (L2) suits dense numeric features after scaling; Manhattan (L1) is more robust to outliers and high dimensions; cosine suits text and embeddings where direction matters more than magnitude; Hamming works for categorical or binary vectors, and Gower-style distances combine mixed types. Scaling is mandatory: distance adds squared differences across features, so a feature measured in dollars swamps one measured in years. In the loan example, raw distance 1,000.45 versus scaled distance 3.0017 shows the difference between ignoring age and using it. Use a pipeline with StandardScaler or MinMaxScaler fitted on the training data only, and remove or down-weight irrelevant features, since they add noise to every distance.
k controls the bias-variance tradeoff. k = 1 gives a jagged boundary that memorises noise (training accuracy 100% because each point is its own nearest neighbour, so evaluate with cross-validation or leave-one-out, never on the training set); very large k smooths toward the majority class (k = n predicts the overall mode or mean). Choose k by cross-validation, use odd k for binary problems to avoid ties and consider distance weighting (weights="distance") so close neighbours count more. A rough starting heuristic is √n, but validate. For regression, the prediction is the mean (or distance-weighted mean) of neighbour targets, which cannot extrapolate beyond the observed range.
Neighbour distances 0.5, 0.8, 1.0, 1.2, 2.0 with labels 1, 1, 0, 1, 0. Unweighted: 3 of 5 vote class 1 (0.60). Weights 1/d = 2.0, 1.25, 1.0, 0.833, 0.5: class 1 total = 2.0 + 1.25 + 0.833 = 4.083; class 0 = 1.5; probability of class 1 = 4.083 / 5.583 = 0.731.
Curse of dimensionality, scalability and use cases
In high dimensions the notion of "nearest" degrades. To capture a fraction 0.1 of uniformly distributed data inside a hypercube neighbourhood, the edge length must be 0.1^(1/d): 0.32 in 2 dimensions, 0.79 in 10 and 0.98 in 100, i.e. the "local" neighbourhood covers nearly the entire range of every feature. Distances between points concentrate (the nearest and farthest neighbours are almost equally far), so KNN works poorly with hundreds of raw features. Remedies: feature selection, dimensionality reduction (PCA, or learned embeddings, after which cosine similarity works well) and metric learning.
KNN's cost is at prediction time: a brute-force query is O(n × d), so 1 million rows and 100 features means about 10⁸ operations per query, and memory holds the whole training set. Use KD-trees or ball trees for low dimensions (up to roughly 20), and approximate nearest neighbour indexes (HNSW, IVF, product quantisation) for large, high-dimensional data, trading a little recall for orders of magnitude speed; this is how vector databases and retrieval systems work. KNN is a good fit for small to medium data with meaningful distances, anomaly scoring (distance to the k-th neighbour), imputation (KNNImputer), recommendation by similarity and as a baseline for sanity-checking more complex models. It is a poor fit for large, high-dimensional, sparse or noisy-feature problems, and for settings requiring a compact model or fast low-latency inference without an index.
Edge length needed to capture 10% of uniform data: d = 2 → 0.1^0.5 = 0.316; d = 10 → 0.1^0.1 = 0.794; d = 100 → 0.1^0.01 = 0.977. In 100 dimensions a "local" cube spans 98% of every axis, so it isn't local.
How it works, step by step
Step 1 of 41. Scale and select features
Standardise numeric features within a pipeline and drop irrelevant ones.
- Fit scaler
- on train only
When to use it & trade-offs
What it is
K-nearest neighbours (KNN) predicts for a new point by looking at the k closest training points under a distance metric and taking a majority vote (classification) or an average (regression), optionally weighting closer neighbours more. There is no training in the usual sense: the model *is* the stored data (a lazy learner), so all the work happens at prediction time. Its behaviour is controlled by k (small k gives low bias and high variance, large k the reverse), the distance metric (Euclidean, Manhattan, cosine) and, critically, feature scaling, because distance is dominated by features with large numeric ranges.
Why it matters: KNN is simple, non-parametric and makes no assumption about the shape of the decision boundary, so it's a useful baseline and a clear illustration of the bias-variance tradeoff, locality and the curse of dimensionality. The same nearest-neighbour idea underlies similarity search, recommendation and retrieval systems (vector databases use approximate nearest neighbours), so understanding its cost and failure modes carries over directly.
When to reach for it
- Quick, strong baselines on small data
- Similarity search and recommendation primitives
- Imputing missing values and scoring anomalies by neighbour distance
When to avoid or be careful
- Unscaled features
- Hundreds of noisy raw dimensions
- Evaluating k on the training set
KNN in context
Strengths: No training; flexible boundaries; simple.
Watch out: Slow prediction; needs scaling; weak in high dimensions.
Strengths: Compact; calibrated probabilities.
Watch out: Linear unless features are engineered.
Strengths: Robust to scaling; handles interactions.
Watch out: Less local-similarity interpretation.
Interview signals & numbers to know
When this topic comes up
- “Find similar items”
- “Predictions are slow at scale”
- Curse of dimensionality
- Approximate nearest neighbours
- Choosing k
Benchmarks & rules of thumb
- 0.316 / 0.794 / 0.977
- edge length to capture 10% of data in 2, 10 and 100 dimensions
- O(n × d)
- brute-force cost per query
- k = 1
- 100% training accuracy but high variance
Common mistakes & follow-ups
Common interview mistakes
- Forgetting to scale and letting income dominate age.
- Using k = 1 because training accuracy is perfect.
- Running brute-force KNN on millions of rows in production.
Likely interviewer follow-ups
- Why must features be scaled for KNN?
- How does k affect bias and variance?
- How would you speed up KNN on a large dataset?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply K-Nearest Neighbors (KNN) with data science interview Q&A and hands-on practice.