Machine Learning · 20 of 20

t-SNE tutorial

Places similar high-dimensional observations near one another on a 2D map. Learn the concept, implement it from scratch, and apply it with scikit-learn.

Category
Dimensionality reduction
Core idea
KL(P ‖ Q) = ∑ᵢ≠ⱼ pᵢⱼ log(pᵢⱼ / qᵢⱼ)
Typical use
Exploring embeddings, image features, cell populations, and document clusters.
Practical tool
scikit-learn

What is t-SNE?

t-SNE is a dimensionality reduction technique. Places similar high-dimensional observations near one another on a 2D map. Its central idea is summarized by KL(P ‖ Q) = ∑ᵢ≠ⱼ pᵢⱼ log(pᵢⱼ / qᵢⱼ).

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with scikit-learn and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when t-SNE is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with scikit-learn and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryscikit-learn
Learning modeFrom scratch + library

How t-SNE works

  1. 1

    Input

    High-dimensional vectors and a neighborhood-size preference.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Match pairwise neighbor probabilities using gradient descent in two dimensions.

  4. 4

    Output

    A two-dimensional embedding that reveals local groups and neighborhoods.

  5. 5

    Validate

    Use trustworthiness or neighborhood-overlap measures instead of judging only by visual appeal.

Formula and intuition

KL(P ‖ Q) = ∑ᵢ≠ⱼ pᵢⱼ log(pᵢⱼ / qᵢⱼ)

pᵢⱼ measures similarity in the original space and qᵢⱼ measures similarity in the two-dimensional embedding.

The notation captures the main operation or complexity statement behind t-SNE. Read it together with the symbol key above and the step-by-step process in this guide.

When to use t-SNE

Exploring embeddings, image features, cell populations, and document clusters.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

t-SNE from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(80, 12))
distance_x = ((X[:, None] - X[None, :]) ** 2).sum(axis=2)
P = np.exp(-distance_x / (2 * distance_x[distance_x > 0].mean()))
np.fill_diagonal(P, 0)
P = (P + P.T) / (2 * P.sum())

Y = rng.normal(0, 1e-3, (len(X), 2))
for _ in range(600):
    distance_y = ((Y[:, None] - Y[None, :]) ** 2).sum(axis=2)
    affinity = 1 / (1 + distance_y)   # Student-t similarity in the map
    np.fill_diagonal(affinity, 0)
    Q = affinity / affinity.sum()
    gradient = 4 * ((P - Q) * affinity)[:, :, None] * (Y[:, None] - Y[None, :])
    Y += 50 * gradient.sum(axis=1)    # reduce KL divergence
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build t-SNE with scikit-learn

TSNE provides a tested optimizer, initialization choices, perplexity control, and reproducible random seeds.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install scikit-learn
  1. Prepare the data.High-dimensional vectors and a neighborhood-size preference. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Match pairwise neighbor probabilities using gradient descent in two dimensions.
  4. Inspect the result.A two-dimensional embedding that reveals local groups and neighborhoods. Then apply the evaluation checks in the next section.
Pythonscikit-learn workflow
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
from sklearn.preprocessing import StandardScaler

X, labels = load_digits(return_X_y=True)
X = StandardScaler().fit_transform(X[:1000])
labels = labels[:1000]
embedding = TSNE(
    n_components=2, perplexity=30, init="pca",
    learning_rate="auto", random_state=42,
).fit_transform(X)
print("embedding shape:", embedding.shape)
print("trustworthiness:", trustworthiness(X, embedding, n_neighbors=10))
print("label sample:", labels[:10])

API details and version-specific options: official scikit-learn reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Use trustworthiness or neighborhood-overlap measures instead of judging only by visual appeal.
  • Repeat with several seeds and perplexities; stable local neighborhoods deserve more confidence.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • Distances between far-apart clusters are not globally meaningful.
  • Cluster size in the map does not represent population size or variance.
  • Always scale features and limit interpretation to exploratory visualization.

Before using t-SNE in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference scikit-learn

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See t-SNE in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →