k-nearest neighbors
k 近邻
Predict from stored examples while making distances, scaling, ties, query costs and evaluation boundaries explicit.
knnAsk nearby examples, but first define nearby
You have labeled examples and a new case. Instead of fitting a line or a neural network, keep the examples, find the nearest ones, and let their labels vote. This is k-nearest neighbors, or kNN. It puts much of the work at prediction time. The premise is that nearby inputs provide useful information about the new label; a distance formula cannot establish that premise by itself.
Consider two invented training vectors: class A at and class B at . Query with . Raw squared Euclidean distances are 1,000,001 and 9, so B wins. Now divide each squared feature difference by that feature’s variance in the training set. Those variances are 1 and 250,000; the distances become 5 and 9, so A wins. Neither answer is automatically correct. The example shows that feature units and scaling are part of the classifier, not cosmetic preprocessing.
Distance, neighborhood, then a decision
Let the training set be , with . Choose an integer , a distance, and explicit tie rules. Let contain the indices of the selected nearest points to query . Uniform-vote classification predicts
The indicator is one when the neighbor belongs to class . With several classes, the winning class need only have the most votes, not necessarily more than half. There can be a tie between class vote counts and a separate tie in distances at the neighborhood boundary. Choosing an odd does not remove either problem in general. The basic rule and its distance dependence are presented in Cornell’s kNN notes; scikit-learn’s nearest-neighbor guide specifically warns about equally distant points with different labels at positions and .
For numerical features, a diagonal rescaling of Euclidean distance gives
The square root is unnecessary for ranking these nonnegative distances. This does not mean squared distance itself is a metric: it need not satisfy the triangle inequality. One choice is to use each training feature’s empirical variance for . The common centering mean cancels in a pairwise difference, so the expression is equivalent to Euclidean distance after standardization. Our program uses scale squared one for a training-constant feature; any query difference on that feature then adds the same amount to every candidate distance and cannot change their order.
The same neighborhood supports regression. Under uniform weights, the local constant minimizing squared error is the average target:
To see why, differentiate with respect to ; its derivative is and its second derivative is . This is a different output rule from classification. scikit-learn, nearest-neighbor regression describes this averaging approach.
At , a single local observation determines the label. At , every query uses every training label and returns the same majority class under a fixed class-tie rule. In between, increasing averages more examples but can merge neighborhoods whose labels differ. A larger need not improve accuracy monotonically. Select it using validation appropriate to the sampling process, along with the feature representation and distance.
Keep exact distances and reproducible ties
The complete standard-library program implements uniform-vote classification on small rational datasets. Integers and Fraction inputs give exact squared distances. It deliberately rejects ordinary floats so that roundoff is not confused with a distance tie. Labels are nonempty strings; training vectors must have one common nonzero dimension.
Training copies the examples and optionally learns feature variances from them. Querying maintains a heap of candidates. Equal distances prefer the smaller original training-row index; tied class vote totals prefer the lexicographically earlier label. Changing training order can therefore change a prediction when there is a boundary tie. These choices define this implementation, rather than claiming a unique universal tie policy.
from fractions import Fraction as F
from collections import Counter
from heapq import nsmallest
def coordinate(x):
if type(x) is not int and not isinstance(x,F):
raise ValueError('use integer or Fraction coordinates')
return F(x)
def fit_knn(points,labels,standardize=False):
if type(standardize) is not bool:
raise ValueError("standardize must be a Boolean")
x=tuple(tuple(coordinate(v) for v in row) for row in points)
y=tuple(labels)
if not x or not x[0] or len(x)!=len(y):
raise ValueError('matching nonempty data required')
dimension=len(x[0])
if any(len(row)!=dimension for row in x) or any(not isinstance(c,str) or not c for c in y):
raise ValueError('consistent dimensions and nonempty string labels required')
scale2=[F(1)]*dimension
if standardize:
for j in range(dimension):
mean=sum(row[j] for row in x)/len(x)
variance=sum((row[j]-mean)**2 for row in x)/len(x)
scale2[j]=variance if variance else F(1)
return x,y,tuple(scale2)
def query_knn(model,query,k):
x,y,scale2=model
query=tuple(coordinate(v) for v in query)
if len(query)!=len(scale2) or type(k) is not int or not 1<=k<=len(x):
raise ValueError('matching query and integer 1 <= k <= N required')
distances=((sum((a-b)**2/s for a,b,s in zip(row,query,scale2)),i)
for i,row in enumerate(x))
neighbors=nsmallest(k,distances)
votes=Counter(y[i] for distance,i in neighbors)
winner=min(votes,key=lambda label:(-votes[label],label))
return winner,neighbors
raw=fit_knn([(1,1000),(3,0)],['A','B'])
scaled=fit_knn([(1,1000),(3,0)],['A','B'],standardize=True)
assert scaled[2]==(1,250000)
assert query_knn(raw,(0,0),1)==('B',[(F(9),1)])
assert query_knn(scaled,(0,0),1)==('A',[(F(5),0)])
tie=fit_knn([(-1,0),(1,0),(0,1)],['C','B','A'])
assert query_knn(tie,(0,0),1)[0]=='C' # first stored row wins equal distance
assert query_knn(tie,(0,0),3)[0]=='A' # one vote per class: label order
The first example verifies the scale-induced change from B to A. The second has three equidistant training points from three classes. With , row order selects C; with , each class has one vote and the class-order rule selects A. The returned neighbor distances and indices make both decisions inspectable.
Copying and, when requested, scaling the training data uses arithmetic and model storage. A single query computes distances in arithmetic. Selecting entries with nsmallest has an upper bound of comparisons, with special cases for one neighbor or selecting all points. Query working storage is beyond the stored model: a generator avoids keeping every distance. Rational bit costs depend on numerator and denominator lengths.
A full comparison of every training point with every other point would involve distance arithmetic; that is not the cost of one query. KD trees and ball trees can reduce work in favorable geometry, but their speed depends on dimension, structure, and requested . They do not provide an unconditional logarithmic worst-case query guarantee. scikit-learn’s algorithm discussion separates single-query costs from all-pairs search and describes deterioration in higher dimensions.
A close training neighbor is not proof of a good forecast
Querying a stored training example often finds itself at distance zero. A one-neighbor classifier can then report perfect training accuracy while performing poorly on new data. Leave-one-out evaluation must remove the current row, and any learned scaling must be fitted on the remaining training fold. Do not remove every zero-distance neighbor: different legitimate training cases can share the same coordinates. Near duplicates, repeated measurements from one person, or future records leaking across a time split also require appropriate grouping.
Scaling, imputation, and feature selection must be learned from training data and then applied unchanged to held-out data. During cross-validation this fitting belongs inside each fold. scikit-learn’s common-pitfalls guide explains why fitting a transformation on the complete dataset can leak information even without using test labels explicitly.
Dimension affects how local a neighborhood can be. Under a uniform distribution on the unit cube , an axis-aligned cube of side entirely inside the domain has probability mass . To capture a fixed fraction of population mass this way,
For , the side length is 0.1 in two dimensions, about 0.631 in ten, and about 0.955 in one hundred. A region containing a modest population fraction can span most of each coordinate’s range. This is a volume calculation under a particular distribution, not an exact formula for a random Euclidean kNN ball or a theorem that every high-dimensional dataset fails. Low intrinsic dimension, useful embeddings, and irrelevant-feature removal can change the geometry. Cornell’s dimensionality discussion uses the unit-cube example to motivate the issue.
Uniform vote fractions are empirical neighbor proportions, not automatically calibrated probabilities. Distance weighting is another option, but inverse-distance weights need an explicit rule for zero distances, such as voting only among exact matches. Mixed numerical and categorical features also need a justified distance; assigning category names arbitrary integers does not establish meaningful numerical proximity.
Change one decision rule at a time
- For A=, B= and query , why does standardizing with the training variances change the nearest neighbor? Answer: raw squared distances are 1,000,001 and 9. Dividing by variances 1 and 250,000 gives A distance and B distance 9. The relative feature weights changed.
- If , can moving the query change its predicted class in this implementation? Answer: no. All training labels always vote and the class-tie rule is fixed. Distances only change their ordering, not the vote totals.
- Does odd guarantee a unique class winner? Answer: no. Three classes can receive one vote each. Even can encounter several equally near candidate points, so the neighborhood also needs a tie rule.
- To evaluate a training row by leave-one-out, is it enough to remove its self-match after fitting scaling on all rows? Answer: no. Refit learned preprocessing without that row, then query against the remaining rows. Keep other legitimate zero-distance examples; identifying the held-out record requires its row identity, not just its coordinates.
What the classical error bound actually says
Cover and Hart’s 1967 paper analyzes nearest-neighbor classification in the large-sample limit. For the binary problem, with training and new-query pairs (X,Y) sampled jointly i.i.d. and the paper’s stated regularity conditions, the limiting one-neighbor risk and Bayes risk satisfy
The Bayes risk is the smallest possible expected classification error using the same feature information and knowing its distribution. The bound is asymptotic, not a finite-data accuracy promise. The paper’s theorem specifies conditions on a separable metric space and continuity or atomic points; it is not a claim about arbitrary data collection or label-dependent tie selection. Cover and Hart, Section VI
For a concrete counterexample to automatic optimality, suppose features contain no label information and . The Bayes classifier always predicts 1, with error 0.2. A neighbor’s independently drawn label disagrees with the new label with probability . More stored points do not remove that label noise for fixed one-neighbor prediction. Choosing a neighborhood size that changes with sample size raises a different statistical question. Metric learning and efficient neighbor search address other parts of the method: what closeness should mean and how to find it cheaply.
Make a prediction, then check
With k=3, which tie can still occur?
Learning objectives
- Define distance, neighborhood and voting and handle distance ties separately from class-vote ties.
- Calculate scale-induced prediction changes and distinguish storage, single-query and all-pairs costs.
- Check fold-specific preprocessing and self-match leakage and state the limits of dimension intuition and the classical 1-NN risk bound.
Prerequisites & connections
Explore related knowledge →References
- Nearest Neighbor Pattern Classification
Thomas M. Cover; Peter E. Hart · 1967 - Cornell CS 4/5780 — k-nearest neighbors / Curse of Dimensionality
Cornell University · 2022 - scikit-learn — Nearest Neighbors
scikit-learn developers - scikit-learn — Common pitfalls and recommended practices
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Read Cover–Hart, Cornell and sklearn sources and separated conditional limiting risk, cube-volume intuition and actual query complexity.
- Checked heap selection against full distance sorting; computed training variances independently by pair differences and verified scale reversal, affine invariance, ties and k=N.
- Checked constant columns, leave-one-out with distinct cases sharing coordinates, invalid inputs and label-noise risk 0.32; matched four bilingual answers, equations, code and anchors.
- Cross-review checked both tie rules, constant columns, zero distances, single/all-query costs and the Cover–Hart paper; wording now explicitly requires jointly i.i.d. training and new-query (X,Y) pairs. The existing sklearn-pitfalls source was reused rather than duplicating the same page.
- The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.
Source locations checked:
- Nearest Neighbor Pattern Classification · Original Stanford-hosted PDF: page 1 lower half title/abstract and iid setting (upper half is preceding paper, excluded); Section II and III PDF2, Section V iid nearest-neighbor convergence lemma PDF3–4, Section VI binary limiting-risk theorem and proof PDF4–5. Bound is asymptotic with stated separable-metric/continuity-or-atom hypotheses, not finite-sample optimality; DOI 10.1109/TIT.1967.1053964.
- Cornell CS 4/5780 — k-nearest neighbors / Curse of Dimensionality · Fall 2022 kNN notes, algorithm definition, Minkowski distance, k=1/k=N and Curse of Dimensionality sections read. Cube-volume illustration explicitly restricted to a uniform interior cube; did not repeat an unconditional high-dimensional failure claim or claim that converging points necessarily coincide at finite n.
- scikit-learn — Nearest Neighbors · Lines 75–87 storing instances and distance-tie warning; sections 1.6.2 and 1.6.3 lines 144–158 vote/mean rules; section 1.6.4 lines 167–214 all-pairs versus single-query cost and tree geometry dependence. No blanket worst-case log-time tree claim.
- scikit-learn — Common pitfalls and recommended practices · Sections 12.1 and 12.2, especially lines 122–141: training-only preprocessing, splitting first, per-fold fitting and pipeline rationale. Actual fetched text read; used for scaling and leave-one-out leakage discussion.
Related topics