You cannot plot data with 64 columns. t-SNE squeezes it onto a flat 2-D map while trying to keep close neighbours close. It is one of the best tools for seeing whether your data has natural groups. In this lesson you will map handwritten digits with t-SNE, compare it with PCA, tune perplexity, and learn which parts of a t-SNE picture you can trust.
In this lesson you will learn
- What t-SNE does and how it differs from PCA
- How to run
TSNEfrom scikit-learn - What perplexity controls and how to choose it
- How to measure map quality with trustworthiness
- What a t-SNE map can and cannot tell you
You should know PCA and k-nearest neighbours.
How t-SNE Works
t-SNE stands for t-distributed Stochastic Neighbour Embedding. The steps, in plain words:
- For every point, work out which other points are its close neighbours in the original space. Turn those distances into “how likely is this point to pick that one as a neighbour”.
- Scatter all points randomly (or by PCA) on a 2-D sheet.
- Move the points, step by step, until the neighbour chances on the sheet match the original ones as closely as possible.
PCA looks for the straight directions with the most spread. It keeps the big shape of the data but often piles small groups on top of each other. t-SNE does not care about straight directions. It cares about who sits next to whom, so groups pull apart into clear islands.
Mapping Handwritten Digits
Each digit picture is 8 × 8 pixels, so each row has 64 numbers. We take the first 800 pictures and squeeze them to 2-D with PCA and with t-SNE. To score each map, we check how often a point’s nearest neighbour on the map shows the same digit.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
# 8x8 pictures of handwritten digits: 64 numbers per picture
X, y = load_digits(return_X_y=True)
X, y = X[:800], y[:800]
print("original shape:", X.shape)
pca_2d = PCA(n_components=2).fit_transform(X)
tsne_2d = TSNE(n_components=2, perplexity=30, random_state=0).fit_transform(X)
print("t-SNE shape :", tsne_2d.shape)
# How often does a point's nearest 2-D neighbour have the same digit?
knn = KNeighborsClassifier(n_neighbors=1)
for name, Z in [("PCA ", pca_2d), ("t-SNE", tsne_2d)]:
acc = cross_val_score(knn, Z, y, cv=5).mean()
print(f"{name} 2-D map: nearest neighbour has same digit {acc:.0%} of the time")
Output
original shape: (800, 64)
t-SNE shape : (800, 2)
PCA 2-D map: nearest neighbour has same digit 52% of the time
t-SNE 2-D map: nearest neighbour has same digit 96% of the time
fit_transformreturns one 2-D point per picture. Unlike PCA, t-SNE has notransformfor new rows. It only maps the data it was given.- On the PCA map, a point’s nearest neighbour is the same digit only 52% of the time. The digits overlap heavily.
- On the t-SNE map it is 96%. As the figure shows, most digits form their own island. A few, such as 1, split into two or three small islands, perhaps because people write them in different styles.
- t-SNE never saw the labels. The groups appear only because pictures of the same digit look alike.
Perplexity and Trustworthiness
Perplexity is roughly the number of neighbours each point pays attention to. Small values focus on very local detail; large values look at bigger groups. The usual range is 5 to 50, and the default is 30. We measure each map with trustworthiness, which checks that points close on the map were really close in 64-D. A score of 1.0 is perfect.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
X, _ = load_digits(return_X_y=True)
X = X[:800]
# Trustworthiness: 1.0 means points that are close in 2-D
# were also close in the original 64 dimensions.
for perplexity in (2, 30, 100):
Z = TSNE(perplexity=perplexity, random_state=0).fit_transform(X)
t = trustworthiness(X, Z, n_neighbors=10)
print(f"perplexity {perplexity:3}: trustworthiness {t:.3f}")
# Random starting points: change the seed and the picture moves
a = TSNE(init="random", random_state=0).fit_transform(X)
b = TSNE(init="random", random_state=1).fit_transform(X)
print("\nfirst point, seed 0:", a[0].round(1))
print("first point, seed 1:", b[0].round(1))
Output
perplexity 2: trustworthiness 0.983
perplexity 30: trustworthiness 0.993
perplexity 100: trustworthiness 0.991
first point, seed 0: [ -6. -44.3]
first point, seed 1: [-50.4 -2.2]
- All three perplexities give good maps here, with the default of 30 slightly ahead. A perplexity must be smaller than the number of points.
- With random starting points, a different
random_stateputs the same picture in a different place. The first point moves from about (−6, −44) to (−50, −2). The groups are the same, only rotated and shifted. Always fixrandom_stateif you want the same map twice. - Since scikit-learn 1.2 the default start is PCA, which makes maps more stable between runs.
Reading a t-SNE Map Safely
| You can trust | Do not trust |
|---|---|
| Which points are close neighbours | Distances between far-apart islands |
| That clear islands exist | The size of an island |
| That some classes mix together | The axes, which have no meaning |
t-SNE tends to make every group about the same size, even when one group is spread out and another is tight. Two islands far apart on the map may not be far apart in the data.
Speed tip
t-SNE is slow on large data. For tens of thousands of rows, first reduce to about 50 columns with PCA, then run t-SNE on those.
Common Mistakes
- Using t-SNE output as model features. It cannot map new rows, and its distances are not reliable. Use it to look, not to train.
- Clustering on the t-SNE map. Islands can be an artefact of perplexity. Cluster in the original space, then colour the map by cluster.
- Trying one perplexity only. Try a few values. A pattern you see at every setting is more likely to be real.
- Forgetting to scale. If columns use different units, scale them first, or one column will decide all the distances.
Practice Exercises
Exercise 1. Run t-SNE on all 1,797 digit pictures with PCA to 30 columns first. What lines do you add?
Show answer
X, y = load_digits(return_X_y=True)
X30 = PCA(n_components=30).fit_transform(X)
Z = TSNE(random_state=0).fit_transform(X30)
Exercise 2. Two islands on your t-SNE map sit far apart. Can you say those two groups are very different?
Show answer
Not from the map alone. t-SNE keeps neighbours, not long distances. Measure the distance between the group centres in the original data before drawing that conclusion.
Frequently Asked Questions
What is the difference between t-SNE and UMAP?
Both make neighbour-keeping maps. UMAP, from the separate umap-learn package, is usually faster, can map new rows, and often keeps a bit more of the large-scale shape. t-SNE is built into scikit-learn.
Can t-SNE make 3-D maps?
Yes, set n_components=3. The default Barnes-Hut method supports up to 3 dimensions. 2-D is the most common because it is easiest to read.
Summary
- t-SNE maps high-dimensional data to 2-D while keeping neighbours close.
- It separates groups far better than PCA, but only for viewing.
- Perplexity sets how many neighbours each point considers.
- Trust local neighbourhoods, not island sizes or distances between islands.
