Contents
k-Nearest NeighborsHow to Choose k and Why to Scale
Keep the data, measure the distance, let the closest vote
A tutorial companion to the video Machine Learning Interview #17: k-Nearest Neighbors: How to Choose k and Why to Scale PDF
01Introduction
1.1The question
How would you guess a wine you have never tasted? Compare it with wines you know, find the ones most like it, and go with the majority. That is k-nearest neighbors, one of the oldest and simplest methods in machine learning, and it does not train at all. Because it is so simple, interviewers use it to test whether you understand the ideas that sit under every model: distance, scaling, overfitting and how to choose a hyperparameter. They ask: how does k-nearest neighbors work, and how do you choose k? This tutorial answers both, and derives every step on the way.
1.2Prerequisites and notation
Prerequisites. Vectors and the Euclidean length; expectation and variance. Overfitting and the bias–variance tradeoff (Episode 2), the curse of dimensionality (Episode 10) and cross-validation (Episode 11) help, and are explained again where we use them.
Notation. We have n training points (x_i,y_i), i=1,\dots,n. Each input x_i=(x_{i1},\dots,x_{id}) is a vector of d measurements, and each label y_i is one of C classes (for regression, a number). For our wines n=124, d=13 and C=3. A new input is x. The distance between two inputs is \operatorname{dist}(x,x'), and N_k(x) is the set of the indices of the k training points closest to x. For measurement j, \mu_j and \sigma_j are its mean and standard deviation over the training points. \mathbb I(\cdot) is 1 if the condition holds and 0 otherwise.
1.3A short history
The nearest-neighbor rule was introduced by Evelyn Fix and Joseph Hodges in a 1951 report for the US Air Force School of Aviation Medicine, which proved that the rule becomes as good as the best possible classifier as the data grow, if k grows too, but slowly (Fix and Hodges, 1989). Thomas Cover and Peter Hart showed in 1967 that even a single neighbor, with unlimited data, makes at most twice the lowest possible error (Cover and Hart, 1967); Charles Stone later proved that the rule is consistent for every distribution (Stone, 1977). Jon Bentley’s k-d tree of 1975 made the search for neighbors fast in low dimensions (Bentley, 1975; Friedman et al., 1977). Textbook treatments are Murphy (2022, §16.1), Hastie et al. (2009, §2.3.2 and §13.3) and Duda et al. (2001, §4.5).
All examples use one real data set, the wine data of Forina et al. (1988): 178 wines grown in the same region of Italy from three cultivars, each with 13 chemical measurements, such as alcohol, flavanoids, color intensity, hue and proline (an amino acid). We keep 54 wines aside as a test set and train on the other 124. All numbers in this tutorial were computed for this tutorial, with the same data as the companion video.