Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Nonlinear embeddings: t-SNE and UMAP

ProblemPlace high-dimensional points in two or three dimensions so that points that are neighbours stay neighbours, for visualisation
Devised byGeoffrey Hinton and Sam Roweis (2002), stochastic neighbour embedding; Laurens van der Maaten and Hinton (2008), t-SNE; Leland McInnes, John Healy and James Melville (2018), UMAP
AccuracyNonconvex objectives: local minima, and results that depend on the initialisation and parameters
CostExact t-SNE: per iteration. UMAP: for the exact neighbour graph, then per epoch
Read firstPrincipal component analysis and kernel PCA, Gradient descent and nonlinear conjugate gradients
APITsne (new(components, perplexity), with_iterations, with_learning_rate, fit_transform, kl_divergence), Umap (new(components, neighbors, min_dist, seed), with_epochs, fuzzy_graph, fit_transform), fit_ab

Overview

PCA can only rotate and flatten, so it cannot unroll a curved sheet or show clusters that are separated in ways no single plane captures. Neighbour embeddings give up on preserving distances and keep only who is near whom. They define, for every pair of points, a similarity in the original space and one in the embedding, and move the embedded points until the two agree. t-SNE matches probability distributions over neighbours. UMAP matches fuzzy neighbourhood graphs. Both produce striking pictures of clusters in data with hundreds of dimensions, such as cell types from gene expression or digits from images. They need care in reading: sizes of clusters and distances between them carry little meaning.

Where it is used

t-SNE and UMAP make high-dimensional data visible.

  • Exploring data. A two-dimensional map of thousands of cells in single-cell genomics, of images, or of word vectors shows which items are alike.
  • Checking a model. Whether a neural network’s internal representation separates the classes.
  • A caution. Distances between clusters in the picture are not reliable; the maps show neighbourhoods, not global geometry.

History

Geoffrey Hinton and Sam Roweis (2002) introduced stochastic neighbour embedding (SNE), in which each point picks neighbours with Gaussian probabilities in both spaces. It suffered from the crowding problem: a two-dimensional map has too little room for the moderately distant neighbours of high-dimensional points. Laurens van der Maaten and Hinton (2008) replaced the Gaussian in the embedding with a heavy-tailed Student t distribution, and t-SNE became the standard visualisation tool; van der Maaten (2014) made it fast with Barnes-Hut trees. Leland McInnes, John Healy and James Melville (2018) derived UMAP from a model of data on a Riemannian manifold and fuzzy topology. In practice it optimises a similar objective faster, by stochastic gradient descent with negative sampling.

The idea

t-SNE

Input similarities. For each point , define conditional probabilities of picking as a neighbour. The bandwidth is chosen by bisection so that the distribution’s perplexity , an effective number of neighbours, equals a target (typically 5 to 50). Dense regions get small , sparse ones large. Symmetrise: .

Embedded similarities. In the embedding use a Student t kernel with one degree of freedom,

whose heavy tails let moderately dissimilar points sit far apart, relieving the crowding.

Objective. Minimise the Kullback-Leibler divergence , whose gradient is

an attraction along edges with and a repulsion otherwise. KL is asymmetric: placing true neighbours far apart (large , small ) is expensive, but placing non-neighbours close is cheap. So t-SNE preserves local structure and is free with global structure.

Optimisation. Gradient descent with momentum and per-coordinate adaptive gains, starting from a tiny PCA layout. For the first quarter of the iterations (at most 250) the are multiplied by 12, which is called early exaggeration. This pulls clusters into tight groups that can move past each other before the fine structure forms.

Perplexity

Perplexity sets the neighbourhood size, and changes the picture:

These are five Gaussian clusters in 20 dimensions, all of the same size and spread, all equally far apart. With perplexity 3 each point sees only a few neighbours, and every cluster breaks into loose fragments. At 30 and 100 the clusters are compact, but their apparent sizes and the distances between them differ from panel to panel, and none of it reflects the data. Only the grouping is meaningful.

UMAP

UMAP builds a weighted graph of the data and finds a layout whose own graph matches it:

  1. Fuzzy neighbourhoods. For each point take its nearest neighbours. Let be the distance to the nearest one, and choose so that . The directed membership is : the nearest neighbour always has membership 1, which keeps every point connected.
  2. Fuzzy union. Symmetrise with the probabilistic OR, .
  3. Embedding similarity , with and fitted (by Levenberg-Marquardt, fit_ab) to a curve equal to 1 up to min_dist and decaying exponentially beyond it. For min_dist = 0.1 the reference implementation uses and , and the library’s fit agrees closely.
  4. Cross-entropy between the two graphs, minimised by stochastic gradient descent. Edges are sampled in proportion to their weight and pull their endpoints together. For each one, the first endpoint is pushed away from five random points (negative sampling), standing in for the repulsion of all non-edges.

min_dist controls how tightly points may pack:

Unrolling the Swiss roll

A Swiss roll is a rectangle rolled up in three dimensions. The coloured bands mark position along the roll, and an ideal embedding would lay them side by side in order:

