Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 46

t-SNE

Place similar rows close together on a 2D map so clusters in a high-dimensional table become visible. One example is on this page.

Intermediate12 min
t-SNE MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

t-SNE builds a map for seeing structure. It tries to keep each point's neighbors nearby on the page and lets distant points stay loosely placed. Distances across the map are not real distances in the original table. Use the picture to look, not as model input.

Example

python
import numpy as np
from sklearn.manifold import TSNE

rng = np.random.default_rng(0)
X = np.vstack([rng.normal(0, 0.2, (20, 4)), rng.normal(3, 0.2, (20, 4))])
xy = TSNE(n_components=2, random_state=0, perplexity=5, init="pca").fit_transform(X)
gap = abs(xy[20:, 0].mean() - xy[:20, 0].mean())
print(f"map shape: {tuple(xy.shape)}")
print(f"group gap: {gap:.2f}")

Output:

text
map shape: (40, 2)
group gap: 93.73

When to use it

  • Use it to inspect whether groups separate. Do not feed the map into a classifier as features.
  • Perplexity sets how many neighbors matter. Rerun with a second value before you trust a picture.
  • The layout can change between runs. Set random_state when you need the same picture.

Loading playground…