Python & Data Science
LLMs & GenAI Under review

Pca Vs T Sne Vs Umap Picking The Right Dimensional

You’ve been staring at a scatter plot for ten minutes, and it looks like someone sneezed confetti onto your screen. Fifty features, two plotted axes, zero insight. You know there’s structure in your data — the problem is, you’re trying to understand a 50-dimensional shape by looking at its 2D shadow on the wall. That’s the curse of dimensionality in a nutshell, and it’s why dimensionality reduction isn’t just a nice-to-have — it’s a survival skill for anyone who works with real data.

In this article, we’re going to put three tools on the workbench and figure out what each one actually does. PCA is the fast, predictable workhorse that thinks in straight lines. t-SNE is the artist that cares deeply about who your neighbors are but takes creative liberties with distance. UMAP is the newcomer that promises both speed and a better sense of the big picture — though we’ll see that promise comes with a pretty big asterisk. By the end, you’ll know exactly when to reach for each one, and — maybe more importantly — when not to trust what you see.

1. The Problem: Your High-Dimensional Data Is Lying to You

Imagine you’re at a crowded party. You want to figure out who’s friends with whom, so you measure the distance between every pair of people. In a small room, that’s easy — friends cluster together, strangers stand apart. Now imagine the party is spread across a hundred tiny rooms connected by winding hallways. Two people standing three feet apart in different rooms might as well be on different planets, while two people twenty feet apart in the same room are clearly together. The geometry of the space matters, and when you can only see a flattened version of it, your sense of “close” breaks down completely.

That’s what happens with high-dimensional data. As the number of dimensions grows, the distance between any two points converges toward the same average value. Everything looks equally far apart. Your distance metrics — Euclidean, Manhattan, cosine — all start to lie to you. This is the curse of dimensionality, and it’s the reason we need to project data down to two or three dimensions where our eyes (and our clustering algorithms) can make sense of it.

The three tools we’re going to compare each solve this problem differently:

  • PCA (Principal Component Analysis): linear, fast, deterministic. It finds the directions of maximum variance and projects onto them. Think of it as rotating your data to find its natural axes, then dropping the least important ones.
  • t-SNE (t-distributed Stochastic Neighbor Embedding): nonlinear, preserves local neighborhoods, slow on big data. It asks “who are your closest friends?” in high dimensions and tries to put those friends near you in 2D.
  • UMAP (Uniform Manifold Approximation and Projection): nonlinear, balances local and global structure, much faster than t-SNE. It builds a fuzzy graph of your data’s shape and tries to lay that graph flat.

The core question we’re chasing: which tool reveals true structure, and which one creates artifacts you’ll misinterpret as real patterns?

Let’s start by loading some data we can actually see — or at least, data whose true structure we know. We’ll use Fashion-MNIST, a dataset of 28×28 grayscale images of clothing items. Each image is 784 pixels, which means each data point lives in a 784-dimensional space. That’s impossible to visualize directly, but we know the ground truth: there are ten clothing categories, and images of the same category should cluster together.

import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import fashion_mnist

# Load Fashion-MNIST — 60,000 training images, 28×28 each = 784 dimensions
(x_train, y_train), (_, _) = fashion_mnist.load_data()

# We'll work with a subset for speed — 5,000 images
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]

# Flatten each 28×28 image into a 784-dimensional vector
data = images.reshape(images.shape[0], -1).astype(np.float32)

print(f"Data shape: {data.shape}")
print(f"That's {data.shape[1]} dimensions — one per pixel.")
print(f"Label distribution: {np.bincount(labels)}")

# Show a few raw images so we connect 'dimensions' to concrete pixels
label_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

fig, axes = plt.subplots(2, 5, figsize=(10, 4))
for i, ax in enumerate(axes.flat):
    ax.imshow(images[i], cmap='gray')
    ax.set_title(label_names[labels[i]], fontsize=9)
    ax.axis('off')
plt.suptitle("Sample Fashion-MNIST Images — 784 Dimensions Each", fontsize=13)
plt.tight_layout()
plt.show()

That’s our starting point. Five thousand images, each one a point in a 784-dimensional space. There’s real structure here — sneakers should look different from dresses — but we can’t see it yet. Let’s fix that.

2. PCA: The Workhorse That Thinks in Straight Lines

