Skip to main content

lib_jsl_machine_learning/unsupervised/clustering/
k_medoids.rs

1//! k-medoids clustering (Partitioning Around Medoids).
2//!
3//! See the book entry [k-means and k-medoids](https://jwkunz.github.io/lib_jsl/book/unsupervised/k-means.html#k-medoids).
4
5use crate::common::{Clusterer, check_features, squared_distance};
6use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
7
8/// PAM: like k-means, but each cluster is represented by an actual data point (its medoid)
9/// instead of a mean, and the objective is the total *distance* (not squared), which makes the
10/// result robust to outliers and lets any dissimilarity be used (see [`KMedoids::fit_distances`]).
11/// A greedy BUILD phase picks the initial medoids, then SWAP repeatedly exchanges a medoid for a
12/// non-medoid whenever that lowers the total cost.
13#[derive(Debug, Clone)]
14pub struct KMedoids {
15    k: usize,
16    max_iterations: usize,
17    medoids: Vec<usize>,
18    cost: f64,
19    labels: Vec<usize>,
20}
21
22impl KMedoids {
23    pub fn new(k: usize) -> Self {
24        KMedoids { k, max_iterations: 100, medoids: Vec::new(), cost: f64::NAN, labels: Vec::new() }
25    }
26
27    /// Indices (into the training data) of the chosen medoids, one per cluster.
28    pub fn medoids(&self) -> &[usize] {
29        &self.medoids
30    }
31
32    /// The total distance from every point to its medoid.
33    pub fn cost(&self) -> f64 {
34        self.cost
35    }
36
37    /// Clusters from a precomputed symmetric dissimilarity matrix; returns cluster labels.
38    pub fn fit_distances(&mut self, d: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
39        let n = d.nrows();
40        if d.ncols() != n || n == 0 || self.k == 0 || self.k > n {
41            return Err(ErrorsJSL::InvalidInputRange("Need a square distance matrix and 1 <= k <= n."));
42        }
43        if d.iter().any(|v| !v.is_finite() || *v < 0.0) {
44            return Err(ErrorsJSL::InvalidInputRange("Distances must be finite and non-negative."));
45        }
46        // ANCHOR: pam
47        // BUILD: first the point with the smallest total distance, then greedily the point that
48        // most reduces the total cost.
49        let mut medoids = vec![(0..n).min_by(|&a, &b| d.row(a).sum().total_cmp(&d.row(b).sum())).expect("n > 0")];
50        let mut nearest: Vec<f64> = (0..n).map(|i| d[[i, medoids[0]]]).collect();
51        while medoids.len() < self.k {
52            let gain = |c: usize| (0..n).map(|i| (nearest[i] - d[[i, c]]).max(0.0)).sum::<f64>();
53            let c = (0..n).filter(|c| !medoids.contains(c)).max_by(|&a, &b| gain(a).total_cmp(&gain(b))).expect("k <= n");
54            medoids.push(c);
55            for i in 0..n {
56                nearest[i] = nearest[i].min(d[[i, c]]);
57            }
58        }
59        let total = |m: &[usize]| (0..n).map(|i| m.iter().map(|&c| d[[i, c]]).fold(f64::INFINITY, f64::min)).sum::<f64>();
60        let mut cost = total(&medoids);
61        // SWAP until no exchange improves the cost.
62        for _ in 0..self.max_iterations {
63            let mut best = (cost, None);
64            for slot in 0..self.k {
65                for candidate in (0..n).filter(|c| !medoids.contains(c)) {
66                    let mut trial = medoids.clone();
67                    trial[slot] = candidate;
68                    let c = total(&trial);
69                    if c < best.0 - 1e-12 {
70                        best = (c, Some((slot, candidate)));
71                    }
72                }
73            }
74            match best.1 {
75                Some((slot, candidate)) => {
76                    medoids[slot] = candidate;
77                    cost = best.0;
78                }
79                None => break,
80            }
81        }
82        // ANCHOR_END: pam
83        self.labels = (0..n).map(|i| (0..self.k).min_by(|&a, &b| d[[i, medoids[a]]].total_cmp(&d[[i, medoids[b]]])).expect("k > 0")).collect();
84        self.medoids = medoids;
85        self.cost = cost;
86        Ok(self.labels.clone())
87    }
88}
89
90impl Clusterer for KMedoids {
91    fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL> {
92        check_features(x)?;
93        let rows: Vec<Vec<f64>> = x.rows().into_iter().map(|r| r.to_vec()).collect();
94        let d = R2D::from_shape_fn((rows.len(), rows.len()), |(i, j)| squared_distance(&rows[i], &rows[j]).sqrt());
95        Ok(self.fit_distances(d.view())?.into_iter().map(Some).collect())
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate::datasets::make_blobs;
103    use crate::metrics::adjusted_rand_index;
104    use ndarray::{Axis, arr2, concatenate};
105
106    #[test]
107    fn recovers_blobs_and_returns_real_data_points_as_medoids() {
108        let (x, l) = make_blobs(30, &[vec![0.0, 0.0], vec![7.0, 0.0], vec![3.0, 6.0]], 0.7, 2);
109        let mut km = KMedoids::new(3);
110        let got = km.fit_predict(x.view()).unwrap();
111        let truth: Vec<Option<usize>> = l.iter().map(|&c| Some(c)).collect();
112        assert!((adjusted_rand_index(&got, &truth).unwrap() - 1.0).abs() < 1e-12);
113        assert_eq!(km.medoids().len(), 3);
114        assert!(km.medoids().iter().all(|&m| m < x.nrows()));
115        assert!(km.cost() > 0.0);
116    }
117
118    #[test]
119    fn robust_to_an_outlier_where_means_are_pulled() {
120        let (cluster, _) = make_blobs(40, &[vec![0.0, 0.0]], 0.5, 1);
121        let far = arr2(&[[100.0, 100.0]]);
122        let x = concatenate(Axis(0), &[cluster.view(), far.view()]).unwrap();
123        let mut km = KMedoids::new(1);
124        km.fit_predict(x.view()).unwrap();
125        let m = km.medoids()[0];
126        assert!(x[[m, 0]].abs() < 1.0, "medoid should stay in the cluster, got {:?}", x.row(m));
127        // The mean of all points is dragged far from the cluster.
128        assert!(x.column(0).sum() / 41.0 > 2.0);
129    }
130
131    #[test]
132    fn works_with_a_custom_dissimilarity_and_validates() {
133        // Two groups defined purely by a distance matrix (no coordinates).
134        let mut d = R2D::from_elem((6, 6), 10.0);
135        for i in 0..6 {
136            d[[i, i]] = 0.0;
137        }
138        for g in [0, 3] {
139            for i in g..g + 3 {
140                for j in g..g + 3 {
141                    if i != j {
142                        d[[i, j]] = 1.0;
143                    }
144                }
145            }
146        }
147        let labels = KMedoids::new(2).fit_distances(d.view()).unwrap();
148        assert_eq!(labels[0], labels[2]);
149        assert_eq!(labels[3], labels[5]);
150        assert_ne!(labels[0], labels[3]);
151        assert!(KMedoids::new(0).fit_distances(d.view()).is_err());
152        assert!(KMedoids::new(7).fit_distances(d.view()).is_err());
153        assert!(KMedoids::new(2).fit_distances(arr2(&[[0.0, -1.0], [-1.0, 0.0]]).view()).is_err());
154        assert!(KMedoids::new(2).fit_distances(R2D::zeros((2, 3)).view()).is_err());
155    }
156}