PCA shows the roll as seen from its end, with neighbours across the turns overlapping. t-SNE and UMAP keep small neighbourhoods intact, but neither unrolls the sheet in one piece. Both start from the PCA layout, which is the rolled-up spiral, and both tear it into strips to relieve the strain rather than unrolling it. The reference UMAP implementation starts from a spectral embedding of the graph instead, which is already unrolled. The fraction of each point’s 10 nearest neighbours that remain among its 10 nearest in the embedding measures what is kept:

Table 12.14. Neighbourhood preservation (fraction of 10 nearest neighbours kept) and time of PCA, t-SNE and UMAP.

dataPCAt-SNEUMAPtime (PCA / t-SNE / UMAP)
Swiss roll (600 points, 3D)0.300.860.7721 µs / 1.12 s / 0.11 s
five clusters (300 points, 20D)0.250.470.3443 µs / 0.28 s / 60.8 ms

Both methods keep far more neighbourhoods than PCA on the roll. In the 20-dimensional clusters, a point’s nearest neighbours within its own cluster are nearly arbitrary (the cluster is a round Gaussian cloud), so no two-dimensional map keeps many of them; t-SNE and UMAP still keep the clusters apart. UMAP is an order of magnitude faster than exact t-SNE.

Algorithm

t-SNE.

  1. Input similarities. For each point , find by bisection the bandwidth whose conditional distribution has the target perplexity. Symmetrise to get .
  2. Initialise the embedding with the first two principal components of the data, scaled down to a small spread.
  3. Iterate. In each iteration:
    • compute all the from the current positions;
    • compute the gradient for every point (using during early exaggeration);
    • update each coordinate’s gain, a per-coordinate multiplier of the learning rate: add 0.2 to it when the gradient and the current velocity have opposite signs (the coordinate is still being pushed the way it is already moving), and multiply it by 0.8 otherwise (the push has reversed);
    • update the velocity (the previous velocity times the momentum, minus the learning rate times the gain times the gradient) and add it to the position;
    • subtract the mean position, so that the embedding stays centred.

Every iteration computes all pairs, . This is “exact” t-SNE; tree-based approximations reduce it to .

UMAP.

  1. Graph. For each point find its nearest neighbours, and, by bisection, . Form the directed memberships and combine them into the symmetric weights .
  2. Curve. Fit and to the target curve for the chosen min_dist.
  3. Initialise with the first two principal components, scaled to the range .
  4. Optimise for a fixed number of epochs, with a learning rate that decreases linearly to zero. In each epoch, visit each edge with probability . For a visited edge:
    • move and towards each other by the attractive gradient, with each component of the step clipped to a fixed range;
    • choose five other points at random and move away from each by the repulsive gradient, clipped likewise.

The cost per epoch is proportional to the number of edges, about .

Implementation

            // Student-t similarities in the embedding.
            let mut num = R2D::zeros((n, n));
            let mut total = 0.0;
            for i in 0..n {
                for j in i + 1..n {
                    let d2: f64 = (0..dims).map(|k| (y[[i, k]] - y[[j, k]]).powi(2)).sum();
                    let v = 1.0 / (1.0 + d2);
                    num[[i, j]] = v;
                    num[[j, i]] = v;
                    total += 2.0 * v;
                }
            }
            let total = total.max(1e-300);
            let mut grad = R2D::zeros((n, dims));
            for i in 0..n {
                for j in 0..n {
                    if i != j {
                        let q = (num[[i, j]] / total).max(1e-12);
                        let mult = 4.0 * (p[[i, j]] - q) * num[[i, j]];
                        for k in 0..dims {
                            grad[[i, k]] += mult * (y[[i, k]] - y[[j, k]]);
                        }
                    }
                }
            }
            let momentum = if it < exaggeration_steps { 0.5 } else { 0.8 };
            for i in 0..n {
                for k in 0..dims {
                    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);
                    velocity[[i, k]] = momentum * velocity[[i, k]] - self.learning_rate * gains[[i, k]] * grad[[i, k]];
                    y[[i, k]] += velocity[[i, k]];
                }
            }
            let mean = y.mean_axis(ndarray::Axis(0)).expect("non-empty");
            y -= &mean;
        for epoch in 0..self.epochs {
            let alpha = self.learning_rate * (1.0 - epoch as f64 / self.epochs as f64);
            for &(i, j, w) in &edges {
                if rng.uniform() * max_w > w {
                    continue; // sample edges in proportion to their weight
                }
                let d2: f64 = (0..dims).map(|k| (y[[i, k]] - y[[j, k]]).powi(2)).sum();
                if d2 > 0.0 {
                    let coeff = -2.0 * a * b * d2.powf(b - 1.0) / (1.0 + a * d2.powf(b));
                    for k in 0..dims {
                        let g = clip(coeff * (y[[i, k]] - y[[j, k]]));
                        y[[i, k]] += alpha * g;
                        y[[j, k]] -= alpha * g;
                    }
                }
                for _ in 0..self.negative_rate {
                    let r = rng.below(n);
                    if r == i {
                        continue;
                    }
                    let d2: f64 = (0..dims).map(|k| (y[[i, k]] - y[[r, k]]).powi(2)).sum();
                    let coeff = 2.0 * b / ((0.001 + d2) * (1.0 + a * d2.powf(b)));
                    for k in 0..dims {
                        let g = if d2 > 0.0 { clip(coeff * (y[[i, k]] - y[[r, k]])) } else { 4.0 };
                        y[[i, k]] += alpha * g;
                    }
                }
            }
        }
  • Both use exact neighbour computations, practical for a few thousand points. Production implementations use Barnes-Hut or FFT approximations (t-SNE) and approximate nearest-neighbour search (UMAP).
  • t-SNE is deterministic, since it starts from PCA and uses no random numbers. UMAP is reproducible for a given seed.
  • Neither provides a transform for new points: both are fitted to one data set.
  • Gradient components are clipped to ±4 in UMAP, as in the reference implementation.