PCA is the baseline everyone learns first, and for good reason. The intuition is beautifully simple: imagine a cloud of points shaped like a cigar. The cigar has a long axis and a short axis. PCA finds that long axis — the direction where the data varies the most — and calls it the first principal component. Then it finds the next most-variable direction, constrained to be perpendicular to the first, and calls that the second component. Keep going, and you’ve rotated your data to align with its natural axes. Drop the least important axes, and you’ve reduced dimensionality.

In plain English: PCA is just “rotate the data so the most important directions line up with the axes, then chop off the dimensions that don’t matter much.”

What PCA actually optimizes: it finds orthogonal directions that maximize variance. Each principal component is a weighted sum of the original features — a recipe like “0.3 × pixel_1 + 0.1 × pixel_2 − 0.05 × pixel_3 + …” The weights (called loadings) tell you which original features contribute most to each component, which makes PCA wonderfully interpretable.

The explained variance ratio tells you how much of the original data’s spread is captured by each component. If the first two components capture 45% of the variance, that means you’re keeping 45% of the information and throwing away 55% when you plot in 2D. That’s a number you should always check — it tells you how much to trust the 2D picture.

Here’s the catch: PCA can only find straight-line directions. If your data lives on a curved surface — a manifold — PCA will flatten it like a pancake and destroy the structure. Imagine data points arranged in a spiral. PCA will find the direction of maximum variance cutting straight across the spiral, mashing the arms together. If your clusters are arranged in a circle, PCA will see one big blob.

PCA is also deterministic and blazingly fast. On million-sample datasets, it finishes in seconds where t-SNE would take hours. This makes it perfect as a preprocessing step — and as we’ll see, you should almost always initialize t-SNE and UMAP with PCA coordinates, not random noise.

Let’s run PCA on our Fashion-MNIST subset and see what happens.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.datasets import fashion_mnist

# --- Recreate the dataset (self-contained block) ---
(x_train, y_train), (_, _) = fashion_mnist.load_data()
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]
data = images.reshape(images.shape[0], -1).astype(np.float32)

label_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Standardize — PCA is sensitive to scale
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# Fit PCA and transform to 2D
pca = PCA(n_components=2, random_state=42)
data_pca = pca.fit_transform(data_scaled)

# Print explained variance ratio for first 10 components
pca_full = PCA(random_state=42)
pca_full.fit(data_scaled)
cumulative = np.cumsum(pca_full.explained_variance_ratio_)
print("Explained variance ratio (first 10 components):")
for i in range(10):
    print(f"  PC{i+1}: {pca_full.explained_variance_ratio_[i]:.4f}  (cumulative: {cumulative[i]:.4f})")
print(f"\nFirst 2 components capture {cumulative[1]:.2%} of the total variance.")
print("That means we're losing about {:.0f}% of the information in this 2D plot.".format((1-cumulative[1])*100))

# Scatter plot colored by true labels
fig, ax = plt.subplots(figsize=(10, 7))
scatter = ax.scatter(data_pca[:, 0], data_pca[:, 1], c=labels, cmap='tab10', alpha=0.6, s=10)
legend1 = ax.legend(*scatter.legend_elements(), title="Classes", bbox_to_anchor=(1.02, 1), loc='upper left')
for i, name in enumerate(label_names):
    legend1.get_texts()[i].set_text(name)
ax.add_artist(legend1)
ax.set_xlabel(f"PC1 ({pca_full.explained_variance_ratio_[0]:.1%} variance)")
ax.set_ylabel(f"PC2 ({pca_full.explained_variance_ratio_[1]:.1%} variance)")
ax.set_title("PCA on Fashion-MNIST (5,000 samples)")
plt.tight_layout()
plt.show()

Look at that plot. Some classes separate decently — trousers and sneakers pull away from shirts and coats — but there’s massive overlap in the center. Pullovers, coats, and shirts all bleed into each other. PCA found the directions of maximum pixel variance, but those directions don’t necessarily correspond to the visual features that distinguish a coat from a pullover. The linear assumption is the bottleneck here.

3. t-SNE: The Neighbor-Preserver That Can Trick You

If PCA is a cartographer drawing straight borders, t-SNE is a local tour guide who only cares about your immediate neighborhood. It doesn’t try to preserve the overall shape of the country — it just makes sure your closest friends stay close.

