Velamuvi AIAcademy

Lesson 5 of 8 · Techniques

t-SNE and UMAP

See how t-SNE and UMAP draw high-dimensional data as 2-D maps: perplexity, random_state, reading the picture safely, and when PCA is the better choice.

  • 19 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain how t-SNE draws high-dimensional data as a 2-D map that keeps neighbours close
  • Run TSNE in scikit-learn and choose perplexity and random_state
  • Read a t-SNE map safely, knowing that group sizes and gaps mean little
  • Speed t-SNE up with PCA first, and know when UMAP or PCA is the better tool
  • Explain why t-SNE coordinates must never be used as model features

The idea in plain words

In Principal Component Analysis you squeezed many features into a few by finding the directions in which the data varies most. PCA is fast and its axes mean something, but it can only rotate and flatten. If the groups in your data need more than two straight directions to tell apart, a 2-D PCA picture piles them on top of each other.

t-SNE has a different goal. It doesn't try to keep every distance. It only tries to keep neighbours: points that are close together in the data should be close together on the map. Points that are far apart just need to end up somewhere else.

It works in three steps:

1. In the data, turn the distances from each point to all the others into
   "neighbour chances": close points get a high chance, far points almost none.
2. Place the points on a 2-D map (at random, or from a PCA picture) and
   measure the same chances there.
3. Move the points a little at a time, so that the chances on the map match
   the chances in the data: pull together points that should be neighbours,
   push the others apart. Repeat about 1,000 times.

The "t" is the curve used for the chances on the map, Student's t-distribution. Its heavy tails let points that are only moderately far apart in the data sit far apart on the map, which opens up clear gaps between groups. That makes the pictures easy to read, and, as you'll see, it also makes those gaps unreliable as measurements.

Show it: 500 handwritten digits on a map

scikit-learn includes 1,797 small images of handwritten digits, each 8 × 8 = 64 pixels, so every image is a point in 64 dimensions. The program draws 500 of them as a t-SNE map, printed as text: each image appears as the digit it shows. Then it scores the map: for every image, it takes the 10 nearest neighbours on the map and counts how many show the same digit, and it does the same for a 2-D PCA map.

Try it yourselfPython
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.neighbors import NearestNeighbors

X, y = load_digits(return_X_y=True)     # 1,797 images of handwritten digits, 8 x 8 = 64 pixels each
X, y = X[:500], y[:500]                 # a small subset keeps t-SNE fast
tsne_map = TSNE(n_components=2, perplexity=30, random_state=0).fit_transform(X)
print("data:", X.shape, " map:", tsne_map.shape)

# Draw the map as text: each image is printed as the digit it shows
cols, rows = 60, 20
low, high = tsne_map.min(axis=0), tsne_map.max(axis=0)
grid = [[" "] * cols for _ in range(rows)]
for (a, b), digit in zip(tsne_map, y):
    col = int((a - low[0]) / (high[0] - low[0]) * (cols - 1))
    row = int((b - low[1]) / (high[1] - low[1]) * (rows - 1))
    grid[rows - 1 - row][col] = str(digit)
print("\n".join("".join(line).rstrip() for line in grid))

# Score a map: the share of each image's 10 nearest neighbours that show the same digit
def neighbour_score(points, k=10):
    _, idx = NearestNeighbors(n_neighbors=k + 1).fit(points).kneighbors(points)
    return (y[idx[:, 1:]] == y[:, None]).mean()          # column 0 is the image itself

pca_map = PCA(n_components=2).fit_transform(X)
print(f"same digit among 10 nearest neighbours: 64 pixels {neighbour_score(X):.2f}, "
      f"PCA map {neighbour_score(pca_map):.2f}, t-SNE map {neighbour_score(tsne_map):.2f}")
Output
data: (500, 64)  map: (500, 2)
                         4
                      4444444
             11111   4444  44
             11111   44444               66
              11111   44            66666666
                  11                 6666666
                2  1111                 666
                22   111
  7777          2    888888
