Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

Read first

01

LSA: an SVD of the word table

Read

Put documents in rows and words in columns, weight the counts by TF-IDF, and take a truncated SVD: C≈UkΣkVk⊤C \approx U_k \Sigma_k V_k^\top. 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 UkΣkU_k\Sigma_k are document coordinates; rows of VkV_k 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 VkV_k.

In the reference's example, two dimensions leave a residual of norm 6.446, and a new document lands at (3.35, −0.75).

02

Why LSA dimensions aren't topics

Read

SVD 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.

03

PLSA: documents as mixtures

Read

PLSAProbabilistic 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 dd comes from one of KK topics:

P(w∣d)=∑k=1KP(k∣d) P(w∣k).P(w \mid d) = \sum_{k=1}^{K} P(k \mid d)\, P(w \mid k) .

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, P(k∣d,w)∝P(k∣d) P(w∣k)P(k \mid d, w) \propto P(k \mid d)\, P(w \mid k). In the reference's example a word splits 0.571 to 0.429 between two topics.

04

Where PLSA falls short

Read

PLSA learns a separate topic mix P(k∣d)P(k \mid d) 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.
05

LDA: priors on the mixtures

Read

Latent Dirichlet allocation puts Dirichlet priors on both distributions. To write a document, draw its topic mix θd∼Dir(α)\theta_d \sim \text{Dir}(\alpha); each topic's words come from ϕk∼Dir(η)\phi_k \sim \text{Dir}(\eta); for every word, draw a topic from θd\theta_d and a word from that topic.

Collapsed Gibbs sampling reassigns one word's topic at a time:

P(z=k∣rest)∝(ndk+α) nkw+ηnk+Vη.P(z = k \mid \text{rest}) \propto (n_{dk} + \alpha)\, \frac{n_{kw} + \eta}{n_k + V\eta} .

In the reference's example, one word's two topic probabilities come out 0.589 and 0.411. Small α\alpha gives documents few topics; small η\eta gives topics few words.

06

Watch topics form

Explore

AExplorable · 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)?

2
How sure?
50

One sweep reassigns every word's topic once.

3
0.10
0.05
30
sunrainwindcloudbreadsoupsaltpeppergoalteamballcoachTopic 1Topic 2Topic 3
  • 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 first; the figure appears when you commit.

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.

07

Both on one corpus

Read
Topic modelRecorded · Python and R agreeRecorded 2026-11-21 · 30 values compared
R

3 topics in 61 documents (85 terms); topic 1 (team, …) is the most common.

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
teamTopic 10.0634
matchTopic 10.0558
strikerTopic 10.0405
leagueTopic 10.0330
fansTopic 10.0330
bakeTopic 10.0324
goalTopic 10.0254
keptTopic 10.0254
penaltyTopic 10.0254
goalkeeperTopic 10.0254
ratesTopic 20.0852
interestTopic 20.0605
bankTopic 20.0522
higherTopic 20.0521
marketsTopic 20.0440
sharesTopic 20.0440
profitsTopic 20.0440
inflationTopic 20.0440
investorsTopic 20.0357
fellTopic 20.0275
garlicTopic 30.0618
onionsTopic 30.0500
sauceTopic 30.0499
oilTopic 30.0386
oliveTopic 30.0386
herbsTopic 30.0386
lemonTopic 30.0386
saltTopic 30.0385
roastTopic 30.0270
chickenTopic 30.0270

Topics

TopicShare of textCoherence (UMass)Top terms
140.6%−1.215team, match, striker, league, fans, bake, goal, kept, penalty, goalkeeper
234.3%−1.154rates, interest, bank, higher, markets, shares, profits, inflation, investors, fell
325.1%−0.7381garlic, 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)
))
Python

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

TopicShare of textCoherence (UMass)Top terms
140.6%−1.215team, match, striker, league, fans, bake, goal, kept, penalty, goalkeeper
234.3%−1.154rates, interest, bank, higher, markets, shares, profits, inflation, investors, fell
325.1%−0.7381garlic, 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 KK by coherence on the same corpus suggested 4 topics.

08

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.
09

Check: LSA, PLSA and LDA

Checkpoint

Check 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 (0.5,0.5)(0.5, 0.5), and a word has probability 0.30.3 under topic 1 and 0.20.2 under topic 2. What is topic 1's responsibility for that word?

Show the answer

Answer: 0.6

0.5×0.3=0.150.5 \times 0.3 = 0.15 and 0.5×0.2=0.100.5 \times 0.2 = 0.10; normalized, 0.15/0.25=0.60.15 / 0.25 = 0.6.

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 α\alpha. What happens to documents' topic mixes?

Show the answer

Answer: a

Small Dirichlet concentration favors sparse mixes. η\eta 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.

10

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