Here’s the intuition. t-SNE looks at every pair of points in high-dimensional space and asks: “How likely is it that these two are neighbors?” It converts distances into probabilities using a Gaussian kernel centered on each point. Points that are close together get a high probability of being neighbors; points far apart get a probability near zero. Then it tries to arrange the points in 2D so that the neighbor probabilities match as closely as possible.

Now here’s the clever part. In high dimensions, t-SNE uses a Gaussian kernel to define neighborhoods. But in the low-dimensional layout, it uses a Student-t distribution with heavy tails. Why? Because of something called the “crowding problem.” In high dimensions, you can have many points that are all moderately far from each other. When you try to cram them into 2D, there’s not enough room — points get crowded together. The heavy tails of the t-distribution let moderately distant points stretch apart in the 2D map, which is what creates those beautiful, well-separated clusters. This is the secret sauce that makes t-SNE plots look so much cleaner than PCA.

The key knob you need to tune is perplexity. In plain English: “how many neighbors do you consider local?” A perplexity of 30 means the algorithm balances its attention across roughly 30 nearest neighbors for each point. Low perplexity (5) means very local attention — you’ll see lots of small, tight sub-clusters, some of which might just be noise. High perplexity (50 or 100) means more global attention — clusters merge together, and you might lose fine structure.

This is the hardest part of t-SNE, and honestly of this whole article: what t-SNE plots do NOT tell you.

  • Cluster sizes are meaningless. t-SNE expands small clusters and contracts large ones to satisfy the perplexity constraint. A tiny cluster in your t-SNE plot might represent thousands of points, and a huge blob might represent dozens. You cannot read sample counts from the visual area.
  • Distances between clusters are meaningless. Two clusters that look far apart in t-SNE might actually be close neighbors in high-dimensional space. t-SNE only cares about preserving within-cluster distances, not between-cluster distances.
  • Random noise can look like structure at low perplexity. If you set perplexity too low, t-SNE will find “clusters” in pure random noise. It’s an artist that hates blank canvas — it will paint something even when there’s nothing there.

t-SNE is also computationally expensive. In its exact form, it’s O(N²) — double the points, quadruple the runtime. For datasets above 10,000 points, you need the Barnes-Hut approximation. For 100,000+ points, even that struggles. This is why you almost never run t-SNE on raw million-point datasets without downsampling first.

Practical protocol from the literature: always use PCA initialization (not random), set exaggeration early in optimization to encourage cluster separation, and for large datasets, use downsampling-based initialization where you first run t-SNE on a subset, then add remaining points based on their neighbors in the existing embedding.

Let’s run t-SNE on our data and see how it compares to PCA.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.datasets import fashion_mnist

# --- Recreate the dataset (self-contained block) ---
(x_train, y_train), (_, _) = fashion_mnist.load_data()
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]
data = images.reshape(images.shape[0], -1).astype(np.float32)

label_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Standardize
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# PCA initialization — reduce to 50 dimensions first (standard practice)
pca_init = PCA(n_components=50, random_state=42)
data_pca50 = pca_init.fit_transform(data_scaled)

# t-SNE with perplexity=30, PCA initialization
tsne = TSNE(n_components=2, perplexity=30, init=data_pca50[:, :2],
            random_state=42, n_iter=1000, verbose=0)
data_tsne = tsne.fit_transform(data_scaled)

# Plot
fig, ax = plt.subplots(figsize=(10, 7))
scatter = ax.scatter(data_tsne[:, 0], data_tsne[:, 1], c=labels, cmap='tab10', alpha=0.6, s=10)
legend1 = ax.legend(*scatter.legend_elements(), title="Classes", bbox_to_anchor=(1.02, 1), loc='upper left')
for i, name in enumerate(label_names):
    legend1.get_texts()[i].set_text(name)
ax.add_artist(legend1)
ax.set_title("t-SNE (perplexity=30) on Fashion-MNIST")
ax.set_xlabel("t-SNE 1")
ax.set_ylabel("t-SNE 2")
plt.tight_layout()
plt.show()

Now that’s a different picture. The clusters are tight, well-separated, and mostly correspond to the true clothing categories. But notice something: the “Shirt” class (label 6) is split into multiple sub-clusters, and some clusters are much larger visually than others. Are those size differences real? No — remember, t-SNE expands and contracts clusters to satisfy the perplexity constraint. The visual area tells you nothing about the number of samples in each cluster.