7777777   7         888888888                         00 0
777777  77779         8 8888                          00000
         999              8888                       0000000
                5555                                 000000
                55555555  55    9
                   5 555555  99999 9
     2 22 2             555   999999
    22222222                 33 9999
      2 2222                3333 9
                      3 33333 33
                      333333
same digit among 10 nearest neighbours: 64 pixels 0.94, PCA map 0.62, t-SNE map 0.97

From pixels alone, images of the same digit end up in tight groups, and the ten digits sit clearly apart. t-SNE never saw the labels; they are only there so you can judge the picture. The map also shows detail: some digits form two islands (two ways of writing a 2, for example), and a few images sit next to another digit's group, like the 9s beside the 7s. Those are worth a look: an unusual handwriting style, or perhaps a wrong label.

The scores say the same. In the original 64 pixels, 94% of each image's nearest neighbours show the same digit. The 2-D PCA map keeps only 62%, because two straight directions can't separate ten digits. The t-SNE map scores 97%, even higher than the pixels, because it pulls each group together and pushes the groups apart. This is what t-SNE is good at: local structure, meaning who is near whom.

t-SNE's results can change a little between versions of scikit-learn, so your map may be rotated, mirrored or arranged differently, and some numbers in this lesson may differ slightly. The groups are what matter.

Perplexity and random_state

A small perplexity makes each point care only about its closest few neighbours, so the map shows fine detail but may break real groups into fragments. A large one makes each point consider many neighbours, which keeps more of the overall shape but can blur small groups, and it runs slower. Perplexity must be smaller than the number of points, or TSNE stops with a ValueError, so use 5 to 10 on small datasets. There is no single right value: try a few, such as 5, 30 and 50, and trust the structure that appears in all of them.

t-SNE also involves chance. It improves a starting layout step by step, and different starts can end in different maps that are equally good: groups in other places, rotated or mirrored. With init="random" the start is random, and random_state decides it:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE

X = load_digits().data[:300]
# init="random" starts from random positions, so random_state decides the start
a = TSNE(init="random", random_state=0).fit_transform(X)
b = TSNE(init="random", random_state=0).fit_transform(X)
c = TSNE(init="random", random_state=1).fit_transform(X)
print("same random_state, same map:     ", np.allclose(a, b))
print("different random_state, same map:", np.allclose(a, c))
Output
same random_state, same map:      True
different random_state, same map: False

Fixing random_state gives the same map every time, on the same version of scikit-learn; another seed gives another arrangement. Since scikit-learn 1.2 the default is init="pca", which starts every run from the PCA picture, so different seeds give much more similar maps. Keep that default, set random_state so others can reproduce your picture, and never read meaning into where a group happens to land.

Why sizes and gaps in the picture mean little

The next program builds data whose answer is known: three groups of 100 points in 10 dimensions. Group B is five times as spread out as A and C, and C is five times as far from A as B is. It measures each group's size (the average distance of its points from its centre) and compares two gaps (distances between group centres), in the data and on t-SNE maps made with three perplexities:

Try it yourselfPython
import numpy as np
from sklearn.manifold import TSNE

rng = np.random.RandomState(0)
# Three groups of 100 points in 10-D: A and C are tight, B is 5 times more spread out.
# B's centre is 20 away from A's, and C's centre is 100 away from A's.
X = np.vstack([rng.randn(100, 10), rng.randn(100, 10) * 5, rng.randn(100, 10)])
X[100:200, 0] += 20
X[200:, 0] += 100
group = np.repeat(["A", "B", "C"], 100)

def describe(name, points):
    centre = {g: points[group == g].mean(axis=0) for g in "ABC"}
    sizes = [np.linalg.norm(points[group == g] - centre[g], axis=1).mean() for g in "ABC"]
    ratio = np.linalg.norm(centre["C"] - centre["A"]) / np.linalg.norm(centre["B"] - centre["A"])
    print(f"{name:<16}{sizes[0]:7.1f}{sizes[1]:8.1f}{sizes[2]:8.1f}{ratio:10.1f}")

