t-SNE (t-Distributed Stochastic Neighbor Embedding) › Visualizing t-SNE
Michael BrenndoerferJuly 30, 20256 min read
Machine Learning from ScratchAll chapters Part 6 of 9Explainability
t-SNE (t-Distributed Stochastic Neighbor Embedding) › Visualizing t-SNEOne section · Sections in this chapter3 / 8 ↓
Sections in this chapter8
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's create visualizations to understand how t-SNE works with different types of data structures. We'll start with a simple example using synthetic data to demonstrate the key concepts.
In[3]:
Codeimport sys
from pathlib import Path
import numpy as np
from matplotlib.colors import BoundaryNorm, ListedColormap
for parent in [Path.cwd(), *Path.cwd().parents]:
helper_dir = (
parent / "apps/web/content/notebooks/1_machine-learning-from-scratch"
)
if (helper_dir / "mls_plot_style.py").exists():
if str(helper_dir) not in sys.path:
sys.path.insert(0, str(helper_dir))
break
else:
raise FileNotFoundError("Could not locate mls_plot_style.py")
from mls_plot_style import PALETTE, polish_axes, use_mls_style
# Set random seed for reproducibility
np.random.seed(42)
binary_cmap = ListedColormap([PALETTE["primary"], PALETTE["amber"]])
digit_cmap = ListedColormap(
[
PALETTE["primary"],
PALETTE["amber"],
PALETTE["teal"],
PALETTE["rose"],
PALETTE["purple"],
PALETTE["coral"],
PALETTE["primary_mid"],
PALETTE["amber_soft"],
PALETTE["teal_soft"],
PALETTE["rose_soft"],
]
)
digit_norm = BoundaryNorm(np.arange(-0.5, 10.5, 1), digit_cmap.N)Out[4]:
Visualization


Out[5]:
Visualization


Now let's examine how different perplexity values affect the t-SNE visualization:
Out[6]:
Visualization


Out[7]:
Visualization


Let's also visualize the effect of t-SNE on high-dimensional data by projecting it back to 2D:
Out[8]:
Visualization
