Classical machine learning
K-Nearest Neighbors: Local Learning
Understand KNN classification and regression through distance, neighborhood size, weighting, support, and retrieval operations.
By the end you can
- Explain KNN as query-time local aggregation over stored examples
- Compare neighborhood size, distance metric, and weighting choices
- Identify support, imbalance, tie, and probability-interpretation risks
- Design a neighbor system with inspection, abstention, and serving constraints
Nearest neighbors postpones learning until a query arrives
K-nearest neighbors stores the training examples and predicts from the labels or targets of nearby cases. Training can be almost trivial. Inference performs the expensive search and aggregation.
The model therefore lives in the feature representation and distance metric as much as in the value of k.
The rule also comes with a bound, and the bound is older than most of what it competes with. Cover and Hart proved it in 1967. In the large-sample limit, “for any number of categories, the probability of error of the nearest neighbor rule is bounded above by twice the Bayes probability of error”. They draw the consequence themselves: “in this sense, it may be said that half the classification information in an infinite sample set is contained in the nearest neighbor.” Half, from one stored example. And no further, which is the other half of the sentence.
The same paper names its ancestor. The first formulation of a rule of this type “appears to have been made by Fix and Hodges”. Theirs were two unpublished USAF School of Aviation Medicine reports, from February 1951 and August 1952.
KNN does not discover what nearby should mean; the pipeline defines that geometry.
Visual
A prediction is a local vote or local average
Every new row goes through the same query-time sequence. Encode the query with the fitted preprocessing. Measure distance against the stored training examples. Keep the k closest eligible ones. Aggregate their labels or targets by vote, weight or average. Then return the prediction, together with the supporting cases when those are useful.
- 1
Encode query
Apply the fitted preprocessing and feature representation.
- 2
Measure distance
Compare the query with stored training examples.
- 3
Select neighbors
Keep the k closest eligible examples.
- 4
Aggregate outcomes
Vote, weight, or average their labels or targets.
- 5
Return evidence
Expose the prediction and, when useful, the supporting cases.
Comparison
Three choices define the local estimator
Changing any one can alter the prediction even when the stored data is fixed.
A larger k is not automatically a better k, and the 1967 paper says so formally. Cover and Hart show that the single nearest-neighbour rule is admissible within the class of k-NN rules. For the n-sample problem there exists no k-NN rule with k other than 1 “which has lower probability of error against all distributions”. They prove it by exhibiting such a distribution. It has two categories with equal prior probabilities: one uniform on the unit disk centred at (−3, 0), the other uniform on the unit disk centred at (3, 0). On that data, 1-NN is strictly better than every larger neighbourhood. Neighbourhood size is a claim about the data in front of you. It is not a dial with a correct setting.
The metric is the same kind of choice, and the record on it is an argument rather than a default. A 2001 paper on high-dimensional data mining recommended the Manhattan L1 norm over L2 — “consistently more preferable”, its authors wrote — and the recommendation travelled. Two decades later a paper in Entropy put it on trial, under the title Fractional norms and quasinorms do not help to overcome the curse of dimensionality. Its authors ran 37 binary classification problems drawn from 25 UCI databases at k = 3, 5, 7 and 11. They found kNN under l0.5, l1 and l2 statistically indistinguishable. The 2020 abstract states it without hedging: “A systematic comparison shows that the difference of the performance of kNN based on lp for p=2, 1, and 0.5 is statistically insignificant.” Two published papers, one recommendation, one refutation. Which metric wins on your data is a measurement you run inside your own folds. It is not a setting you inherit from either of them.
Three dials remain. Neighborhood size: small k follows fine detail and noise, large k smooths across broader regions, and it is tuned only within valid splits, sometimes under class-aware constraints. The distance metric: Euclidean for scaled numeric geometry, Manhattan for coordinate-wise differences, cosine for direction in sparse spaces, domain metrics for structured data. Neighbor weighting: a uniform vote treats selected cases equally, inverse-distance emphasizes close cases, either can amplify duplicate or noisy points, and zero distances need explicit handling.
Neighborhood size
Controls how local or smooth the prediction is.
- Small k follows fine detail and noise
- Large k smooths across broader regions
- Must be tuned within valid splits
- May need class-aware constraints
Distance metric
Defines which feature differences count as close.
- Euclidean for scaled numeric geometry
- Manhattan for coordinate-wise differences
- Cosine for direction in sparse spaces
- Domain metrics for structured data
Neighbor weighting
Controls how evidence decays with distance.
- Uniform vote treats selected cases equally
- Inverse-distance emphasizes close cases
- Can amplify duplicate or noisy points
- Requires zero-distance handling
Example
Where local evidence helps and where it breaks
KNN is compelling when analog cases are meaningful and the search space is controlled. When it breaks, it is rarely subtle.
Zillow Group ran comparable-case valuation as a balance sheet. Zillow Offers bought homes and resold them, pricing them from comparable local properties. On 2 November 2021 the company announced that it would wind the business down. The same Q3 2021 results carried a $304.4 million inventory write-down, guidance of a further $240–265 million of losses on homes already under contract, $175–230 million of impairment, restructuring and other associated costs over the course of the wind-down, and a workforce reduction of approximately 25%.
The failure mode is named in the operator's own words. Rich Barton, Zillow Group co-founder and CEO, said in that day's earnings release: “We’ve determined the unpredictability in forecasting home prices far exceeds what we anticipated and continuing to scale Zillow Offers would result in too much earnings and balance-sheet volatility,”. The comparable homes were real. What was not survivable was the variance of the target inside the neighbourhood.
- Product matching: embeddings or engineered attributes retrieve similar catalog items for manual review.
- Medical reference: carefully matched historical cases can support a clinician, but confounding and treatment changes limit direct outcome transfer.
- House valuation: nearby properties may help when location, time, and property type are represented explicitly — and may not, as Zillow Offers demonstrated with a $304.4 million inventory write-down and about 25% of its parent company's workforce on 2 November 2021.
- High-dimensional raw telemetry: Beyer and colleagues proved the limit in 1999. “We show that under a broad set of conditions (much broader than independent and identically distributed dimensions), as dimensionality increases, the distance to the nearest data point approaches the distance to the farthest data point.” Their Theorem 1 gives the condition — if var((d_m)^p / E[(d_m)^p]) tends to 0 then P[DMAX_m <= (1+eps)DMIN_m] tends to 1 for every eps > 0 — and their experiments show the effect arriving at as few as 10–15 dimensions, not at some exotic frontier.
- Rare-class detection: majority voting can erase a sparse minority unless k, weights, and candidate filtering are designed carefully.
Voting creates edge cases that policy must resolve
Ties, class imbalance, duplicate rows and mixed-label neighborhoods all require explicit behavior. Probability-like vote fractions are local frequencies under the chosen representation. They are not guaranteed calibrated probabilities.
Class priors, distance weighting, or separate retrieval constraints can change the answer. These choices should be evaluated. They should not be hidden in defaults.
Analogy
Asking nearby residents instead of consulting a citywide average
Someone moving to a neighborhood asks the closest households about commute time. Local answers may be more relevant than a citywide average, provided closeness includes transport links and work location rather than physical distance alone.
Households answer for themselves, while training examples may be biased, duplicated, or outdated. Neighbors are evidence selected by a metric, not independent experts.
They are also not consulted in equal numbers, and the imbalance is measurable. Radovanovic and colleagues documented it in 2010, in a paper on popular nearest neighbors in high-dimensional data: “Through theoretical and empirical analysis involving synthetic and real data sets we show that under commonly used assumptions this distribution becomes considerably skewed as dimensionality increases, causing the emergence of hubs, that is, points with very high k-occurrences which effectively represent "popular" nearest neighbors.” Across 50 real data sets, the Spearman correlation between dimensionality d and the skewness of the k-occurrence distribution S(N_k) was 0.62. A minority of stored rows ends up answering for a disproportionate share of every query the system will ever receive. That is a property of the metric, not of those rows.
Local learning succeeds only when the neighborhood definition preserves the factors that drive the target.
Steps
Design and validate a neighbor-based system
Do not tune k before validating the geometry. Define which rows are eligible to become neighbors at all. Fit scaling, encoding, imputation or a learned representation inside the folds. Read the actual supporting cases returned for a diverse set of queries. Tune k and weighting on held-out decisions rather than training accuracy. Compare crowded, sparse, boundary and minority regions separately. And measure index memory, latency, update cost and deletion behavior before anything is served.
1. Define comparable cases
Specify which rows are eligible to become neighbors.
2. Fit preprocessing
Scale, encode, impute, or learn a representation inside folds.
3. Inspect neighbor lists
Read actual supporting cases for diverse queries.
4. Tune k and weighting
Use held-out decisions, not training accuracy.
5. Test density slices
Compare crowded, sparse, boundary, and minority regions.
6. Plan retrieval operations
Measure index memory, latency, updates, and deletion behavior.
Key idea
A close neighbor may still be outside support
Every query has a nearest training example, even if all examples are far away. The algorithm will return a prediction anyway, unless the system adds a distance, density or conformity check.
Define an abstention policy for queries with weak local support. This is not modern tooling bolted onto an old algorithm. The first paper to give a k-nearest-neighbour classifier a way to decline appeared in 1970, written by M. E. Hellman. It also left the hard half of the problem exactly where it found it. Christoph Dalitz, surveying reject options and confidence measures for kNN classifiers, records what was missing: “In the first paper introducing a reject option for kNN classifiers, Hellman proposed to apply a threshold on the kNN probability estimator (3), but made no suggestion how to find an appropriate threshold”. The reject option dates from 1970. The threshold is still yours to pick, justify and monitor.
Nearest is a relative rank; it does not prove that anything is genuinely near.
KNN shifts cost from fit time to storage and serving
Exact search can become expensive as rows and dimensions grow. Tree-based spatial indexes help mainly in lower-dimensional settings, while approximate nearest-neighbor indexes trade exactness for speed and memory.
How expensive is not a matter of opinion; it is scored in public. NeurIPS ran a Billion-Scale Approximate Nearest Neighbor Search Challenge in 2021, across three hardware tracks: a limited-DRAM Azure VM with FAISS as the baseline, DRAM-plus-SSD with DiskANN as the baseline, and unrestricted hardware. Entrants were ranked by recall at a query-throughput threshold. The organisers state the scope: “We compiled six diverse billion-scale datasets, four newly released for this competition, that span a variety of modalities, data types, dimensions, deep learning models, distance functions and sources.” Index memory, latency and recall are the competition's scoring rule because they are the deployed model's specification.
Updates, privacy deletion, deduplication and stale examples are production concerns, because the training set remains part of the live predictor. A regulator can be the one to say so. In the FTC's Everalbum matter, the proposed consent order published in the Federal Register on 25 January 2021 reached past the data into what had been built from it: “Part III of the proposed order requires Respondent to delete (A) photos and videos of Ever app Users who requested deactivation of their accounts, (B) face recognition data that it created without obtaining Users' affirmative express consent, and (C) models and algorithms it developed in whole or in part using images from Users' photos.” The Commission finalised the settlement on 7 May 2021 by a 4-0 vote. For a lazy learner, clause (A) and clause (C) name the same deletion. The stored examples are the model.
For a lazy learner, data management is model management.
Case
A billion-vector neighbour graph takes under twelve hours and none of it is training
The engineering that makes this survivable is a research literature of its own. Malkov and Yashunin's Hierarchical Navigable Small World graphs, first posted in 2016 and published in 2020, build “a multi-layer structure consisting from hierarchical set of proximity graphs (layers) for nested subsets of the stored elements”. That trades exactness for a logarithmic search.
Johnson and colleagues at Facebook AI Research measured what it buys at scale. Their GPU implementation, described in 2017, enables “the construction of a high accuracy k-NN graph on 95 million images from the Yfcc100M dataset in 35 minutes, and of a graph connecting 1 billion vectors in less than 12 hours on 4 Maxwell Titan X GPUs”. None of those hours is training. They are the standing cost of keeping the training set queryable.
Key takeaways
- KNN stores examples and defers most computation until a query is evaluated; Cover and Hart's 1967 bound says half the classification information in an infinite sample already sits in the single nearest stored case.
- The feature representation and distance metric define what counts as comparable, and which norm to use is an experiment rather than an inheritance: a 2020 Entropy study found l0.5, l1 and l2 statistically indistinguishable across 37 binary problems from 25 UCI databases.
- Small neighborhoods follow local variation and large ones smooth across broader regions, and Cover and Hart proved that no k other than 1 has lower error against all distributions.
- Vote fractions and weighted averages are local frequencies under the chosen representation, not automatically calibrated uncertainty estimates.
- Every query has a nearest case, and Beyer and colleagues showed the nearest distance converging on the farthest from as few as 10–15 dimensions, so a distance or density check and a reject-option threshold — open since Hellman posed it in 1970 — are part of the design, not an extra.
- Indexing, updates, deletion, duplicates, memory and latency are the deployed KNN model: the NeurIPS'21 challenge scores exactly those, and the FTC's Everalbum order compelled deletion of the derived models along with the photos.