Skip to main content
LearnMLAcademy
Intermediate10 min read

t-SNE

Visualize high-dimensional data clusters with non-linear t-SNE probability maps, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

t-Distributed Stochastic Neighbor Embedding (t-SNE)

t-SNE is a non-linear dimensionality-reduction method used mainly to visualize high-dimensional data in two or three dimensions. Its central idea is simple: if two samples are close neighbors in the original feature space, t-SNE tries to place them close together on the map.

t-SNE in Simple Words

1
High-dimensional data
Many features
2
Measure similarity
Who is near whom?
3
Build a 2D/3D map
Move points around
4
Inspect neighborhoods
Look for local structure

The central objective

Preserve useful local neighborhood relationships when making a low-dimensional visualization.

t-SNE is commonly used to inspect embeddings, image features, text representations, biological measurements and other datasets where each sample may have tens, hundreds or thousands of values. It is an exploratory visualization tool, not a classifier and not proof that visible groups are real-world classes.

tt-distributed
SStochastic
NNeighbor
EEmbedding

Why t-SNE Is Useful

Humans can easily inspect a scatter plot with two or three axes, but not a point described by 64, 500 or 1,000 features. t-SNE gives us a low-dimensional map that can make local relationships easier to inspect.

Example: E-commerce customers

Imagine every customer is represented by browsing, purchase, category-interest and engagement features. We cannot directly draw a 500-dimensional scatter plot. t-SNE can map those samples into 2D so we can inspect which customers end up as local neighbors.

PCA and t-SNE answer different questions

PCAt-SNE
Linear transformationNon-linear embedding
Focuses on directions of feature varianceFocuses strongly on neighborhood probabilities
Has reusable components for later transformationScikit-learn t-SNE is primarily a fit-and-visualize workflow

PCA can be a useful first step before t-SNE when the original feature count is very high. Reducing to a moderate number of dimensions first can remove some noise and make t-SNE faster.


Core Philosophy of t-SNE

One idea per visual: keep close neighbors close

High-dimensional space

A • • B
C •

D • • E
→

2D t-SNE map

A • B •
  C •

D • E •

Illustration only. Absolute positions, axes and cluster spacing are not direct measurements of the original feature space.

Think of a classroom friendship map. If Alice's closest friends are Bob and Carla, a useful map should try to keep Bob and Carla near Alice. But the exact distance between the “football group” and the “music group” should not automatically be interpreted as a precise real-world distance.

A t-SNE plot is not a clustering algorithm

t-SNE can make visually separated islands even though it is not directly assigning semantic cluster labels. If you need formal clustering, use and evaluate a clustering method separately rather than treating every visible island as a guaranteed class.


Fundamental Concepts in t-SNE

1. Similarities

Convert high-dimensional neighborhood relationships into probabilities.

2. Low-dimensional map

Represent low-dimensional similarities with a heavy-tailed t-distribution.

3. Optimization

Move map points to reduce the mismatch measured by KL divergence.

Distance & high-dimensional similarity

With the default metric, t-SNE starts from Euclidean-style relationships between samples and converts distances into neighborhood probabilities. A smaller distance generally means a stronger neighborhood relationship.

Euclidean distance: easy worked example

A = (1, 2), B = (4, 6)

d = √[(4 − 1)² + (6 − 2)²]

d = √[3² + 4²]

d = √[9 + 16]

d = √25 = 5

High-dimensional probabilities

t-SNE does not try to copy every raw distance into 2D. It converts high-dimensional affinities into probabilities: close neighbors get larger probability mass than distant points. Different samples can use different Gaussian bandwidths so that the neighborhood scale matches the chosen perplexity.

Student t-distribution and the crowding problem

In the low-dimensional map, t-SNE uses a Student t-distribution with heavy tails. The heavy tail gives moderately distant points more room in the map and reduces the tendency for many points to crowd into the center.

Simple interpretation

High-dimensional Gaussian affinities answer: who should be neighbors?

Low-dimensional t-distribution answers: how should those neighborhood relationships be represented on the map?


Step-by-Step Working of t-SNE

High-Dimensional Samples │ ▼ Compute Neighborhood Affinities │ ▼ Create Initial 2D/3D Positions │ ▼ Compute Low-Dimensional Affinities │ ▼ Compare P and Q with KL Divergence │ ▼ Move Points to Reduce the Cost │ ▼ Final Visualization

KL Divergence

t-SNE minimizes the mismatch between high-dimensional neighborhood probabilities P and low-dimensional neighborhood probabilities Q using Kullback-Leibler divergence:

KL(P || Q) = Σ pᵢⱼ log(pᵢⱼ / qᵢⱼ)