In practice

//! Nonlinear embeddings: t-SNE and UMAP on clusters in 20 dimensions.

use lib_jsl_machine_learning::datasets::make_blobs;
use lib_jsl_machine_learning::unsupervised::reduction::{Tsne, Umap};

fn main() {
    let centres: Vec<Vec<f64>> = (0..5).map(|c| (0..20).map(|d| if d % 5 == c { 5.0 } else { 0.0 }).collect()).collect();
    let (x, labels) = make_blobs(40, &centres, 1.0, 4);
    let mut tsne = Tsne::new(2, 20.0).with_iterations(500);
    let yt = tsne.fit_transform(x.view()).unwrap();
    println!("t-SNE: KL divergence {:.3}", tsne.kl_divergence());
    let yu = Umap::new(2, 15, 0.1, 1).fit_transform(x.view()).unwrap();
    // The embedded centre of each cluster.
    for (name, y) in [("t-SNE", &yt), ("UMAP", &yu)] {
        let centres: Vec<String> = (0..5)
            .map(|c| {
                let idx: Vec<usize> = (0..y.nrows()).filter(|&i| labels[i] == c).collect();
                let m = |k: usize| idx.iter().map(|&i| y[[i, k]]).sum::<f64>() / idx.len() as f64;
                format!("({:.1}, {:.1})", m(0), m(1))
            })
            .collect();
        println!("{name} cluster centres: {}", centres.join(" "));
    }
}
t-SNE: KL divergence 0.335
t-SNE cluster centres: (-32.0, 1.1) (23.0, 16.6) (-11.5, -34.4) (28.7, -17.8) (-8.2, 34.6)
UMAP cluster centres: (9.2, 12.3) (-9.8, 2.0) (-1.2, 7.7) (6.4, -10.2) (-1.3, -3.1)

The five clusters are equally far apart in the data. t-SNE spreads their centres on a rough circle; UMAP’s centres lie at distances between 10 and 23 from each other. Neither arrangement means anything.

Strengths

  • Reveal cluster structure in high-dimensional data that linear projections hide.
  • UMAP is fast, keeps somewhat more global structure, and can embed into more than three dimensions as input to clustering.

Weaknesses

  • Cluster sizes, distances between clusters and densities in the picture are unreliable; results depend on perplexity or the neighbour count, and on the initialisation.
  • Nonconvex optimisation with no guarantee; no mapping for new points in these implementations.
  • The exact methods here cost memory and time.

Exercises

  1. Show that a perplexity of for a uniform distribution over neighbours corresponds to entropy bits.
  2. Derive the t-SNE gradient from the KL divergence.
  3. Show that a Gaussian kernel in two dimensions cannot place ten mutually equidistant neighbours of a point at equal distances, and explain the crowding problem.
  4. Show that the fuzzy union is the probability that at least one of two independent events with probabilities and occurs.
  5. Start t-SNE from a random layout instead of PCA (by permuting the PCA scores), and compare the KL divergence reached on the Swiss roll.
Hints and answers
  1. For a uniform distribution over neighbours bits, and perplexity is .
  2. With and , differentiate with respect to ; the normalising constant contributes terms and the result is .
  3. At most 3 points in the plane can be mutually equidistant (the corners of an equilateral triangle), so ten equidistant neighbours need 9 dimensions. When a high-dimensional neighbourhood is squeezed into 2D, the neighbours crowd and are pushed together; the heavy tails of the distribution relieve this.
  4. The union of two independent events has probability by inclusion-exclusion.
  5. Compare the final KL divergences over several seeds; initialising from PCA typically gives lower and more reproducible values and better global structure than a random start.

Further reading

  • L. van der Maaten and G. Hinton, “Visualizing data using t-SNE”, Journal of Machine Learning Research 9 (2008) 2579–2605.
  • L. McInnes, J. Healy and J. Melville, “UMAP: uniform manifold approximation and projection for dimension reduction”, arXiv:1802.03426, 2018.
  • M. Wattenberg, F. Viégas and I. Johnson, “How to use t-SNE effectively”, Distill (2016).
  • D. Kobak and G. C. Linderman, “Initialization is critical for preserving global data structure in both t-SNE and UMAP”, Nature Biotechnology 39 (2021) 156–157.