print(f"{'':<16} size A  size B  size C  gap A-C / gap A-B")
describe("in the data", X)
for perplexity in [5, 30, 100]:
    describe(f"perplexity {perplexity}", TSNE(perplexity=perplexity, random_state=0).fit_transform(X))
Output
                 size A  size B  size C  gap A-C / gap A-B
in the data         3.0    14.9     2.9       5.0
perplexity 5       12.7    12.8    12.9       1.1
perplexity 30       3.2     3.4     3.2       1.9
perplexity 100      0.3     0.7     0.3       8.2
  • Sizes are not real. B is five times as wide as A and C in the data, yet on the maps it comes out about the same size as the others at perplexity 5 and 30, and only about twice as wide at perplexity 100. t-SNE adapts each point's neighbourhood to how crowded its region is, so a spread-out group is drawn as compactly as a tight one.
  • Gaps are not real either. In the data, C is 5 times as far from A as B is. The maps say 1.1, 1.9 or 8.2, depending only on the perplexity. Even the scale is arbitrary: the same groups measure about 13 units at perplexity 5 and less than 1 at perplexity 100.

So read a t-SNE map for one thing: which points are neighbours, and which form groups. To compare sizes or distances, go back to the original data.

t-SNE is slow on large data: PCA first

t-SNE compares points in pairs, and the number of pairs grows much faster than the number of points: 500 points make 124,750 pairs, and a million points make almost 500 billion. scikit-learn's TSNE uses the Barnes-Hut approximation, which treats distant groups of points as one instead of comparing every pair, but it still makes about 1,000 passes over all the points, so hundreds of thousands of points can take a very long time. Two habits help:

  1. Subsample for a first look: a few thousand random points usually show the main groups.
  2. Reduce with PCA first. When the data has many features, such as images with thousands of pixels or text embeddings with hundreds of numbers, PCA down to about 50 dimensions removes noise and makes the neighbour search much faster. scikit-learn's documentation recommends this too.
Try it yourselfPython
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.neighbors import NearestNeighbors

X, y = load_digits(return_X_y=True)
X, y = X[:500], y[:500]

pca = PCA(n_components=20, random_state=0).fit(X)       # step 1: 64 pixels -> 20 numbers
X_small = pca.transform(X)
tsne_map = TSNE(perplexity=30, random_state=0).fit_transform(X_small)   # step 2: draw them
print(f"PCA keeps {pca.explained_variance_ratio_.sum():.0%} of the variation with {X_small.shape[1]} numbers")

_, idx = NearestNeighbors(n_neighbors=11).fit(tsne_map).kneighbors(tsne_map)
print(f"same digit among 10 nearest neighbours on the map: {(y[idx[:, 1:]] == y[:, None]).mean():.2f}")
Output
PCA keeps 92% of the variation with 20 numbers
same digit among 10 nearest neighbours on the map: 0.97

Twenty numbers keep 92% of the variation, and the map is as good as the one drawn from all 64 pixels (0.97 both times). With 64 features the time saved is small; with thousands of features it is large.

t-SNE output is for looking, not for models

PCA learns a rule that it can apply to new points with transform. t-SNE only places the points it was given:

Try it yourselfPython
import numpy as np
from sklearn.manifold import TSNE

X = np.random.RandomState(0).randn(100, 5)       # 100 points with 5 features
tsne = TSNE(perplexity=20, random_state=0).fit(X)
print("map of the fitted points:", tsne.embedding_.shape)
print("can place new points:", hasattr(tsne, "transform"))
Output
map of the fitted points: (100, 2)
can place new points: False

To place new customers or images, you would have to run t-SNE again on everything, which redraws the whole map, and the coordinates also change with the seed, the perplexity and the library version. A model trained on them can't be used later. Draw maps with t-SNE; train models on the original features or on PCA.

