Skip to main content

lib_jsl_machine_learning/unsupervised/reduction/
umap.rs

1//! UMAP: uniform manifold approximation and projection.
2//!
3//! See the book entry [Nonlinear embeddings: t-SNE and UMAP](https://jwkunz.github.io/lib_jsl/book/unsupervised/embeddings.html#umap).
4
5use crate::common::{MlRng, Transformer, check_features, pairwise_distances};
6use crate::unsupervised::reduction::principal_component_analysis::Pca;
7use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
8
9/// UMAP (McInnes, Healy and Melville) builds a weighted *fuzzy graph* of the data, in which each
10/// point is connected to its `neighbors` nearest points with membership strengths that fall off
11/// with distance (measured beyond the nearest neighbour, which locally always connects), and the
12/// directed graph is symmetrised by fuzzy union. It then finds a low-dimensional layout whose
13/// fuzzy graph is as similar as possible, by stochastic gradient descent: connected points attract
14/// each other and randomly sampled points repel. Compared with t-SNE it is faster and keeps more
15/// global structure.
16///
17/// `min_dist` sets how tightly points may pack in the embedding (small values give dense clumps),
18/// and `neighbors` trades local detail against global structure. This implementation builds the
19/// exact neighbour graph, so it suits up to several thousand points, and initialises the layout
20/// with PCA.
21#[derive(Debug, Clone)]
22pub struct Umap {
23    components: usize,
24    neighbors: usize,
25    min_dist: f64,
26    epochs: usize,
27    learning_rate: f64,
28    negative_rate: usize,
29    seed: u64,
30}
31
32/// Fits the smooth curve `1 / (1 + a x^{2b})` to the target similarity profile: 1 up to `min_dist`
33/// and an exponential decay of scale `spread` beyond it. Levenberg-Marquardt on `(a, b)`.
34pub fn fit_ab(min_dist: f64, spread: f64) -> (f64, f64) {
35    let xs: Vec<f64> = (1..=300).map(|i| 3.0 * spread * i as f64 / 300.0).collect();
36    let target: Vec<f64> = xs.iter().map(|&x| if x <= min_dist { 1.0 } else { (-(x - min_dist) / spread).exp() }).collect();
37    let model = |a: f64, b: f64, x: f64| 1.0 / (1.0 + a * x.powf(2.0 * b));
38    let cost = |a: f64, b: f64| xs.iter().zip(&target).map(|(&x, &t)| (model(a, b, x) - t).powi(2)).sum::<f64>();
39    let (mut a, mut b, mut lambda) = (1.5, 0.9, 1e-2);
40    let mut current = cost(a, b);
41    for _ in 0..200 {
42        // Normal equations with a numerical Jacobian.
43        let (mut jtj, mut jtr) = ([[0.0; 2]; 2], [0.0; 2]);
44        for (&x, &t) in xs.iter().zip(&target) {
45            let r = model(a, b, x) - t;
46            let ja = (model(a + 1e-6, b, x) - model(a, b, x)) / 1e-6;
47            let jb = (model(a, b + 1e-6, x) - model(a, b, x)) / 1e-6;
48            jtj[0][0] += ja * ja;
49            jtj[0][1] += ja * jb;
50            jtj[1][1] += jb * jb;
51            jtr[0] += ja * r;
52            jtr[1] += jb * r;
53        }
54        jtj[1][0] = jtj[0][1];
55        let mut improved = false;
56        for _ in 0..20 {
57            let (m00, m11) = (jtj[0][0] * (1.0 + lambda), jtj[1][1] * (1.0 + lambda));
58            let det = m00 * m11 - jtj[0][1] * jtj[1][0];
59            if det.abs() < 1e-300 {
60                lambda *= 10.0;
61                continue;
62            }
63            let da = -(m11 * jtr[0] - jtj[0][1] * jtr[1]) / det;
64            let db = -(-jtj[1][0] * jtr[0] + m00 * jtr[1]) / det;
65            let (na, nb) = ((a + da).max(1e-3), (b + db).max(1e-3));
66            let c = cost(na, nb);
67            if c < current {
68                (a, b, current, lambda) = (na, nb, c, (lambda * 0.5).max(1e-12));
69                improved = true;
70                break;
71            }
72            lambda *= 4.0;
73        }
74        if !improved || current < 1e-12 {
75            break;
76        }
77    }
78    (a, b)
79}
80
81impl Umap {
82    pub fn new(components: usize, neighbors: usize, min_dist: f64, seed: u64) -> Self {
83        Umap { components, neighbors, min_dist, epochs: 300, learning_rate: 1.0, negative_rate: 5, seed }
84    }
85
86    pub fn with_epochs(mut self, epochs: usize) -> Self {
87        self.epochs = epochs;
88        self
89    }
90
91    /// The symmetrised fuzzy-graph edge weights `(i, j, weight)` with `i < j`.
92    #[allow(clippy::needless_range_loop)]
93    pub fn fuzzy_graph(&self, x: VR2D) -> Result<Vec<(usize, usize, f64)>, ErrorsJSL> {
94        check_features(x)?;
95        let n = x.nrows();
96        if self.neighbors < 2 || self.neighbors >= n {
97            return Err(ErrorsJSL::InvalidInputRange("Need 2 <= neighbors < samples."));
98        }
99        let d = pairwise_distances(x);
100        let k = self.neighbors;
101        let target = (k as f64).log2();
102        let mut directed = vec![vec![0.0; n]; n];
103        for i in 0..n {
104            let mut order: Vec<usize> = (0..n).filter(|&j| j != i).collect();
105            order.sort_by(|&a, &b| d[[i, a]].total_cmp(&d[[i, b]]));
106            let nn = &order[..k];
107            let rho = nn.iter().map(|&j| d[[i, j]]).find(|&v| v > 0.0).unwrap_or(0.0);
108            // Bandwidth sigma so that the memberships sum to log2(k).
109            let (mut lo, mut hi, mut sigma) = (0.0f64, f64::INFINITY, 1.0f64);
110            for _ in 0..64 {
111                let total: f64 = nn.iter().map(|&j| (-(d[[i, j]] - rho).max(0.0) / sigma).exp()).sum();
112                if (total - target).abs() < 1e-5 {
113                    break;
114                }
115                if total > target {
116                    hi = sigma;
117                    sigma = 0.5 * (lo + hi);
118                } else {
119                    lo = sigma;
120                    sigma = if hi.is_finite() { 0.5 * (lo + hi) } else { sigma * 2.0 };
121                }
122            }
123            for &j in nn {
124                directed[i][j] = (-(d[[i, j]] - rho).max(0.0) / sigma.max(1e-12)).exp();
125            }
126        }
127        let mut edges = Vec::new();
128        for i in 0..n {
129            for j in i + 1..n {
130                let (a, b) = (directed[i][j], directed[j][i]);
131                let w = a + b - a * b; // fuzzy set union
132                if w > 0.0 {
133                    edges.push((i, j, w));
134                }
135            }
136        }
137        Ok(edges)
138    }
139
140    /// Embeds `x`, one row of coordinates per point.
141    pub fn fit_transform(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
142        let edges = self.fuzzy_graph(x)?;
143        let n = x.nrows();
144        if self.components == 0 || self.components > x.ncols() || self.min_dist.is_nan() || self.min_dist < 0.0 {
145            return Err(ErrorsJSL::InvalidInputRange("Need 1 <= components <= features and min_dist >= 0."));
146        }
147        let dims = self.components;
148        let (a, b) = fit_ab(self.min_dist, 1.0);
149        let mut rng = MlRng::new(self.seed);
150        // PCA initialisation scaled to a span of ±10, with a little jitter to break ties.
151        let mut y = Pca::new(dims).fit_transform(x)?;
152        let span = y.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(1e-12);
153        y.mapv_inplace(|v| v / span * 10.0 + rng.gaussian(0.0, 1e-4));
154        let max_w = edges.iter().map(|e| e.2).fold(0.0, f64::max);
155        let clip = |v: f64| v.clamp(-4.0, 4.0);
156        // ANCHOR: umap_sgd
157        for epoch in 0..self.epochs {
158            let alpha = self.learning_rate * (1.0 - epoch as f64 / self.epochs as f64);
159            for &(i, j, w) in &edges {
160                if rng.uniform() * max_w > w {
161                    continue; // sample edges in proportion to their weight
162                }
163                let d2: f64 = (0..dims).map(|k| (y[[i, k]] - y[[j, k]]).powi(2)).sum();
164                if d2 > 0.0 {
165                    let coeff = -2.0 * a * b * d2.powf(b - 1.0) / (1.0 + a * d2.powf(b));
166                    for k in 0..dims {
167                        let g = clip(coeff * (y[[i, k]] - y[[j, k]]));
168                        y[[i, k]] += alpha * g;
169                        y[[j, k]] -= alpha * g;
170                    }
171                }
172                for _ in 0..self.negative_rate {
173                    let r = rng.below(n);
174                    if r == i {
175                        continue;
176                    }
177                    let d2: f64 = (0..dims).map(|k| (y[[i, k]] - y[[r, k]]).powi(2)).sum();
178                    let coeff = 2.0 * b / ((0.001 + d2) * (1.0 + a * d2.powf(b)));
179                    for k in 0..dims {
180                        let g = if d2 > 0.0 { clip(coeff * (y[[i, k]] - y[[r, k]])) } else { 4.0 };
181                        y[[i, k]] += alpha * g;
182                    }
183                }
184            }
185        }
186        // ANCHOR_END: umap_sgd
187        Ok(y)
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::common::squared_distance;
195    use crate::datasets::{make_blobs, make_swiss_roll};
196
197    fn neighbour_purity(y: &R2D, labels: &[usize], k: usize) -> f64 {
198        let n = y.nrows();
199        let mut agree = 0usize;
200        for i in 0..n {
201            let mut d: Vec<(usize, f64)> = (0..n).filter(|&j| j != i).map(|j| (j, squared_distance(&y.row(i).to_vec(), &y.row(j).to_vec()))).collect();
202            d.sort_by(|a, b| a.1.total_cmp(&b.1));
203            agree += d.iter().take(k).filter(|(j, _)| labels[*j] == labels[i]).count();
204        }
205        agree as f64 / (n * k) as f64
206    }
207
208    #[test]
209    fn curve_fit_matches_the_reference_parameters() {
210        let (a, b) = fit_ab(0.1, 1.0);
211        assert!((a - 1.577).abs() < 0.1 && (b - 0.895).abs() < 0.05, "{a} {b}");
212        // A larger min_dist keeps points further apart: the fitted curve stays high for longer.
213        let (a2, _) = fit_ab(0.5, 1.0);
214        assert!(a2 < a);
215    }
216
217    #[test]
218    fn graph_weights_are_valid_fuzzy_memberships() {
219        let (x, _) = make_blobs(20, &[vec![0.0, 0.0], vec![8.0, 8.0]], 0.8, 1);
220        let g = Umap::new(2, 6, 0.1, 1).fuzzy_graph(x.view()).unwrap();
221        assert!(g.iter().all(|&(i, j, w)| i < j && w > 0.0 && w <= 1.0 + 1e-12));
222        // The two blobs are far apart, so no edge crosses between them.
223        assert!(g.iter().all(|&(i, j, _)| (i < 20) == (j < 20)));
224        assert!(g.len() >= 20 * 6 / 2); // symmetrisation never loses directed edges
225    }
226
227    #[test]
228    fn separates_clusters_and_keeps_manifold_neighbourhoods() {
229        let centres: Vec<Vec<f64>> = (0..3).map(|c| (0..8).map(|d| if d % 3 == c { 7.0 } else { 0.0 }).collect()).collect();
230        let (x, l) = make_blobs(40, &centres, 1.0, 3);
231        let y = Umap::new(2, 10, 0.1, 1).fit_transform(x.view()).unwrap();
232        assert!(neighbour_purity(&y, &l, 10) > 0.97, "{}", neighbour_purity(&y, &l, 10));
233        // Swiss roll: embedded neighbours should be close on the roll's own coordinate (angle t).
234        let (roll, t) = make_swiss_roll(250, 0.0, 2);
235        let e = Umap::new(2, 12, 0.2, 1).fit_transform(roll.view()).unwrap();
236        let mut close = 0.0;
237        for i in 0..250 {
238            let mut d: Vec<(usize, f64)> = (0..250).filter(|&j| j != i).map(|j| (j, squared_distance(&e.row(i).to_vec(), &e.row(j).to_vec()))).collect();
239            d.sort_by(|a, b| a.1.total_cmp(&b.1));
240            close += d.iter().take(5).filter(|(j, _)| (t[*j] - t[i]).abs() < 1.2).count() as f64 / 5.0;
241        }
242        assert!(close / 250.0 > 0.8, "{}", close / 250.0);
243        // Same seed, same embedding.
244        assert_eq!(Umap::new(2, 10, 0.1, 1).fit_transform(x.view()).unwrap(), y);
245    }
246
247    #[test]
248    fn errors() {
249        let (x, _) = make_blobs(10, &[vec![0.0, 0.0]], 1.0, 1);
250        assert!(Umap::new(2, 1, 0.1, 1).fit_transform(x.view()).is_err());
251        assert!(Umap::new(2, 10, 0.1, 1).fit_transform(x.view()).is_err()); // neighbors >= samples
252        assert!(Umap::new(0, 5, 0.1, 1).fit_transform(x.view()).is_err());
253        assert!(Umap::new(2, 5, -1.0, 1).fit_transform(x.view()).is_err());
254        assert!(Umap::new(1, 5, 0.1, 1).with_epochs(20).fit_transform(x.view()).is_ok());
255    }
256}