K-Nearest Neighbors
Open Spotify and look at the "Fans Also Like" section on any artist. Open Pinterest and tap "More Like This" on a pin. Open the App Store and scroll to "Apps Similar to This One." Every single one of those sections is the same algorithm running underneath: find the 10 items closest to this one in some big mathematical space, show those. It is also the algorithm running inside every modern AI search engine ("find me documents similar to this question") and every RAG system that powers a chatbot's memory. By the end of this lesson, you'll understand the whole idea. There is no training step, no math to solve, just "look at your neighbors and copy their answer", and you'll know exactly when this dirt-simple recipe wins and when it falls apart.
After this lesson, you will be able to:
- Understand KNN — it just saves all the training data and makes predictions by finding the most similar examples (no actual 'training' happens!)
- See how changing K (how many neighbors you ask) makes the model smoother or more jagged
- Know the different ways to measure 'closeness' (Euclidean, Manhattan, cosine) and when each makes sense
- Recognize KNN's trade-offs: dead simple to understand, but slow on big datasets and struggles with many features
- Explain the curse of dimensionality and why KNN requires dimensionality reduction when features exceed ~20-50
Before you start
Don't worry if this one feels too simple to be real — KNN is genuinely that straightforward. No training, no fancy math, just "find the closest examples and copy their answer." It is a great starting point for any problem!
#The Algorithm with No Training
#How KNN Works
Try it! Open the Python REPL and type these lines yourself. Run KNN on the Iris dataset:from sklearn.neighbors import KNeighborsClassifier; from sklearn.datasets import load_iris; X, y = load_iris(return_X_y=True); knn = KNeighborsClassifier(n_neighbors=3).fit(X, y); print(f"Accuracy: {knn.score(X, y):.0%}")— you just classified flowers by asking their neighbors!
#Worked Example: Classifying a New Fruit
You have 6 labeled fruits with two features — weight (grams) and sweetness (1–10):
| Fruit | Weight | Sweetness | Label |
|---|---|---|---|
| 1 | 150 | 7 | apple |
| 2 | 170 | 8 | apple |
| 3 | 130 | 6 | apple |
| 4 | 200 | 4 | orange |
| 5 | 220 | 3 | orange |
| 6 | 180 | 5 | orange |
| Fruit | Distance | Label |
|---|---|---|
| 1 | √((160−150)² + (6−7)²) = √101 ≈ 10.05 | apple |
| 2 | √(10² + 2²) = √104 ≈ 10.20 | apple |
| 3 | √(30² + 0²) = 30.00 | apple |
| 4 | √(40² + 2²) = √1604 ≈ 40.05 | orange |
| 5 | √(60² + 3²) ≈ 60.07 | orange |
| 6 | √(20² + 1²) ≈ 20.02 | orange |
But also notice a trap waiting: weight ranges 130–220 (≈90 spread) and sweetness ranges 3–8 (≈5 spread). Weight is roughly 18× larger in raw units, so it dominates every distance calculation. Sweetness is almost invisible. This is why feature scaling is mandatory — without it, KNN is really just "1-nearest-neighbor on the biggest feature."
For regression:
Now see the scaling trap on a real 5-neighbour classifier. Ages run from 20 to 80 and incomes from $20k to $200k, so the two features start on very different scales.
Do: Leave Scaler on No scaling and look at the coloured regions. Then click StandardScaler, then MinMaxScaler. Watch the amber rings and the accuracy readout each time.Notice: With no scaling the regions follow income almost alone, because income has the larger numbers. After scaling, the regions bend with both age and income. Amber-ringed points are ones whose predicted class changed from the unscaled run.Why: KNN compares raw distances, so a feature with big numbers wins every vote about who is near. Scaling puts the features on a comparable footing before distances are measured. The data is a small made-up set of 30 points, and the accuracy shown is measured on those same points, so read it as a demonstration, not a test score.
#Visualizing KNN: Voronoi Diagrams
Interactive Lab
Pick KNN from the algorithm dropdown, change K with the slider, and watch the boundary go from jagged (K=1, overfits) to smooth (K=29, underfits). The sweet spot is usually somewhere between.
You train KNN on a 2D dataset three times: K=1, K=5, K=25. Which row matches each model's TRAINING accuracy?
#Time Complexity: The Lazy Learner's Cost
| Phase | Time Complexity | What It Means |
|---|---|---|
| Training | O(1) | Just store the data — no computation at all |
| Prediction (naive) | O(n * d) per query | Compare against every training point in d dimensions |
| Prediction (KD-Tree) | O(d * log n) average | Fast for low dimensions (d < 20) |
| Prediction (Ball Tree) | O(d * log n) average | Better for moderate dimensions |
| Prediction (ANN/FAISS) | O(d * log n) approximate | Sub-millisecond on billions of vectors |
For small datasets (n < 10,000), the naive approach is fine. For production systems with millions of points, you need acceleration structures like KD-Trees, Ball Trees, or approximate nearest neighbor libraries.
#Choosing K: The Bias-Variance Knob
You have a KNN classifier with K=1 that gets 100% training accuracy. Is this model good?
K is the single most important hyperparameter:
-
K = 1: Every training point creates its own tiny decision region. Training accuracy is always 100% (each point is its own nearest neighbor). The boundary is extremely jagged and overfits to noise. High variance, low bias.
-
K = n (all data): Every prediction is the majority class of the entire training set. The model ignores the input entirely. This is maximum underfitting. Low variance, high bias.
-
K = sqrt(n): A common starting point. Tune via cross-validation.
Bias is the qualitative half of that statement: as K grows the neighbours reach farther from the query, so their average drifts away from the true value near the query. The variance half is exact, and the derivation below shows it. It assumes each neighbour value is the same true value plus independent noise with variance sigma squared.
#Finding the Best K with Cross-Validation
Tests: Verify that cross-validation scores are computed for each K. Verify that the best K is selected based on the highest score.
Now visualize K's effect directly: train three KNN classifiers (K=1, 5, 25) on the same 2D blobs and overlay their decision regions side by side.
#How Good Can 1-NN Get? The Cover-Hart Bound
Take two classes. At a point x, let eta(x) be the true probability that the label is 1. The best any classifier can do at x is to predict the likelier class, so its error there is r(x), the smaller of eta and 1 minus eta. Averaged over x this is the Bayes error R*, the floor nobody can beat. With unlimited training data, the plain 1-nearest-neighbour rule has error at most twice that floor, which is why a rule with no training step is not hopeless.
#The Curse of Dimensionality: by Simulation
Words don't quite convince. In high dimensions, the ratio (max pairwise distance / min pairwise distance) goes to 1 — meaning every point becomes about the same distance from every other point. Run the simulation in your browser.
#Distance Metrics
The choice of distance metric profoundly affects KNN's behavior:
#Euclidean Distance (L2)
#Manhattan Distance (L1)
Drag the point in the picture below and compare the three ways of measuring its length. The set of points at distance 1 is a diamond for Manhattan, a circle for Euclidean and a square for the largest-coordinate rule, so each choice defines "near" with a different shape.
#Cosine Similarity (for text/embeddings)
Cosine and Euclidean distance are closely related once vectors are scaled to length 1, which is how most embeddings are stored.
When to use which
- Euclidean: Default choice for continuous features with similar scales
- Manhattan: Better when features are on different scales or when outlier robustness matters
- Cosine: Text data, embeddings, any high-dimensional sparse data where direction matters more than magnitude
#Choosing the Right Distance Metric
The distance metric you choose can make or break your KNN model. Here is a practical decision framework:
-
Structured tabular data (age, income, height): Start with Euclidean after StandardScaler. If outliers are present, switch to Manhattan — it does not square the differences, so one extreme value in one dimension cannot dominate.
-
Text data (TF-IDF vectors, word embeddings): Always use Cosine. A 10-page document and a 1-page document about the same topic have very different magnitudes but similar directions. Cosine ignores magnitude and compares only direction.
-
Mixed feature types (some continuous, some binary): Consider Manhattan. It handles binary features more naturally because the distance is simply the number of mismatched binary features plus the absolute differences in continuous features.
-
Very high dimensions (d > 100): The choice of metric matters less because all distances converge, but Cosine tends to degrade more slowly than Euclidean in high dimensions.
You have 50,000 documents represented as 768-dim sentence-transformer embeddings. You want KNN over them for semantic search. Which distance metric and acceleration choice?
#Weighted KNN
Standard KNN gives equal weight to all K neighbors. Weighted KNN gives closer neighbors more influence:
#The Curse of Dimensionality
Three short derivations make those claims exact: how big the neighbourhood must be, where the volume of a cube lives, and why distances bunch together.
Move the dimension d, the shell thickness and the neighbourhood share, and watch the shell share head to 1, the side needed for a 10 percent neighbourhood head to the whole range, and the pairwise distances bunch together as d grows.
#Try It Yourself
Tests: Verify K=1 returns the class of the single nearest neighbor. Verify that increasing K can change predictions for ambiguous points. Implement distance weighting and compare results.
#When to Use KNN vs. Alternatives
| Situation | Reach for | Why |
|---|---|---|
| You need similarity search over embeddings (RAG, recommendations) | KNN with FAISS / ScaNN / HNSW | This is literally what KNN was born for |
| Small clean dataset (< 10K rows), low dimensions (< 20) | KNN | Simplest baseline you can spin up in 3 lines |
| Hundreds of features, tens of thousands of rows | Random Forest / Gradient Boosting | KNN drowns in the curse of dimensionality |
| You need probability outputs and interpretable coefficients | Logistic regression | KNN gives votes, not calibrated probabilities |
| Large dataset with low latency requirement at inference | Linear / tree models (training-time work, fast at inference) | KNN is O(n·d) per query — opposite of what you want |
| Missing values to impute in tabular data | KNNImputer (sklearn) | KNN-based imputation preserves local structure |
#Key Takeaways
- KNN has no training step. It stores the entire dataset and defers all computation to prediction time, making it a "lazy learner" with O(1) training but O(n*d) prediction cost
- K controls the bias-variance tradeoff. K=1 overfits (every point is its own neighborhood), large K underfits (everything is averaged); use cross-validation to find the sweet spot, often starting at sqrt(n)
- Feature scaling is critical. KNN is purely distance-based, so unscaled features with large ranges dominate the distance calculation and render small-range features invisible
- The curse of dimensionality breaks KNN in high dimensions. As dimensions increase, all points become approximately equidistant, making the concept of "nearest" meaningless; use PCA or feature selection first
- Vector search is KNN's most important modern application. Every RAG system, recommendation engine, and semantic search engine is built on approximate nearest neighbor search using libraries like FAISS and ScaNN
#Quick Check
What happens during the 'training' phase of KNN?