Tiny KL contribution example

Suppose p = 0.20 and q = 0.10

p × ln(p/q) = 0.20 × ln(2)

≈ 0.20 × 0.693

≈ 0.139

The real t-SNE objective sums contributions across many pairs. This one pair is only for understanding the formula.

Gradient-based optimization repeatedly changes the low-dimensional coordinates to reduce this objective. Because the objective is non-convex, different initializations or random seeds can end at different local solutions.

Understanding perplexity

Perplexity is related to the effective neighborhood size t-SNE considers. It is not simply “the number of clusters” and it does not directly tell t-SNE how many groups to create.

Lower perplexity

Uses a smaller effective neighborhood and can emphasize very local relationships.

Middle value

Often a useful starting point, but still needs inspection rather than blind acceptance.

Higher perplexity

Uses a broader effective neighborhood and may smooth over smaller-scale patterns.

Do not memorize “5 = local” and “50 = global” as fixed rules

Different perplexity values can produce noticeably different shapes, sizes and spacing. In Scikit-learn, perplexity must also be smaller than the number of samples. It is sensible to inspect more than one reasonable value rather than declaring one plot to be the truth.

What must not be over-interpreted?

Cluster size

A larger island on the map does not necessarily mean a proportionally larger high-dimensional group.

Distance between islands

Far-apart islands are not guaranteed to be equally far apart in the original space.

Shape

The outline of a t-SNE island can change with perplexity, initialization and optimization.

Axes

t-SNE axis 1 and axis 2 do not have the direct feature meaning that original variables have.


Preprocessing Before t-SNE

Because neighborhood methods depend on distances, feature scale matters. If one meaningful numerical feature ranges from 0–1 and another from 0–1,000,000, the larger-scale feature can dominate the distance calculation unless that scale difference is intentional.

Scaling

Often useful when comparable numerical features use very different units. Do not standardize mechanically if the feature geometry has a domain-specific meaning.

PCA/SVD first

For very high-dimensional data, reducing to a moderate dimension first can speed up t-SNE and suppress some noise.


Python Implementation of t-SNE

Scikit-learn provides TSNE. The built-in handwritten-digits dataset used below has 64 input features per image, not 784. The target labels are used only to color the final plot; t-SNE itself does not train on those labels.

Python Code: t-SNE on handwritten digits

import matplotlib.pyplot as plt

from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler

# 1. Load data
digits = load_digits()
X = digits.data      # 1797 samples, 64 features
y = digits.target    # used only for plot colors

# 2. Put numerical features on a comparable scale
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 3. Optional pre-reduction before t-SNE
pca = PCA(n_components=40, random_state=42)
X_reduced = pca.fit_transform(X_scaled)

# 4. Build a 2D t-SNE embedding
tsne = TSNE(
    n_components=2,
    perplexity=30,
    init="pca",
    learning_rate="auto",
    max_iter=1000,
    random_state=42
)
X_tsne = tsne.fit_transform(X_reduced)

print("Original shape:", X.shape)
print("After PCA:", X_reduced.shape)
print("t-SNE shape:", X_tsne.shape)
print("Final KL divergence:", round(tsne.kl_divergence_, 3))

# 5. Visualize
plt.figure(figsize=(10, 8))
plt.scatter(
    X_tsne[:, 0],
    X_tsne[:, 1],
    c=y,
    cmap="tab10",
    s=12
)
plt.title("t-SNE Visualization of Handwritten Digits")
plt.show()

Expected deterministic console output

Original shape: (1797, 64)
After PCA: (1797, 40)
t-SNE shape: (1797, 2)
Final KL divergence: 0.83

The exact last digits of the KL value can depend on library/platform details. The important output is the 2D embedding shape and the visualization.

t-SNE is not a normal train → transform-new-data pipeline in Scikit-learn

The Scikit-learn TSNE interface provides the fitted embedding for the samples used during fitting; it does not provide the same reusable transform() workflow as PCA. That is one reason t-SNE is best treated here as an exploratory visualization method rather than a production feature transformer for incoming samples.


Advantages, Limitations & Comparisons

Useful strengths

  • Local visualization: Can make neighborhood structure easier to inspect.
  • Non-linear embedding: Can reveal patterns not visible in a simple linear 2D projection.
  • Representation inspection: Useful for exploring learned embeddings and feature spaces.

Important limitations

  • Computational cost: Considerably more expensive than PCA on large datasets.
  • Non-convex optimization: Different seeds or settings can produce different maps.
  • Global geometry: Large-scale distances and cluster sizes can be misleading.
  • No ordinary transform: Scikit-learn t-SNE is not a drop-in feature transformer for unseen samples.

