- Introduced by
- Cover, T.M. & Hart, P.E.
- Year
- 1967
- Type
- Instance-based (non-parametric) learning
What does it do?
K-Nearest Neighbors (KNN) is a non-parametric, instance-based method that classifies or predicts a new observation from the k closest examples in the training data.
For classification it takes a majority vote among those neighbors; for regression it averages their values. The nearest-neighbor rule on which it builds was analyzed by Cover and Hart in 1967.
The intuition behind the method
The idea is simple: similar inputs tend to have similar outputs. To label a new point, KNN finds the handful of training examples that sit nearest to it in feature space and lets them decide. There is no equation fitted in advance — the training data itself is the model, and a prediction is made only when a new point arrives.
History
The nearest-neighbor decision rule was analyzed by Thomas Cover and Peter Hart in their 1967 paper in the IEEE Transactions on Information Theory. Their analysis showed that, for large samples and suitably smooth underlying distributions, the error of the nearest-neighbor rule is bounded above by twice the Bayes error, the minimum error achievable over all decision rules. The k-neighbor form with voting, as used in this page, is a generalization of that rule, and it is now widely used as an instance-based baseline.
When to use it
Choose KNN for classification or regression on tabular data whose features are numeric (continuous or binary) and for which a distance is meaningful once scaled. It makes no distributional assumption, so it is worth considering when the assumptions of a parametric model are doubtful. A parametric model such as linear regression estimates only a few coefficients, but it commits to a functional form for the relationship; if that form is far from the truth, its predictions can be poor, whereas a non-parametric method does not assume a parametric form. KNN suits cases where the number of features p is small relative to the sample size n (p far smaller than n is preferred). Avoid it when there are many features, because distances lose contrast and nearest neighbors stop being informative; in that setting a parametric model such as logistic regression or Naive Bayes is usually a better starting point. It is also a poor fit when fast predictions are needed on a very large training set, since each prediction scans the stored data. Ordinal or categorical features should be used only if their numeric coding makes Euclidean differences meaningful.
Limitations and considerations
- Euclidean distance over raw features is dominated by variables with large numeric ranges, so standardization is a precondition for the method to work as intended.
- Distances lose contrast as the number of features grows relative to the sample size, so neighbors become uninformative in high-dimensional data.
- Irrelevant or noisy features distort neighbor selection, and this effect grows with their number, so feature selection or feature weighting should be considered alongside standardization.
- Prediction requires computing distances to every stored training point, so cost grows with the training set size.
- In small samples the nearest neighbors of a point may be far from it, so the local vote rests on little evidence.
- The fraction of neighbors voting for a class is a crude probability estimate that depends on k and on class balance, so it should not be read as a calibrated risk without checking.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Distribution-free: the nearest-neighbor rule does not depend on the underlying joint distribution of the data, as the 1967 analysis emphasizes.
- No fitting step: the training data are stored and used directly, so there are no coefficients to estimate, and the decision boundary can be nonlinear.
- The same neighbor-based rule covers multi-class classification through majority voting and regression through averaging the k neighbors' values.
- A prediction can be inspected by showing the k training examples that determined it.
Applications
- Classification of tabular records into two or more classes when a labeled reference set is available and similarity in the chosen features is meaningful.
- Regression of a numeric target by averaging the values of the most similar training examples.
- Benchmarking: a non-parametric reference model against which parametric classifiers can be compared on the same standardized features.
- Exploratory checks on whether nearby examples share labels, which indicates how much local structure a dataset contains.
How it works
How it works
For a new observation, KNN computes its distance to every training example, using the Euclidean formula shown in the mechanics section across all p features, where x is the new observation and x_i is the i-th training example. Because this distance is scale-sensitive, features should be standardized first, with the scaling statistics estimated from the training data only. Without standardization, a variable with a large numeric range dominates the distance and determines which points count as nearest.
Formula
d(x, x_i) = \sqrt{\sum_{j=1}^{p}(x_j - x_{ij})^2}The k training points with the smallest distances to the new observation are selected as its neighbors. The value of k sets how local the decision is: a small k follows local structure closely but responds strongly to noisy points, while a larger k gives a smoother boundary. k is usually chosen by comparing several candidate values with cross-validation and keeping the one with the best validation performance.
The neighbors then determine the output. For classification the predicted class is the most frequent label among the k neighbors; for regression the prediction is the mean of their target values. Ties in the vote must be resolved by a fixed rule stated in advance, for example by the class of the nearest tied neighbor. Distance-weighted voting, which gives closer neighbors more influence, is a common alternative. Each prediction requires computing distances to the stored training set, so prediction cost grows with the size of that set.
Formula
\hat{y} = \text{mode/mean of the } k \text{ nearest neighbors}Common pitfalls
- Applying Euclidean distance to categorical features coded as numbers, where the squared differences in the distance formula have no meaningful interpretation.
- Standardizing with statistics computed on the full dataset, including test points, which leaks information into the evaluation.
- Choosing k without validation, or selecting it on the same data used to report final performance.
- Evaluating on the training set itself: a training point is one of its own nearest neighbors (at distance zero), which inflates training-set accuracy, especially for small k.
- With imbalanced classes the majority vote favors the frequent class, so per-class recall should be checked, and class-weighted voting or resampling considered.
Frequently asked questions
How do I choose the value of k?
k should be selected with cross-validation rather than guessed: compare several candidate values on held-out folds and keep the one with the best validation performance. A small k follows the data closely but is sensitive to noisy points, while a larger k smooths the decision boundary.
Why must I standardize the features?
KNN decides who is 'nearest' using distance, which is scale-sensitive. If one feature is on a much larger numeric scale than the others, it dominates the distance and distorts the neighbor set. Standardizing features (for example with a StandardScaler) is required so each feature contributes fairly.
Why does KNN struggle with many features?
In high-dimensional spaces all points become roughly equidistant — the curse of dimensionality — so 'nearest' neighbors are no longer meaningfully close. KNN performance drops quickly, and a parametric model such as Naive Bayes or logistic regression is usually preferable. Keeping p far smaller than n helps.
Is there a training step?
Not in the usual sense. KNN is instance-based (lazy): it simply stores the training data and does all the work at prediction time, when it computes distances to find the nearest neighbors of a new point.
Related methods
Sources
Cover, T.M. & Hart, P.E. (1967). Nearest Neighbor Pattern Classification. IEEE Transactions on Information Theory, 13(1), 21–27.
Open DOI reference2013_Book_AnIntroductionToStatisticalLea, p. 105