t-SNE & Topic Modeling
Visualize nonlinear structure with t-SNE, learn its caveats, then discover hidden themes in text with LSA and LDA.
PCA gave us one tool for shrinking dimensions, but it can only rotate and project along straight axes. This lesson covers two unsupervised techniques that go further: t-SNE, which unfolds nonlinear structure into striking 2-D maps, and topic modeling, which discovers the hidden themes in a pile of documents. Different data, same spirit — find structure nobody labeled.
Where PCA plots fall short
The digits dataset packs each handwritten digit into 64 pixel features. There are ten obvious groups in there — one per digit — but similarity between digits isn't a straight-line affair: a curvy 3 sits "near" an 8 in ways no single linear axis captures. Project onto the top two principal components and much of that neighborhood structure smears together:
A few digits (0s, 6s) form loose islands, but the middle is a traffic jam. PCA did its job — it kept the two highest-variance directions — but the variance that separates a 4 from a 9 lives on a curved surface that no two straight axes can flatten.
t-SNE: preserving neighborhoods
t-distributed Stochastic Neighbor Embedding (t-SNE) takes a different goal: instead of preserving global variance, preserve local similarity. For every pair of points it computes "how likely are these two to be neighbors?" in the original high-dimensional space, then arranges points in 2-D so those neighbor probabilities match as closely as possible. Points that were close stay close; everything else is negotiable.
The knob you'll actually turn is perplexity — roughly, the number of neighbors each point tries to stay faithful to. Small perplexity focuses on very local structure (and can shatter clusters into fragments); larger values look further out and give smoother, more global layouts.
Even on this small 300-digit sample, the ten classes resolve into distinct islands — remember, t-SNE never saw the colors. Perplexity 5 produces tighter, more fragmented clumps; perplexity 30 gives the cleaner map. On the full dataset the separation is even more dramatic, which is why t-SNE became the standard for eyeballing embeddings, from digits to word vectors to single-cell genomics.
Reading a t-SNE plot honestly
t-SNE optimizes neighbor probabilities, and it will cheerfully distort everything else to get them. Keep these rules in mind:
- Distances between clusters mean little. Two islands far apart aren't necessarily more different than two nearby ones.
- Cluster sizes mean little. t-SNE expands dense blobs and shrinks sparse ones; the areas on screen don't reflect spread in the data.
- Different runs and perplexities give different pictures. Always try a couple of perplexity values before trusting a pattern.
- It's visualization-only. There's no
transformfor new points, so you can't use t-SNE coordinates as features in a deployed pipeline; refitting changes the whole map.
The modern alternative: UMAP
UMAP solves a similar neighbor-preservation problem but runs much faster,
scales to millions of points, preserves global structure somewhat better,
and can transform new data. It's not bundled with scikit-learn (package
umap-learn), but in practice it has largely replaced t-SNE for big
datasets. The reading skills above apply to UMAP plots too.
One practical tip that applies to both: for very wide data (thousands of features), run PCA down to about 50 components first, then t-SNE on that — faster and less noisy.
From pixels to words: bag-of-words
Dimensionality reduction gets even more interesting on text. First we need numbers: the bag-of-words representation counts how often each vocabulary word occurs in each document, ignoring order entirely. Each document becomes one very wide, very sparse row — one column per word.
CountVectorizerproduces raw counts.TfidfVectorizerreweights them by tf-idf, shrinking words that appear everywhere ("the", "and") and boosting words distinctive to a few documents.
Eighteen tiny documents already produce a matrix dozens of columns wide — real corpora hit tens of thousands. And you can probably see three themes hiding in there. Topic modeling is how the machine finds them.
Topic modeling: LSA and LDA
A topic model factorizes the document-term matrix into two smaller pieces: documents-to-topics ("doc 3 is 90% space") and topics-to-words ("the space topic loves rocket, orbit, earth"). Two classic approaches:
- LSA (Latent Semantic Analysis) applies truncated SVD — literally PCA's engine — to the (usually tf-idf) matrix. Fast and deterministic, but topic weights can be negative, which makes them awkward to read.
- LDA (Latent Dirichlet Allocation) is a probabilistic model: each document is a mixture of topics, each topic a distribution over words. It works on raw counts and its topics are proper probabilities — usually the more interpretable of the two.
Both models recover the space / cooking / football split without ever being told those themes exist — the topics are just directions (LSA) or word distributions (LDA) in bag-of-words space. Note the last two lines: LDA also gives each document a topic mixture, which makes a great compact feature vector for downstream tasks like clustering articles or routing support tickets. In practice, choosing the number of topics works like choosing k in K-Means: try several values and judge whether the top words tell coherent stories.
The same "compress, then look" recipe extends beyond text — run PCA on face images and the components become ghostly "eigenfaces"; feed t-SNE the topic mixtures of news articles and related stories cluster together. Unsupervised learning keeps paying rent as a lens on data.
Check your understanding
Q1.What does t-SNE try to preserve when mapping data to 2-D?
Q2.In a t-SNE plot, two clusters appear far apart and one looks much bigger than the other. What can you safely conclude?
Q3.Why can't you use fitted t-SNE coordinates as features for scoring new data in production?
Q4.What is the key difference between LSA and LDA topics?
Q5.In the bag-of-words representation, what does each column of the matrix correspond to?
Exercise: Add a fourth topic
Extend the lesson's corpus with 5–6 short sentences about a fourth theme
of your choosing (weather, music, finance...). Refit LDA with
n_components=4 and print the top 5 words per topic — does your new theme
get its own topic? Then refit with n_components=3 on the same expanded
corpus and observe what goes wrong.
Next up: a new module — time series, where the order of the rows finally matters and yesterday is your best predictor of today.