t-SNE vs PCA

Featuret-SNEPCA
TransformationNon-linear embeddingLinear projection
Main teaching focusLocal neighborhoodsFeature variance directions
Reusable transformNot in Scikit-learn TSNEYes
Typical useExploratory 2D/3D visualizationVisualization or dimensionality reduction

What about UMAP?

UMAP is another popular non-linear embedding method. Its behavior, speed and global/local trade-offs depend on its own settings and implementation, so avoid memorizing a blanket rule such as “UMAP always preserves global structure better.” The safest comparison is to understand each method's objective and test sensible settings on the dataset at hand.


Common t-SNE Mistakes

  1. Treating every island as a confirmed cluster. A t-SNE map is evidence for exploration, not automatic semantic clustering.
  2. Reading between-cluster distance literally. Large gaps in 2D are not precise measurements of original-space separation.
  3. Using only one perplexity or seed. The map can change; inspect stability rather than trusting one attractive image.
  4. Ignoring feature scale. Distance-based neighborhoods can be dominated by large numerical units.
  5. Using t-SNE as a normal production feature transformer. Scikit-learn TSNE does not expose the same out-of-sample transform workflow as PCA.

Quick FAQ

Does t-SNE find clusters?

It creates an embedding that often makes local groups visually apparent, but it is not itself a semantic clustering algorithm.

Is perplexity the number of neighbors?

It is related to an effective neighborhood size through the entropy of the neighborhood probability distribution. Thinking “rough neighborhood scale” is useful; treating it as an exact K-nearest-neighbor count is too literal.

Should I run PCA before t-SNE?

For very high-dimensional data, pre-reducing to a moderate dimension with PCA for dense data or TruncatedSVD for sparse data can reduce noise and computation. It is not mandatory for every small dataset.

Final Summary

t-SNE is a non-linear method designed primarily for visualizing high-dimensional samples in two or three dimensions. It converts high-dimensional and low-dimensional affinities into probability distributions and optimizes the map by minimizing their KL-divergence mismatch.

Its greatest teaching value is local: nearby samples should remain useful neighbors. Its biggest interpretation warning is equally important: cluster size, shape, orientation and long-range distances in the 2D picture should not automatically be treated as faithful measurements of the original feature space.

Most Important Insight to Remember

Use t-SNE to explore local neighborhoods, then verify any apparent pattern with additional analysis instead of believing the picture alone.

Continue learning

Review PCA for linear dimensionality reduction, Feature Scaling for distance-sensitive preprocessing, or K-Means if your goal is explicit clustering rather than visualization.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "t-SNE"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What is t-SNE's primary purpose and why cannot you use it for model training?
Question 2 of 4
What does the perplexity parameter control in t-SNE?
Question 3 of 4
A t-SNE plot shows 5 clearly separated clusters. Can you conclude the data has exactly 5 natural clusters?
Question 4 of 4
Why does t-SNE use a t-distribution in the low-dimensional space rather than a Gaussian?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is t-SNE's primary purpose and why cannot you use it for model training?▼

Correct Answer: t-SNE maps high-dimensional data to 2D or 3D preserving local structure. It has no parametric transform — new points cannot be projected without rerunning the entire algorithm on the full dataset

t-SNE is purely exploratory. For model preprocessing, use PCA (has a transform formula) or UMAP (parametric). Use t-SNE only to understand cluster structure visually.

2What does the perplexity parameter control in t-SNE?▼

Correct Answer: The effective number of nearest neighbours for each point's local structure — low perplexity emphasises local structure; high perplexity considers broader neighbourhood. Try multiple perplexity values before drawing conclusions

Low perplexity creates tight isolated clusters. High perplexity shows broader global structure but small clusters may disappear. Always try multiple perplexity values.

3A t-SNE plot shows 5 clearly separated clusters. Can you conclude the data has exactly 5 natural clusters?▼

Correct Answer: Not necessarily — t-SNE is stochastic and distorts global distances. Different random seeds produce different layouts. Treat as hypothesis generator, validate with quantitative clustering metrics

Clusters that appear far apart in 2D may not be far apart in the original space. t-SNE suggests structure but does not confirm it definitively.

4Why does t-SNE use a t-distribution in the low-dimensional space rather than a Gaussian?▼

Correct Answer: The t-distribution has heavier tails — it allows moderate-distance neighbours in high dimensions to be placed far apart in 2D without penalty (the crowding problem). Gaussian in 2D would force too many points to cluster centrally

The crowding problem: in 2D there is not enough space to faithfully represent all moderate-distance neighbours from high dimensions. The t-distribution's heavy tails allow t-SNE to place these points far apart, revealing cluster structure more clearly.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next