UMAP: a faster cousin

UMAP (Uniform Manifold Approximation and Projection) follows the same idea: find each point's nearest neighbours in the data, then lay them out in 2-D so that neighbours stay close. It is usually much faster than t-SNE, handles millions of points, often keeps more of the overall layout, and it can place new points on an existing map. UMAP lives in its own package, umap-learn, not in scikit-learn. It isn't available in this site's browser or in the course's checks, so the code below is shown but not run. To try it on your own computer, install it with pip install umap-learn.

# Not run here: needs the umap-learn package (pip install umap-learn)
import umap
from sklearn.datasets import load_digits

X, y = load_digits(return_X_y=True)                      # all 1,797 images: UMAP is fast
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42)
digits_map = reducer.fit_transform(X)                    # shape (1797, 2)
new_map = reducer.transform(X[:5])                       # unlike t-SNE, UMAP can place new points
  • n_neighbors (default 15), the first of its two main settings, plays the role of perplexity. Small values, such as 5, show fine local detail and may split groups; large values, such as 50 to 200, show more of the overall shape.
  • min_dist (default 0.1) sets how close points may sit on the map. Near 0 gives dense clumps, which helps if you plan to cluster the map; larger values, such as 0.5, spread the points out and show the overall shape more evenly.

The warnings from this lesson still apply: UMAP's group sizes and gaps aren't measurements either. Setting random_state makes it repeatable, but it then runs on a single processor core, so it is slower.

When to use which

PCAt-SNEUMAP
KeepsThe main directions of variationClose neighboursClose neighbours, often more of the overall layout
SpeedVery fastSlow on large dataFast, even on millions of points
New pointstransformNot possibletransform
Packagescikit-learnscikit-learnumap-learn
Best forA first look, compressing features, a step before modelling2-D pictures of up to tens of thousands of pointsPictures of large data, a step before clustering

A good routine: start with PCA, which is fast and whose axes mean something. If the PCA picture is a blur, draw a t-SNE or UMAP map to see whether groups exist, then check those groups in the original data.

Common mistakes

Practice

Practice exercise

A good map keeps neighbours together. Finish nearest() so it returns, for each point, the index of its nearest other point. Then count how many points have the same nearest neighbour in the data and on each map.

Your solutionPython
import numpy as np

# 6 points in 3-D, and two 2-D maps of them (row i is the same point everywhere)
data = np.array([[0, 0, 0], [1, 0, 0], [10, 0, 0], [10, 1, 0], [0, 10, 5], [0, 11, 5]])
map_a = np.array([[0, 0], [0.5, 0], [5, 5], [5, 5.5], [-5, 5], [-5, 4.4]])
map_b = np.array([[0, 0], [5, 5], [0.5, 0], [5, 5.6], [-5, 5], [-5, 4.4]])

def nearest(points):
    # Return an array with, for each point, the index of its nearest OTHER point
    return np.zeros(len(points), dtype=int)

for name, points in [("map_a", map_a), ("map_b", map_b)]:
    kept = 0   # how many points have the same nearest neighbour in data and on this map?
    print(f"{name} keeps {kept} of {len(data)} nearest neighbours")
Knowledge check

A t-SNE map shows group A twice as wide as group B, and group C far away from both. What can you safely conclude?

Summary

  • t-SNE draws high-dimensional data as a 2-D map that keeps neighbours close. It shows groups far better than a 2-D PCA picture, but only its local structure is reliable.
  • Perplexity (default 30, usually 5 to 50) sets how many neighbours count. Set random_state to reproduce a map, and trust structure that survives a few settings.
  • Group sizes and gaps on a t-SNE map mean little; check them in the original data.
  • t-SNE is slow on big data: subsample, reduce with PCA first, or use UMAP (umap-learn, with n_neighbors and min_dist), which is faster and can place new points.
  • Use t-SNE maps for looking, never as model features.

Next: Anomaly Detection.

Finished reading? Tick it off to track your progress.