Let’s check that against the data by running t-SNE at different perplexity values. If the structure is robust, it should persist across reasonable perplexity choices. If it’s an artifact, it’ll shift dramatically.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.datasets import fashion_mnist

# --- Recreate the dataset (self-contained block) ---
(x_train, y_train), (_, _) = fashion_mnist.load_data()
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]
data = images.reshape(images.shape[0], -1).astype(np.float32)

label_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Standardize
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# PCA initialization
pca_init = PCA(n_components=50, random_state=42)
data_pca50 = pca_init.fit_transform(data_scaled)

# Run t-SNE at three perplexity values
perplexities = [5, 30, 100]
fig, axes = plt.subplots(1, 3, figsize=(18, 5))

for ax, perp in zip(axes, perplexities):
    tsne = TSNE(n_components=2, perplexity=perp, init=data_pca50[:, :2],
                random_state=42, n_iter=1000, verbose=0)
    data_tsne = tsne.fit_transform(data_scaled)
    ax.scatter(data_tsne[:, 0], data_tsne[:, 1], c=labels, cmap='tab10', alpha=0.6, s=8)
    ax.set_title(f"t-SNE perplexity={perp}")
    ax.set_xticks([])
    ax.set_yticks([])

plt.suptitle("Same Data, Different Perplexity — Notice How the Picture Changes", fontsize=13)
plt.tight_layout()
plt.show()

print("Notice: at perplexity=5, we see many tiny sub-clusters — some are noise artifacts.")
print("At perplexity=100, clusters merge together — we lose fine structure.")
print("Cluster sizes also shift across perplexities — that's the t-SNE artifact we warned about.")

The picture shifts dramatically. At perplexity 5, the data fragments into many tiny islands — some of those are almost certainly noise. At perplexity 100, distinct clusters start merging into larger blobs. The “right” perplexity depends on your data and your goal, but the key lesson is: never trust a t-SNE plot at a single perplexity setting. Sweep it.

4. UMAP: The Speed Demon That (Sometimes) Keeps the Big Picture

UMAP arrived in 2018 and quickly became the favorite for large datasets, especially in single-cell biology where datasets routinely hit millions of cells. The math is more sophisticated — it’s grounded in topological data analysis and Riemannian geometry — but the intuition is surprisingly accessible.

Think of UMAP as building a “fuzzy skeleton” of your data. First, it connects each point to its nearest neighbors, creating a graph where edges represent “these points are connected in the manifold.” But instead of hard yes/no connections, it uses fuzzy ones — each edge has a weight representing how confident UMAP is that the connection is real. This fuzzy graph captures the shape of your data at multiple scales simultaneously. Then UMAP tries to lay out that graph in 2D, pulling connected points together and pushing unconnected points apart, until it finds a low-dimensional arrangement that preserves as much of the fuzzy topological structure as possible.

In plain English: UMAP draws a connect-the-dots picture of your data’s shape, then stretches that picture flat onto a 2D canvas, trying to keep connected dots close together.

The two knobs you actually need to tune:

  • n_neighbors: how many neighbors define “local.” Low values (5–15) capture very fine, local detail — you’ll see lots of small sub-structures. High values (50–200) capture more global structure — the big-picture shape of your data. This is roughly analogous to perplexity in t-SNE, but it works in the opposite direction: higher n_neighbors = more global.
  • min_dist: how tightly points are allowed to pack together. Low values (0.0–0.1) produce tight, dense clusters — great for seeing fine separation. High values (0.5–0.9) force points to spread out — better for seeing the overall topology.

Now here’s the asterisk on UMAP’s famous “global structure preservation.” When UMAP first appeared, it produced embeddings that looked more globally coherent than t-SNE — clusters were positioned in ways that seemed to reflect their high-dimensional relationships. This was a major selling point. But Kobak and Linderman (2021) showed something fascinating: much of this advantage comes from UMAP’s default initialization (spectral embedding, which is closely related to PCA), while t-SNE historically defaulted to random initialization. When both use the same PCA initialization, the gap in global structure preservation narrows considerably. UMAP isn’t magic — it’s just got better defaults.

UMAP’s real, undisputed advantage is speed. It scales to millions of points where t-SNE chokes, and it’s fast enough that you can interactively sweep n_neighbors and min_dist to understand your data, rather than waiting hours for a single t-SNE run to finish.

