k-nearest neighbours
| Problem | Classify a point by the labels of the training points closest to it |
| Devised by | Evelyn Fix and Joseph Hodges (1951); Thomas Cover and Peter Hart (1967), the error bound; Sahibsingh Dudani (1976), distance weighting |
| Accuracy | As the sample grows, the 1-nearest-neighbour error is at most twice the optimal (Bayes) error; with and , -NN is consistent |
| Cost | No training. Prediction per query by brute force |
| Read first | Foundations: models, data, preprocessing and metrics |
| API | KNearestNeighbors (new(k), distance_weighted, predict_proba, neighbours) |
Overview
The nearest-neighbour rule is the simplest classifier that can learn any boundary: to classify a point, find the training points closest to it and take a majority vote. There is no training, only storage, and no assumption about the shape of the classes. The number of neighbours controls the smoothness of the boundary, from jagged (, every training point decides its own neighbourhood) to nearly linear (large ). The price is paid at prediction time, and in high dimensions, where all points are nearly equally far apart.
Where it is used
k-nearest neighbours needs no training and adapts to any data distribution.
- Recommendation and search. Finding similar items, users or documents.
- Pattern recognition. Handwritten digits, gene-expression profiles and sensor signatures classified by their closest examples.
- Imputation and anomaly detection. Filling missing values from similar records, and flagging points far from all their neighbours.
- Needs good distances. The spatial trees of the geometry chapter make the search fast.
History
Evelyn Fix and Joseph Hodges (1951), in a technical report for the US Air Force School of Aviation Medicine, introduced nonparametric discrimination by nearest neighbours and proved its consistency. Thomas Cover and Peter Hart (1967) showed that with unlimited data the 1-NN error rate is at most twice the Bayes rate, the smallest achievable: half the information for classification lies in the nearest neighbour. Sahibsingh Dudani (1976) proposed weighting the votes by distance. Data structures such as k-d trees (Jon Bentley, 1975) and, in high dimensions, approximate methods such as locality-sensitive hashing (Piotr Indyk and Rajeev Motwani, 1998) make the search fast.
The idea
Voting
The method has no training step at all: it simply stores the training data. To classify a query point , find the set of the training points nearest to it in Euclidean distance, and let them vote. The fraction of the neighbours belonging to class is an estimate of the class probability,
and the prediction is the class with the most votes. The underlying assumption is only that nearby points tend to have the same label.
With distance weighting, each neighbour’s vote counts , where is its distance from the query, so that closer points matter more. A training point at distance zero decides alone.
Choosing k
The number of neighbours controls how smooth the classifier is.
With every training point decides its own surroundings, so the boundary encloses every isolated point, including mislabelled and noisy ones. With the vote averages out such points and the boundary follows the two moons. With the neighbourhood is so large that the curved structure is averaged away as well, and the boundary approaches a straight line.
The training error is misleading here. With each training point is its own nearest neighbour, so the training error is zero; it grows with . The error on new data is high for very small (the classifier follows noise) and for very large (it ignores structure), and lowest in between:
Figure 11.7. Error against k.
The curse of dimensionality
Nearest-neighbour methods depend on neighbours being near. In high dimensions they are not.
Suppose the data are spread uniformly in a unit cube with dimensions, and we want a neighbourhood, a smaller cube, that contains a fraction of the data. Its volume must be , so its edge length is . In one dimension, capturing 1% of the data needs an interval of length 0.01. In ten dimensions it needs a cube of edge , spanning 63% of the range of every feature. Such a “neighbourhood” is not local in any useful sense, and the labels of points that far away say little about the query.
A related effect is that distances concentrate: in high dimensions the nearest and the farthest training points are at nearly the same distance from a query, so the ranking of neighbours is easily upset by noise. Nearest-neighbour methods therefore degrade as the dimension grows, unless the data lie near a low-dimensional surface (a manifold) within the high-dimensional space, as real data often do.
Two practical consequences follow. An irrelevant feature adds pure noise to every distance, so features should be selected. And a feature measured on a large scale dominates the distance, so features should be standardised.
Algorithm
Fit: store the training points and their labels. Nothing is computed.
Predict, for one query point:
- compute the squared Euclidean distance from the query to every training point (the square root is not needed to compare distances);
- select the smallest distances by a partial sort, which finds them in linear time without sorting the rest;
- vote: add 1 to the tally of each neighbour’s class, or with distance weighting. If a neighbour is at distance zero under distance weighting, it alone decides;
- return the class with the largest tally, or the tallies divided by their sum as probabilities.
A prediction costs for training points with features. All the work is done at prediction time, the opposite of most other models. For large training sets a spatial tree finds the neighbours without visiting every point, in low dimensions.
Implementation
/// The `(index, distance)` of the `k` nearest training points to `query`, nearest first.
pub fn neighbours(&self, query: &[f64]) -> Vec<(usize, f64)> {
let mut d: Vec<(usize, f64)> = self.train.rows().into_iter().enumerate().map(|(i, r)| (i, squared_distance(&r.to_vec(), query))).collect();
if d.is_empty() || self.k == 0 {
return Vec::new();
}
let k = self.k.min(d.len());
d.select_nth_unstable_by(k - 1, |a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
d.truncate(k);
d.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
d.into_iter().map(|(i, d2)| (i, d2.sqrt())).collect()
}
/// Class probabilities (vote shares) for each row of `x`, as a `(rows, classes)` matrix.
pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
self.check_fitted(x)?;
let mut out = R2D::zeros((x.nrows(), self.classes));
for (i, row) in x.rows().into_iter().enumerate() {
let near = self.neighbours(&row.to_vec());
let exact: Vec<&(usize, f64)> = near.iter().filter(|n| n.1 == 0.0).collect();
let votes: Vec<(usize, f64)> = if self.distance_weighted && !exact.is_empty() {
exact.iter().map(|n| (n.0, 1.0)).collect()
} else {
near.iter().map(|&(j, d)| (j, if self.distance_weighted { 1.0 / d } else { 1.0 })).collect()
};
let total: f64 = votes.iter().map(|v| v.1).sum();
for (j, w) in votes {
out[[i, self.labels[j]]] += w / total;
}
}
Ok(out)
}
- Ties among equidistant neighbours are broken by training index, and ties in the vote by the lower class label, so results are deterministic.
- The search is brute force. For many queries in two or three dimensions, the k-d tree of the
lib_jsl_geometrycrate is faster.
In practice
//! k-nearest neighbours: choosing k and weighting by distance.
use lib_jsl_machine_learning::common::Classifier;
use lib_jsl_machine_learning::datasets::make_moons;
use lib_jsl_machine_learning::metrics::accuracy;
use lib_jsl_machine_learning::supervised::classification::KNearestNeighbors;
fn main() {
let (x, labels) = make_moons(100, 0.3, 1);
let (x_test, test_labels) = make_moons(1000, 0.3, 2);
for k in [1, 5, 15, 45, 135] {
let mut plain = KNearestNeighbors::new(k);
plain.fit(x.view(), &labels).unwrap();
let mut weighted = KNearestNeighbors::new(k).distance_weighted(true);
weighted.fit(x.view(), &labels).unwrap();
println!(
"k = {k:>3}: test accuracy {:.3}, distance-weighted {:.3}",
accuracy(&test_labels, &plain.predict(x_test.view()).unwrap()).unwrap(),
accuracy(&test_labels, &weighted.predict(x_test.view()).unwrap()).unwrap()
);
}
let mut model = KNearestNeighbors::new(5);
model.fit(x.view(), &labels).unwrap();
let near = model.neighbours(&[0.5, 0.25]);
println!("neighbours of (0.5, 0.25): {}", near.iter().map(|(i, d)| format!("#{i} (class {}, {d:.2})", labels[*i])).collect::<Vec<_>>().join(", "));
}
k = 1: test accuracy 0.877, distance-weighted 0.877
k = 5: test accuracy 0.896, distance-weighted 0.891
k = 15: test accuracy 0.901, distance-weighted 0.902
k = 45: test accuracy 0.899, distance-weighted 0.901
k = 135: test accuracy 0.798, distance-weighted 0.883
neighbours of (0.5, 0.25): #29 (class 0, 0.05), #116 (class 1, 0.09), #122 (class 1, 0.10), #5 (class 0, 0.15), #51 (class 0, 0.18)
Distance weighting makes the choice of less critical: at , two thirds of the 200 training points, plain voting is swamped by distant points while the weighted vote still works.
Strengths
- No training; any boundary shape; naturally multi-class; easy to explain (“these were the most similar cases”).
Weaknesses
- Prediction costs per query and the whole training set must be kept.
- Sensitive to feature scaling and irrelevant features; degrades in high dimensions.
Exercises
- Show that the leave-one-out error of 1-NN can be computed in , and use it to choose .
- In dimensions with uniform points in the unit cube, estimate the median distance from the origin to the nearest point, and how it grows with for fixed .
- Sketch the proof of the Cover-Hart bound for two classes: as , at a point with .
- Implement a k-d tree search for two-dimensional data and compare its speed with brute force for .
Hints and answers
- Compute the full distance matrix (), exclude each point from its own neighbours, and read off the leave-one-out error for every from the sorted neighbour lists.
- For points uniform in the unit ball in dimensions the median distance from the centre to the nearest point is ; for it is about at . The nearest point is therefore as far as the boundary of the ball: neighbourhoods are no longer local in high dimension.
- At a point with , the 1-NN rule predicts the label of a neighbour that, as , is at the same location and has an independent label. It errs if the two labels differ: .
- A k-d tree answers 2D neighbour queries in expected time against for brute force, a speed-up of two to three orders of magnitude at .
Further reading
- T. M. Cover and P. E. Hart, “Nearest neighbor pattern classification”, IEEE Transactions on Information Theory 13 (1967) 21–27.
- E. Fix and J. L. Hodges, “Discriminatory analysis. Nonparametric discrimination: consistency properties”, USAF School of Aviation Medicine report 4, 1951; reprinted in International Statistical Review 57 (1989) 238–247.
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, chapter 13.