Lesson 7 of 8 · Using Embeddings
Visualising Embeddings
See embeddings on a 2D map: dimensionality reduction, PCA step by step in Python, when to use t-SNE or UMAP, and how to read plots without being fooled.
- 5 min read
- Intermediate
- Reviewed
- Why embeddings need to be squashed to be seen
- How PCA finds the most informative directions
- When to use t-SNE or UMAP instead
- How to read embedding plots without being misled
You can't draw 1,536 dimensions
People can see two or three dimensions. Real embeddings have hundreds or thousands. To look at them, we reduce them to two numbers each while keeping as much of their structure as possible, then plot the result.
Plots like this are useful for exploring: spotting topics, outliers, mislabelled items, or whether two groups of documents overlap.
PCA
The program below squashes six 4-number embeddings down to 2 with PCA, using NumPy:
import numpy as np
# Toy 4-number embeddings for six words: [animal, size, wild, domestic]
words = ["kitten", "cat", "lion", "tiger", "mouse", "elephant"]
X = np.array([
[0.9, 0.1, 0.1, 0.9],
[0.9, 0.2, 0.2, 0.9],
[0.9, 0.6, 0.9, 0.1],
[0.9, 0.6, 1.0, 0.1],
[0.8, 0.0, 0.5, 0.3],
[0.9, 1.0, 0.8, 0.1],
])
# PCA: find the two directions along which the points spread out the most
centred = X - X.mean(axis=0)
covariance = centred.T @ centred / len(X)
values, vectors = np.linalg.eigh(covariance) # eigenvalues in increasing order
top2 = vectors[:, ::-1][:, :2] # the two largest directions
# Directions have no natural sign, so fix one: largest entry positive
for j in range(2):
if top2[np.argmax(np.abs(top2[:, j])), j] < 0:
top2[:, j] = -top2[:, j]
coordinates = centred @ top2
share = values[::-1][:2].sum() / values.sum()
print(f"The 2 directions keep {share:.0%} of the spread")
for word, (x, y) in zip(words, coordinates):
print(f"{word:9} x = {round(float(x), 2) + 0.0:5.2f} y = {round(float(y), 2) + 0.0:5.2f}")The two directions keep 99% of the spread, so this flat picture is faithful. Here are the results on a map (coordinates multiplied by 4 so they fill the picture, and nudged slightly where labels would overlap):
With real 1,536-number embeddings, two PCA directions might keep only a small share of the spread. The picture is then a rough sketch, not a faithful map.
t-SNE and UMAP
| Method | Strength | Watch out for |
|---|---|---|
| PCA | Fast, repeatable, keeps big-picture layout | Often squashes clusters together when the data is complex |
| t-SNE | Very good at showing local clusters | Distances between clusters and cluster sizes don't mean much; results change between runs |
| UMAP | Clear clusters, faster than t-SNE, keeps a bit more global layout | Also sensitive to settings; still distorts distances |
t-SNE and UMAP are non-linear: they bend and stretch the space to keep each point's nearest neighbours nearby. That produces striking cluster pictures, but the price is that the map is distorted elsewhere.
Common mistakes
Check how faithful a 2-D picture of embeddings is likely to be.
# How much spread each PCA direction captures, largest first spread = [4.0, 2.5, 0.3, 0.2] # What share of the total spread do the first two directions keep? # Print it as a whole percentage, like: 93%
In a t-SNE plot of embeddings, which feature can you rely on most?
Summary
- Embeddings must be reduced to 2 or 3 dimensions to be seen.
- PCA keeps the directions of greatest spread: fast, repeatable and good for the big picture.
- t-SNE and UMAP show local clusters clearly but distort distances and sizes.
- Plots are great for exploring (topics, outliers, label errors); confirm findings on the full vectors.
Next: a project that puts it all together: a semantic search engine.
Finished reading? Tick it off to track your progress.