Same caveats as t-SNE apply: cluster sizes and inter-cluster distances are not reliable. UMAP is not a truth machine — it’s a faster, sometimes-better neighbor-preserver.

Let’s run UMAP on our Fashion-MNIST data and see what we get.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.datasets import fashion_mnist

# Note: umap-learn must be installed: pip install umap-learn
import umap

# --- Recreate the dataset (self-contained block) ---
(x_train, y_train), (_, _) = fashion_mnist.load_data()
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]
data = images.reshape(images.shape[0], -1).astype(np.float32)

label_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Standardize
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# UMAP with default parameters
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42)
data_umap = reducer.fit_transform(data_scaled)

# Plot
fig, ax = plt.subplots(figsize=(10, 7))
scatter = ax.scatter(data_umap[:, 0], data_umap[:, 1], c=labels, cmap='tab10', alpha=0.6, s=10)
legend1 = ax.legend(*scatter.legend_elements(), title="Classes", bbox_to_anchor=(1.02, 1), loc='upper left')
for i, name in enumerate(label_names):
    legend1.get_texts()[i].set_text(name)
ax.add_artist(legend1)
ax.set_title("UMAP (n_neighbors=15, min_dist=0.1) on Fashion-MNIST")
ax.set_xlabel("UMAP 1")
ax.set_ylabel("UMAP 2")
plt.tight_layout()
plt.show()

The UMAP plot looks similar to t-SNE — tight clusters, good separation — but notice the clusters feel more “connected.” There are bridges between related categories (like sneakers and ankle boots) that t-SNE often pulls apart into isolated islands. This is the global structure that UMAP claims to preserve better.

Now let’s sweep the two key parameters to see how the picture changes.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.datasets import fashion_mnist
import umap

# --- Recreate the dataset (self-contained block) ---
(x_train, y_train), (_, _) = fashion_mnist.load_data()
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]
data = images.reshape(images.shape[0], -1).astype(np.float32)

# Standardize
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# Sweep n_neighbors and min_dist
n_neighbors_values = [5, 15, 50]
min_dist_values = [0.1, 0.5, 0.9]

fig, axes = plt.subplots(3, 3, figsize=(15, 15))
for i, n_neigh in enumerate(n_neighbors_values):
    for j, min_d in enumerate(min_dist_values):
        reducer = umap.UMAP(n_neighbors=n_neigh, min_dist=min_d, random_state=42)
        embedding = reducer.fit_transform(data_scaled)
        ax = axes[i, j]
        ax.scatter(embedding[:, 0], embedding[:, 1], c=labels, cmap='tab10', alpha=0.6, s=5)
        ax.set_title(f"n_neighbors={n_neigh}, min_dist={min_d}")
        ax.set_xticks([])
        ax.set_yticks([])

plt.suptitle("UMAP Parameter Sweep: n_neighbors (rows) × min_dist (columns)", fontsize=14)
plt.tight_layout()
plt.show()

print("Top row (n_neighbors=5): very local — lots of small sub-clusters, some may be noise.")
print("Bottom row (n_neighbors=50): more global — clusters merge, big-picture shape emerges.")
print("Left column (min_dist=0.1): tight packing — good for seeing fine separation.")
print("Right column (min_dist=0.9): spread out — better for seeing overall topology.")

As before, the picture shifts with parameter choices. Low n_neighbors gives you a fragmented view; high n_neighbors merges distinct groups. Low min_dist packs points tightly; high min_dist spreads them out. The “right” setting depends on what question you’re asking, but the fact that you can sweep these parameters in seconds (rather than hours) is UMAP’s killer feature.

5. Head-to-Head: Same Data, Three Tools, One Truth

Now let’s put all three projections side by side. When we see them together, we can start to separate real structure from algorithmic artifacts. The triangulation principle is simple: if all three methods show a cluster, it’s probably real. If only one method shows it, be skeptical.

import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.datasets import fashion_mnist
import umap

# --- Recreate the dataset (self-contained block) ---
(x_train, y_train), (_, _) = fashion_mnist.load_data()
np.random.seed(42)
indices = np.random.choice(x_train.shape[0], 5000, replace=False)
images = x_train[indices]
labels = y_train[indices]
data = images.reshape(images.shape[0], -1).astype(np.float32)

