Skip to main content

lib_jsl_machine_learning/supervised/classification/
k_nearest_neighbors.rs

1//! k-nearest-neighbours classification.
2//!
3//! See the book entry [k-nearest neighbours](https://jwkunz.github.io/lib_jsl/book/machine_learning/nearest-neighbours.html).
4
5use crate::common::{Classifier, argmax, check_features, check_xy, class_count, squared_distance};
6use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
7
8/// Classifies a point by a vote among its `k` closest training points (Euclidean distance). The
9/// model is "lazy": fitting just stores the data. With `distance_weighted` each neighbour's vote
10/// counts `1/distance` so nearer points matter more (an exact match decides alone). Prediction is
11/// brute force, `O(n·d)` per query; use a k-d tree from the geometry crate for large 2D/3D sets.
12#[derive(Debug, Clone)]
13pub struct KNearestNeighbors {
14    k: usize,
15    distance_weighted: bool,
16    train: R2D,
17    labels: Vec<usize>,
18    classes: usize,
19}
20
21impl KNearestNeighbors {
22    pub fn new(k: usize) -> Self {
23        KNearestNeighbors { k, distance_weighted: false, train: R2D::zeros((0, 0)), labels: Vec::new(), classes: 0 }
24    }
25
26    pub fn distance_weighted(mut self, weighted: bool) -> Self {
27        self.distance_weighted = weighted;
28        self
29    }
30
31    fn check_fitted(&self, x: VR2D) -> Result<(), ErrorsJSL> {
32        if self.labels.is_empty() {
33            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
34        }
35        check_features(x)?;
36        if x.ncols() != self.train.ncols() {
37            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.train.ncols())));
38        }
39        Ok(())
40    }
41
42    // ANCHOR: knn
43    /// The `(index, distance)` of the `k` nearest training points to `query`, nearest first.
44    pub fn neighbours(&self, query: &[f64]) -> Vec<(usize, f64)> {
45        let mut d: Vec<(usize, f64)> = self.train.rows().into_iter().enumerate().map(|(i, r)| (i, squared_distance(&r.to_vec(), query))).collect();
46        if d.is_empty() || self.k == 0 {
47            return Vec::new();
48        }
49        let k = self.k.min(d.len());
50        d.select_nth_unstable_by(k - 1, |a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
51        d.truncate(k);
52        d.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
53        d.into_iter().map(|(i, d2)| (i, d2.sqrt())).collect()
54    }
55
56    /// Class probabilities (vote shares) for each row of `x`, as a `(rows, classes)` matrix.
57    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
58        self.check_fitted(x)?;
59        let mut out = R2D::zeros((x.nrows(), self.classes));
60        for (i, row) in x.rows().into_iter().enumerate() {
61            let near = self.neighbours(&row.to_vec());
62            let exact: Vec<&(usize, f64)> = near.iter().filter(|n| n.1 == 0.0).collect();
63            let votes: Vec<(usize, f64)> = if self.distance_weighted && !exact.is_empty() {
64                exact.iter().map(|n| (n.0, 1.0)).collect()
65            } else {
66                near.iter().map(|&(j, d)| (j, if self.distance_weighted { 1.0 / d } else { 1.0 })).collect()
67            };
68            let total: f64 = votes.iter().map(|v| v.1).sum();
69            for (j, w) in votes {
70                out[[i, self.labels[j]]] += w / total;
71            }
72        }
73        Ok(out)
74    }
75    // ANCHOR_END: knn
76}
77
78impl Classifier for KNearestNeighbors {
79    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
80        check_xy(x, labels.len())?;
81        if self.k == 0 {
82            return Err(ErrorsJSL::InvalidInputRange("k must be at least 1."));
83        }
84        self.train = x.to_owned();
85        self.labels = labels.to_vec();
86        self.classes = class_count(labels);
87        Ok(())
88    }
89
90    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
91        let proba = self.predict_proba(x)?;
92        Ok(proba.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use crate::datasets::{make_blobs, make_moons};
100    use crate::metrics::accuracy;
101    use crate::preprocessing::{select_labels, select_rows, train_test_split};
102    use ndarray::arr2;
103
104    #[test]
105    fn separates_blobs_and_handles_nonlinear_moons() {
106        let (x, l) = make_moons(150, 0.15, 3);
107        let (tr, te) = train_test_split(x.nrows(), 0.3, 1).unwrap();
108        let mut m = KNearestNeighbors::new(5);
109        m.fit(select_rows(x.view(), &tr).view(), &select_labels(&l, &tr)).unwrap();
110        let acc = accuracy(&select_labels(&l, &te), &m.predict(select_rows(x.view(), &te).view()).unwrap()).unwrap();
111        assert!(acc > 0.93, "{acc}");
112        let (bx, bl) = make_blobs(30, &[vec![0.0, 0.0], vec![6.0, 6.0], vec![-6.0, 6.0]], 1.0, 2);
113        let mut b = KNearestNeighbors::new(3);
114        b.fit(bx.view(), &bl).unwrap();
115        assert_eq!(accuracy(&bl, &b.predict(bx.view()).unwrap()).unwrap(), 1.0);
116    }
117
118    #[test]
119    fn k_and_weighting_change_the_vote() {
120        // One class-1 point right next to the query, three class-0 points farther away.
121        let x = arr2(&[[0.1, 0.0], [2.0, 0.0], [2.1, 0.0], [2.2, 0.0]]);
122        let l = [1, 0, 0, 0];
123        let mut plain = KNearestNeighbors::new(4);
124        plain.fit(x.view(), &l).unwrap();
125        assert_eq!(plain.predict(arr2(&[[0.0, 0.0]]).view()).unwrap(), vec![0]);
126        let mut weighted = KNearestNeighbors::new(4).distance_weighted(true);
127        weighted.fit(x.view(), &l).unwrap();
128        assert_eq!(weighted.predict(arr2(&[[0.0, 0.0]]).view()).unwrap(), vec![1]);
129        let mut one = KNearestNeighbors::new(1);
130        one.fit(x.view(), &l).unwrap();
131        assert_eq!(one.predict(arr2(&[[0.0, 0.0]]).view()).unwrap(), vec![1]);
132        let p = plain.predict_proba(arr2(&[[0.0, 0.0]]).view()).unwrap();
133        assert_eq!((p[[0, 0]], p[[0, 1]]), (0.75, 0.25));
134        // An exact hit decides alone under distance weighting.
135        assert_eq!(weighted.predict(arr2(&[[2.0, 0.0]]).view()).unwrap(), vec![0]);
136        assert_eq!(one.neighbours(&[0.0, 0.0]).len(), 1);
137        assert_eq!(KNearestNeighbors::new(10).neighbours(&[0.0, 0.0]).len(), 0); // unfitted: no data
138    }
139
140    #[test]
141    fn errors() {
142        let x = arr2(&[[0.0], [1.0]]);
143        assert!(KNearestNeighbors::new(0).fit(x.view(), &[0, 1]).is_err());
144        assert!(KNearestNeighbors::new(1).fit(x.view(), &[0]).is_err());
145        assert!(KNearestNeighbors::new(1).predict(x.view()).is_err());
146        let mut m = KNearestNeighbors::new(5);
147        m.fit(x.view(), &[0, 1]).unwrap(); // k larger than the data is clamped
148        assert_eq!(m.predict(x.view()).unwrap().len(), 2);
149        assert!(m.predict(arr2(&[[1.0, 2.0]]).view()).is_err());
150    }
151}