Skip to main content

lib_jsl_machine_learning/unsupervised/reduction/
t_sne.rs

1//! t-distributed stochastic neighbour embedding.
2//!
3//! See the book entry [Nonlinear embeddings: t-SNE and UMAP](https://jwkunz.github.io/lib_jsl/book/unsupervised/embeddings.html#t-sne).
4
5use crate::common::{Transformer, check_features, squared_distance};
6use crate::unsupervised::reduction::principal_component_analysis::Pca;
7use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
8
9/// Exact t-SNE (van der Maaten and Hinton): embeds high-dimensional points in 2D or 3D so that
10/// neighbours stay neighbours. Pairwise similarities in the input are Gaussian with a per-point
11/// bandwidth chosen to match a target *perplexity* (the effective number of neighbours); in the
12/// embedding they are Student-t distributed (heavy tails let dissimilar clusters separate). The
13/// embedding minimises the KL divergence between the two by gradient descent with momentum and
14/// adaptive gains, using "early exaggeration" of the input similarities at the start to form
15/// clusters.
16///
17/// The exact method costs `O(n²)` per iteration, fine for up to a few thousand points. Only the
18/// layout of the *fitted* points is produced: t-SNE has no transform for new data, and distances
19/// between clusters in the picture are not meaningful.
20#[derive(Debug, Clone)]
21pub struct Tsne {
22    components: usize,
23    perplexity: f64,
24    iterations: usize,
25    learning_rate: f64,
26    early_exaggeration: f64,
27    kl_divergence: f64,
28}
29
30impl Tsne {
31    /// `components` output dimensions (2 or 3 typical); `perplexity` roughly 5 to 50.
32    pub fn new(components: usize, perplexity: f64) -> Self {
33        Tsne { components, perplexity, iterations: 750, learning_rate: 200.0, early_exaggeration: 12.0, kl_divergence: f64::NAN }
34    }
35
36    pub fn with_iterations(mut self, iterations: usize) -> Self {
37        self.iterations = iterations;
38        self
39    }
40
41    pub fn with_learning_rate(mut self, learning_rate: f64) -> Self {
42        self.learning_rate = learning_rate;
43        self
44    }
45
46    /// The KL divergence of the final embedding (lower is a better match to the input).
47    pub fn kl_divergence(&self) -> f64 {
48        self.kl_divergence
49    }
50
51    /// Joint input probabilities `P` (symmetrised, summing to one).
52    fn input_affinities(&self, x: VR2D) -> R2D {
53        let n = x.nrows();
54        let rows: Vec<Vec<f64>> = x.rows().into_iter().map(|r| r.to_vec()).collect();
55        let d2 = R2D::from_shape_fn((n, n), |(i, j)| squared_distance(&rows[i], &rows[j]));
56        let target = self.perplexity.ln();
57        let mut p = R2D::zeros((n, n));
58        for i in 0..n {
59            // Binary search for the precision beta = 1/(2σ²) that yields the target entropy.
60            let (mut lo, mut hi, mut beta) = (0.0f64, f64::INFINITY, 1.0f64);
61            let mut row = vec![0.0; n];
62            for _ in 0..60 {
63                let mut sum = 0.0;
64                for j in 0..n {
65                    row[j] = if j == i { 0.0 } else { (-beta * d2[[i, j]]).exp() };
66                    sum += row[j];
67                }
68                let sum = sum.max(1e-300);
69                let entropy = sum.ln() + beta * (0..n).map(|j| d2[[i, j]] * row[j]).sum::<f64>() / sum;
70                if (entropy - target).abs() < 1e-5 {
71                    break;
72                }
73                if entropy > target {
74                    lo = beta;
75                    beta = if hi.is_finite() { 0.5 * (beta + hi) } else { beta * 2.0 };
76                } else {
77                    hi = beta;
78                    beta = 0.5 * (beta + lo);
79                }
80            }
81            let sum: f64 = row.iter().sum::<f64>().max(1e-300);
82            for j in 0..n {
83                p[[i, j]] = row[j] / sum;
84            }
85        }
86        R2D::from_shape_fn((n, n), |(i, j)| ((p[[i, j]] + p[[j, i]]) / (2.0 * n as f64)).max(1e-12))
87    }
88
89    /// Embeds `x`, returning one row of coordinates per point.
90    pub fn fit_transform(&mut self, x: VR2D) -> Result<R2D, ErrorsJSL> {
91        check_features(x)?;
92        let n = x.nrows();
93        if n < 4 || self.components == 0 || self.components > x.ncols() || self.perplexity.is_nan() || self.perplexity < 1.0 || self.perplexity >= (n - 1) as f64 {
94            return Err(ErrorsJSL::InvalidInputRange("Need at least 4 samples, 1 <= components <= features and 1 <= perplexity < samples."));
95        }
96        let dims = self.components;
97        let mut p = self.input_affinities(x);
98        // PCA initialisation (rescaled to a tiny spread) is deterministic and keeps global structure.
99        let mut y = Pca::new(dims).fit_transform(x)?;
100        let spread = y.column(0).iter().map(|v| v * v).sum::<f64>().sqrt() / (n as f64).sqrt();
101        y.mapv_inplace(|v| v / spread.max(1e-12) * 1e-4);
102        let mut velocity = R2D::zeros((n, dims));
103        let mut gains = R2D::ones((n, dims));
104        let exaggeration_steps = (self.iterations / 4).min(250);
105        p *= self.early_exaggeration;
106        for it in 0..self.iterations {
107            if it == exaggeration_steps {
108                p /= self.early_exaggeration;
109            }
110            // ANCHOR: tsne_gradient
111            // Student-t similarities in the embedding.
112            let mut num = R2D::zeros((n, n));
113            let mut total = 0.0;
114            for i in 0..n {
115                for j in i + 1..n {
116                    let d2: f64 = (0..dims).map(|k| (y[[i, k]] - y[[j, k]]).powi(2)).sum();
117                    let v = 1.0 / (1.0 + d2);
118                    num[[i, j]] = v;
119                    num[[j, i]] = v;
120                    total += 2.0 * v;
121                }
122            }
123            let total = total.max(1e-300);
124            let mut grad = R2D::zeros((n, dims));
125            for i in 0..n {
126                for j in 0..n {
127                    if i != j {
128                        let q = (num[[i, j]] / total).max(1e-12);
129                        let mult = 4.0 * (p[[i, j]] - q) * num[[i, j]];
130                        for k in 0..dims {
131                            grad[[i, k]] += mult * (y[[i, k]] - y[[j, k]]);
132                        }
133                    }
134                }
135            }
136            let momentum = if it < exaggeration_steps { 0.5 } else { 0.8 };
137            for i in 0..n {
138                for k in 0..dims {
139                    gains[[i, k]] = if (grad[[i, k]] > 0.0) != (velocity[[i, k]] > 0.0) { gains[[i, k]] + 0.2 } else { gains[[i, k]] * 0.8 }.max(0.01);
140                    velocity[[i, k]] = momentum * velocity[[i, k]] - self.learning_rate * gains[[i, k]] * grad[[i, k]];
141                    y[[i, k]] += velocity[[i, k]];
142                }
143            }
144            let mean = y.mean_axis(ndarray::Axis(0)).expect("non-empty");
145            y -= &mean;
146            // ANCHOR_END: tsne_gradient
147        }
148        // Final KL divergence against the un-exaggerated P.
149        if self.iterations <= exaggeration_steps {
150            p /= self.early_exaggeration;
151        }
152        let mut total = 0.0;
153        let mut num = R2D::zeros((n, n));
154        for i in 0..n {
155            for j in i + 1..n {
156                let v = 1.0 / (1.0 + (0..dims).map(|k| (y[[i, k]] - y[[j, k]]).powi(2)).sum::<f64>());
157                num[[i, j]] = v;
158                num[[j, i]] = v;
159                total += 2.0 * v;
160            }
161        }
162        self.kl_divergence = (0..n).flat_map(|i| (0..n).map(move |j| (i, j))).filter(|(i, j)| i != j).map(|(i, j)| p[[i, j]] * (p[[i, j]] / (num[[i, j]] / total).max(1e-12)).ln()).sum();
163        Ok(y)
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::datasets::make_blobs;
171
172    /// Fraction of points whose nearest embedded neighbours share their label.
173    fn neighbour_purity(y: &R2D, labels: &[usize], k: usize) -> f64 {
174        let n = y.nrows();
175        let mut agree = 0usize;
176        for i in 0..n {
177            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();
178            d.sort_by(|a, b| a.1.total_cmp(&b.1));
179            agree += d.iter().take(k).filter(|(j, _)| labels[*j] == labels[i]).count();
180        }
181        agree as f64 / (n * k) as f64
182    }
183
184    #[test]
185    fn separates_clusters_from_ten_dimensions_down_to_two() {
186        let centres: Vec<Vec<f64>> = (0..3).map(|c| (0..10).map(|d| if d % 3 == c { 6.0 } else { 0.0 }).collect()).collect();
187        let (x, l) = make_blobs(25, &centres, 1.0, 5);
188        let mut t = Tsne::new(2, 12.0).with_iterations(300);
189        let y = t.fit_transform(x.view()).unwrap();
190        assert_eq!(y.dim(), (75, 2));
191        assert!(neighbour_purity(&y, &l, 10) > 0.97, "{}", neighbour_purity(&y, &l, 10));
192        assert!(t.kl_divergence().is_finite() && t.kl_divergence() > 0.0 && t.kl_divergence() < 1.0, "{}", t.kl_divergence());
193    }
194
195    #[test]
196    fn more_iterations_lower_the_divergence_and_runs_are_reproducible() {
197        let (x, _) = make_blobs(15, &[vec![0.0, 0.0, 0.0], vec![5.0, 5.0, 0.0], vec![0.0, 5.0, 5.0]], 0.7, 2);
198        let kl = |iters: usize| {
199            let mut t = Tsne::new(2, 10.0).with_iterations(iters);
200            let y = t.fit_transform(x.view()).unwrap();
201            (t.kl_divergence(), y)
202        };
203        let (short, y1) = kl(80);
204        let (long, y2) = kl(400);
205        assert!(long < short, "{long} vs {short}");
206        assert_eq!(kl(80).1, y1); // deterministic: no random numbers are used
207        assert_ne!(y1, y2);
208        // The embedding is centred.
209        assert!(y2.mean_axis(ndarray::Axis(0)).unwrap().iter().all(|m| m.abs() < 1e-9));
210    }
211
212    #[test]
213    fn errors() {
214        let (x, _) = make_blobs(10, &[vec![0.0, 0.0]], 1.0, 1);
215        assert!(Tsne::new(2, 30.0).fit_transform(x.view()).is_err()); // perplexity >= samples
216        assert!(Tsne::new(0, 5.0).fit_transform(x.view()).is_err());
217        assert!(Tsne::new(3, 5.0).fit_transform(x.view()).is_err()); // more output dims than input
218        assert!(Tsne::new(2, 0.5).fit_transform(x.view()).is_err());
219        assert!(Tsne::new(1, 3.0).with_iterations(20).fit_transform(x.view()).is_ok());
220    }
221}