label_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Standardize
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)

# PCA
start = time.time()
pca = PCA(n_components=2, random_state=42)
data_pca = pca.fit_transform(data_scaled)
pca_time = time.time() - start

# t-SNE (with PCA init)
pca_init = PCA(n_components=50, random_state=42)
data_pca50 = pca_init.fit_transform(data_scaled)
start = time.time()
tsne = TSNE(n_components=2, perplexity=30, init=data_pca50[:, :2],
            random_state=42, n_iter=1000, verbose=0)
data_tsne = tsne.fit_transform(data_scaled)
tsne_time = time.time() - start

# UMAP
start = time.time()
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42)
data_umap = reducer.fit_transform(data_scaled)
umap_time = time.time() - start

# Side-by-side plot
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
embeddings = [data_pca, data_tsne, data_umap]
titles = [f"PCA ({pca_time:.1f}s)", f"t-SNE ({tsne_time:.1f}s)", f"UMAP ({umap_time:.1f}s)"]

for ax, emb, title in zip(axes, embeddings, titles):
    ax.scatter(emb[:, 0], emb[:, 1], c=labels, cmap='tab10', alpha=0.6, s=8)
    ax.set_title(title)
    ax.set_xticks([])
    ax.set_yticks([])

plt.suptitle("Same Data, Three Projections — Where Do They Agree?", fontsize=14)
plt.tight_layout()
plt.show()

# Runtime bar chart
fig, ax = plt.subplots(figsize=(6, 4))
methods = ['PCA', 't-SNE', 'UMAP']
times = [pca_time, tsne_time, umap_time]
bars = ax.bar(methods, times, color=['steelblue', 'darkorange', 'seagreen'])
ax.set_ylabel("Runtime (seconds)")
ax.set_title("Runtime Comparison on 5,000 Samples")
for bar, t in zip(bars, times):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, f"{t:.1f}s",
            ha='center', fontweight='bold')
plt.tight_layout()
plt.show()

print(f"PCA: {pca_time:.2f}s — essentially instant.")
print(f"t-SNE: {tsne_time:.2f}s — noticeably slower, and this is only 5,000 points.")
print(f"UMAP: {umap_time:.2f}s — much faster than t-SNE, close to PCA speed.")

What do we observe? PCA shows broad, overlapping clouds — some structure is visible, but many classes bleed together. t-SNE shows tight, isolated islands — great separation, but we’ve lost any sense of which clusters are related to which. UMAP shows connected clusters with bridges between related categories — a middle ground.

The triangulation principle in action: trousers, sneakers, and ankle boots form distinct clusters in all three projections — those separations are almost certainly real. Shirts and t-shirts overlap heavily in PCA, separate partially in UMAP, and fragment into sub-clusters in t-SNE — the true structure here is ambiguous, and we should be cautious about over-interpreting any single view.

For a more controlled test, scikit-learn provides a beautiful example using the S-curve dataset — a 3D manifold that we can actually see and understand before projecting it. When you run PCA, t-SNE, and UMAP on the S-curve, PCA flattens it into a pancake (losing the 3D structure entirely), while t-SNE and UMAP unroll it into a 2D sheet that preserves the manifold. You can find that example in scikit-learn’s “Comparison of Manifold Learning methods” gallery — it’s the clearest demonstration I know of why linear methods fail on curved manifolds.

6. When to Use Which: A Decision Framework

No tool is universally best. The right choice depends on your goal, your data size, and what you’re willing to sacrifice. Here’s the framework I use:

Use PCA when:

  • You need speed. PCA finishes in seconds on million-sample datasets.
  • You need interpretability. The loadings tell you exactly which original features drive each component.
  • You need deterministic results. Run PCA twice, get the same answer every time.
  • You’re preprocessing for downstream ML. PCA is the standard first step before t-SNE, UMAP, or clustering.
  • Your data is roughly linear. If you suspect your features have linear relationships, PCA is the right tool.

Use t-SNE when:

  • You have small-to-medium data (under 10,000 points for exact; under 100,000 with Barnes-Hut).
  • You care intensely about local cluster separation and want publication-quality visualizations.
  • You’re willing to tune perplexity carefully and sweep it to check robustness.
  • You understand and accept that cluster sizes and inter-cluster distances are not interpretable.

