From word counts to topics: LSA, PLSA and LDA
Three steps from linear algebra to a probabilistic story. LSA is an SVD of a word-count table, PLSA makes each document a mix of word distributions, and LDA adds Dirichlet priors so the model can score documents it hasn't seen.
What runs in CodeSplash
- REP041Latent semantic analysis / truncated SVD Runs in CodeSplash (Experimental)
- REP042Probabilistic latent semantic analysis (PLSA) Partly runs in CodeSplash
- REP043Latent Dirichlet allocation (LDA) Runs in CodeSplash
- Topic model Verified in Python and R
- Choose the number of topics Verified in Python and R
You will be able to
- Explain LSA as a truncated SVD of a TF-IDF table and why its components aren't topics
- Write PLSA's mixture and its EM responsibility step, and say why it overfits
- Write LDA's generative story and its collapsed Gibbs update, and compare it with PLSA on a corpus
LSA: an SVD of the word table
ReadPut documents in rows and words in columns, weight the counts by TF-IDF, and take a truncated SVD: . That is latent semantic analysisLatent semantic analysis (LSA)A text embedding made by compressing TF-IDF word weights with a truncated SVD, so documents that share words and word patterns sit close..
Rows of are document coordinates; rows of are word coordinates. Words used in the same documents ("car", "automobile") get similar coordinates, so documents can match without sharing a word. A new document folds in by multiplying its TF-IDF row by .
In the reference's example, two dimensions leave a residual of norm 6.446, and a new document lands at (3.35, −0.75).
Why LSA dimensions aren't topics
ReadSVD directions are signed and orthogonal. A dimension might be "+sport words, −finance words": a contrast, not a theme, and a document can have a negative amount of it. Counts are also nothing like Gaussian, which squared error quietly assumes.
LSA is an excellent feature step: fast, deterministic, and good for search and similarity. For themes you can read, the next two models are built on probabilities instead.
PLSA: documents as mixtures
ReadPLSAProbabilistic latent semantic analysis (PLSA)A topic model fitted by EM: each document mixes topics, each topic is a word distribution, with no priors on either. says each word in document comes from one of topics:
Topics are word distributions; documents are topic mixtures; everything is non-negative and sums to one. EM fits it. The E-step splits each word's count across topics by responsibility, . In the reference's example a word splits 0.571 to 0.429 between two topics.
Where PLSA falls short
ReadPLSA learns a separate topic mix for every training document, with no prior. So:
- its parameter count grows with the number of documents, and it overfits;
- it has no principled probability for a new document, which needs an ad hoc fold-in;
- with few words per document, mixes become extreme.
LDA: priors on the mixtures
ReadLatent Dirichlet allocation puts Dirichlet priors on both distributions. To write a document, draw its topic mix ; each topic's words come from ; for every word, draw a topic from and a word from that topic.
Collapsed Gibbs sampling reassigns one word's topic at a time:
In the reference's example, one word's two topic probabilities come out 0.589 and 0.411. Small gives documents few topics; small gives topics few words.
Watch topics form
ExploreAExplorable · Topics by Gibbs sampling
How does LDA turn word co-occurrence into topics, one word at a time?
The corpus was written from 3 topics. How many will the sampler recover exactly (the same four top words)?
One sweep reassigns every word's topic once.
- Topic 1: team, goal, ball, coach
- Topic 2: rain, cloud, sun, wind
- Topic 3: salt, pepper, soup, bread
The corpus was written from three topics: weather (sun … cloud), food (bread … pepper) and sports (goal … coach). The sampler sees only which words share documents.
Commit your prediction above to see the result
Make your prediction to see the result.
A tiny corpus written from three topics. Collapsed Gibbs sampling reassigns one word's topic at a time; slide through the sweeps and watch each topic's word list sharpen. Then try two topics, or five, against the three that wrote it.
Both on one corpus
Read3 topics in 61 documents (85 terms); topic 1 (team, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| team | Topic 1 | 0.0634 |
| match | Topic 1 | 0.0558 |
| striker | Topic 1 | 0.0405 |
| league | Topic 1 | 0.0330 |
| fans | Topic 1 | 0.0330 |
| bake | Topic 1 | 0.0324 |
| goal | Topic 1 | 0.0254 |
| kept | Topic 1 | 0.0254 |
| penalty | Topic 1 | 0.0254 |
| goalkeeper | Topic 1 | 0.0254 |
| rates | Topic 2 | 0.0852 |
| interest | Topic 2 | 0.0605 |
| bank | Topic 2 | 0.0522 |
| higher | Topic 2 | 0.0521 |
| markets | Topic 2 | 0.0440 |
| shares | Topic 2 | 0.0440 |
| profits | Topic 2 | 0.0440 |
| inflation | Topic 2 | 0.0440 |
| investors | Topic 2 | 0.0357 |
| fell | Topic 2 | 0.0275 |
| garlic | Topic 3 | 0.0618 |
| onions | Topic 3 | 0.0500 |
| sauce | Topic 3 | 0.0499 |
| oil | Topic 3 | 0.0386 |
| olive | Topic 3 | 0.0386 |
| herbs | Topic 3 | 0.0386 |
| lemon | Topic 3 | 0.0386 |
| salt | Topic 3 | 0.0385 |
| roast | Topic 3 | 0.0270 |
| chicken | Topic 3 | 0.0270 |
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 40.6% | −1.215 | team, match, striker, league, fans, bake, goal, kept, penalty, goalkeeper |
| 2 | 34.3% | −1.154 | rates, interest, bank, higher, markets, shares, profits, inflation, investors, fell |
| 3 | 25.1% | −0.7381 | garlic, onions, sauce, oil, olive, herbs, lemon, salt, roast, chicken |
- 1 rows have no text and are left out.
- 1 documents have no words left after stop words and frequency limits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec 6f3f7a3a3e8cc6c1
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Documents
TEXT <- "text"
TIME <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c(TEXT, TIME)))
rows <- which(!is.na(df[[TEXT]])) - 1L # documents with text (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))
# %% Topic model
K <- 3
SEED <- 42
alpha <- NULL
if (is.null(alpha)) alpha <- 1 / K
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# Batch variational Bayes from 10 host-drawn starts; the best log-likelihood is kept.
fit <- cs_ml_lda_best(X, K, 50, 20, alpha, eta, SEED, 10)
doc_topic <- cs_ml_shares(fit$gamma)
topic_term <- cs_ml_shares(fit$lambda)
loglik <- fit$loglik
top_terms <- cs_ml_top_terms
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab) # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/lda_three/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
j <- top_terms(topic_term[t, ], 30)
data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))
# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
mean_coherence = if (length(finite)) mean(finite) else NaN,
doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
values[[sprintf("coherence[%d]", t)]] <- coherence[t]
values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
title = "Topic model",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
K, length(rows), length(vocab), vocab[tops[[1]][1]]),
tables = c(list(list(
key = "topics", title = "Topics",
columns = list(list(key = "topic", label = "Topic", type = "integer"),
list(key = "prevalence", label = "Share of text", type = "percent"),
list(key = "coherence", label = "Coherence (UMass)", type = "number"),
list(key = "terms", label = "Top terms")),
rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
terms = paste(vocab[tops[[t]]], collapse = ", ")))
)), extra_tables),
charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
term = cs_col("Term", chart_term, "categorical"),
weight = cs_col("Weight", chart_weight, "numeric")
), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
values = values,
warnings = warnings,
artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
3 topics in 61 documents (85 terms); topic 1 (team, …) is the most common.
To keep this page light, the plots are shown once, under the R tab.
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 40.6% | −1.215 | team, match, striker, league, fans, bake, goal, kept, penalty, goalkeeper |
| 2 | 34.3% | −1.154 | rates, interest, bank, higher, markets, shares, profits, inflation, investors, fell |
| 3 | 25.1% | −0.7381 | garlic, onions, sauce, oil, olive, herbs, lemon, salt, roast, chicken |
- 1 rows have no text and are left out.
- 1 documents have no words left after stop words and frequency limits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec 6f3f7a3a3e8cc6c1
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics
# %% Documents
TEXT = "text"
TIME = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT] if TIME is None else [TEXT, TIME])
rows = np.flatnonzero(df[TEXT].notna().to_numpy()) # documents with text (0-based input rows)
warnings = []
if len(rows) < len(df):
warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")
# %% Topic model
K = 3
SEED = 42
alpha = None or 1.0 / K
eta = None or 1.0 / K
# Batch variational Bayes from 10 host-drawn starts; the best log-likelihood is kept.
gamma, lam, loglik, start = cstext.lda_best(X, K, 50, 20, alpha, eta, SEED, 10)
doc_topic = cstext.shares(gamma)
topic_term = cstext.shares(lam)
top_terms = cstext.top_terms
order = cstext.canonical(doc_topic, topic_term, vocab) # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/lda_three/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)
# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
"n_docs": len(rows),
"n_terms": len(vocab),
"n_topics": K,
"mean_coherence": float(np.mean(finite)) if finite else float("nan"),
"doc_check": csembed.checksum(doc_topic[:, 0], rows),
"loglik": loglik,
}
for t in range(K):
values[f"prevalence[{t + 1}]"] = float(prevalence[t])
values[f"coherence[{t + 1}]"] = coherence[t]
values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
for j in tops[t][:5]:
values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
for j in tops[t]:
chart_topic.append(f"Topic {t + 1}")
chart_term.append(vocab[j])
chart_weight.append(float(topic_term[t, j]))
cs.publish({
"title": "Topic model",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": len(rows),
"summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
"tables": [{
"key": "topics",
"title": "Topics",
"columns": [
{"key": "topic", "label": "Topic", "type": "integer"},
{"key": "prevalence", "label": "Share of text", "type": "percent"},
{"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
{"key": "terms", "label": "Top terms"},
],
"rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
"terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
}] + extra_tables,
"charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
"topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
"term": cs.col("Term", chart_term, "categorical"),
"weight": cs.col("Weight", chart_weight, "numeric"),
}, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
{"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
] + extra_artifacts,
})
On 61 short texts, LDA's three topics lead with team, rates and garlic. PLSA finds the same three themes with a higher training log-likelihood (−852 against −926), as expected from a model with no priors fitting its own documents. Training likelihood rewards overfitting; compare models on held-out text or coherence.
Choosing by coherence on the same corpus suggested 4 topics.
Readiness
Read- LSA (REP041) runs as Prepare's Text to embedding columns step: TF-IDF plus a truncated SVD, frozen into the recipe so SQL, Python and R give the same columns.
- PLSA (REP042) partly runs: Discover → Topic model, method PLSA.
- LDA (REP043) runs: Discover → Topic model, with Choose the number of topics beside it.
Check: LSA, PLSA and LDA
CheckpointCheck yourself
Why are LSA dimensions hard to read as topics?
Show the answer
Answer: a
SVD isn't constrained to non-negative parts. Topic models are.
Check yourself
How does LSA let a query about "automobile" match a document that only says "car"?
Show the answer
Answer: a
Co-occurrence across documents puts "car" and "automobile" on similar directions, so their documents are close in the low-rank space.
Check yourself
In PLSA's E-step, a document's topic mix is , and a word has probability under topic 1 and under topic 2. What is topic 1's responsibility for that word?
Show the answer
Answer: 0.6
and ; normalized, .
Check yourself
Why does PLSA tend to overfit large corpora?
Show the answer
Answer: a
LDA's Dirichlet prior on the mixes is the fix, and it also gives a probability for new documents.
Check yourself
You lower LDA's document–topic prior . What happens to documents' topic mixes?
Show the answer
Answer: a
Small Dirichlet concentration favors sparse mixes. plays the same role for words within topics.
Check yourself
PLSA has a higher training log-likelihood than LDA on the same corpus. Which model is better?
Show the answer
Answer: a
Training fit rewards flexibility. Held-out likelihood, coherence and stability are fairer comparisons.
Recap
Recap- LSA is a truncated SVD of TF-IDF: fast, foldable, signed; a feature step, not topics.
- PLSA mixes word distributions per document; it overfits and can't score new documents cleanly.
- LDA adds Dirichlet priors; compare models on held-out text, not training likelihood.
Concepts in this lesson