Use UMAP when:

  • You have large data (10,000 to 1,000,000+ points).
  • You need speed to iterate on hyperparameters interactively.
  • You want a balance of local and global structure.
  • You’re working in single-cell transcriptomics or similar big-bio domains where UMAP has become the default.

The honest truth: for most exploratory visualization, run both t-SNE and UMAP (with PCA initialization for both) and compare. If they agree, you have a story. If they disagree, dig deeper — the disagreement itself is information.

What none of these tools do:

  • They don’t give you causal relationships.
  • They don’t tell you which features drive the separation (except PCA loadings).
  • They don’t replace proper clustering algorithms — they visualize, they don’t cluster.
  • They don’t give you a single “true” picture of your data. Every projection is a distortion; the question is whether it’s a useful one.

7. Recap and What’s Next

Let’s land the plane with the key takeaways:

  • PCA is linear, fast, deterministic, and interpretable — but it can’t handle curved manifolds. It’s your baseline and your preprocessing workhorse.
  • t-SNE preserves local neighborhoods beautifully but distorts global structure, cluster sizes, and distances. Perplexity must be tuned, and you should never trust a single perplexity setting.
  • UMAP is faster than t-SNE and often preserves more global structure, but much of that advantage comes from better default initialization, not a fundamentally different algorithm. Same caveats about cluster sizes and distances apply.
  • Always use PCA initialization for t-SNE and UMAP. Random initialization gives you worse results and slower convergence.
  • Triangulate: run multiple methods and look for agreement. Structure that appears across PCA, t-SNE, and UMAP is probably real. Structure that only appears in one method is suspect.

In the next article in this series, we’ll take a deeper dive into UMAP’s underlying theory — what “fuzzy simplicial sets” actually mean, and how understanding the topology can help you tune parameters more effectively. For now, you’ve got a practical framework for choosing the right tool and avoiding the most common misinterpretations.

Check Your Understanding

Remember: What are the three dimensionality reduction techniques compared in this article, and what is the primary strength of each?

Understand: In your own words, explain why cluster sizes in a t-SNE plot are not interpretable. What mechanism in the algorithm causes this distortion?

Apply: You have a dataset with 200 features and 50,000 samples. You want to visualize it in 2D to check for clusters before running k-means. Which tool(s) would you choose and why? What parameters would you tune?

Analyze: A colleague shows you a t-SNE plot with perplexity=5 that has dozens of tiny, well-separated clusters. They claim this proves the data has many distinct sub-populations. What questions would you ask to evaluate this claim?

Evaluate: Compare the runtime and global-structure-preservation claims of UMAP versus t-SNE. Under what conditions is UMAP genuinely better, and under what conditions is the difference mostly attributable to initialization defaults?

Create: Design a visualization protocol for a new dataset with unknown structure. Specify the sequence of methods you would apply, the parameters you would sweep, and the criteria you would use to decide whether observed clusters are “real” or artifacts.

  • The Curse of Dimensionality: Why More Features Isn’t Always Better — If the distance-metric breakdown we discussed in Section 1 intrigued you, this article dives deeper into why high-dimensional spaces are deeply weird and how to fight back.
  • Clustering After Dimensionality Reduction: Why the Order Matters — You’ve projected your data to 2D and see clusters. Should you cluster in the original space or the reduced space? This article walks through the tradeoffs.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • LLMs & GenAI Under review

    Giving An Llm Memory Short Term Context Vs Long Te

    Remember the agent you built in Part 2? It was great at calling tools. You could ask it to check the weather, look up a fact, or do some math, and it would figure out which tool to use and hand back the right answer.

  • LLMs & GenAI Under review

    What Makes an "Agent" an Agent? The Loop Behind Every LLM Agent

    You've built a chatbot. It answers questions, maybe even holds a decent conversation. But then you ask it to check the weather in Tokyo right now, and it says, "I don't have access to real-time data." Sound familiar?

  • LLMs & GenAI Under review

    Langchain Vs Llamaindex Vs Raw Api Calls Choosing

    Before we name any frameworks, let’s build a mental model. Imagine you’re building a system that answers questions from a PDF research paper.

  • LLMs & GenAI Under review

    What Is Reinforcement Learning Really Agents Envir

    Let's name the pieces the toddler story introduced. Every RL problem has exactly three components:

Looking for something else?

Search every article by title, summary or topic.