CDiscover · discover.topics
Topic model
What themes run through a collection of texts?
Topics in a text column: LDA (batch or online variational Bayes), NMF (multiplicative updates), PLSA (EM), the correlated topic model, the hierarchical Dirichlet process (finds the number of topics) or the author-topic model, over a document-term matrix built the same way in both engines (lower-case words, stop words removed, frequency limits). Topic-term weights, each document's topic shares, UMass coherence and the top terms per topic. Starting values come from the shared random stream, so Python and R agree.
A real result
Example “Lda three”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
3 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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Lda threeml_corpus · text: text
- Nmf threeml_corpus · text: text
- Lda by yearml_corpus_dated · text: text · time: year
- Nmf by date binsml_corpus_dated · text: text · time: posted
- Lda priors small vocabml_corpus · text: text
- Plsa threeml_corpus · text: text
- Lda onlineml_corpus · text: text
- Ctm threeml_corpus · text: text
In the guides
Where it sits in the decision guides
- Topic modeling (LDA, NMF, BERTopic) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Textcategorical · 1 column
- The text column; each row is one document.
- Timetemporal / numeric · 0–1 column
- Optional: when each document was written; adds a chart of topic shares over time.
- Authorscategorical · 0–1 column
- Author-topic model only: who wrote each document; separate several authors with a semicolon.
Choices you make
model
- Modeldefault lda
LDA models word counts as topic mixtures; NMF factorizes tf-idf and often gives crisper topics.
- LDA (word counts, probabilistic)(default) — Models documents as mixtures over word counts; pick it for longer documents.
- NMF (tf-idf, matrix factorization) — Factors a tf-idf matrix; pick it for shorter documents or sharper topics.
- PLSA (word counts, EM) — Probabilistic latent semantic analysis: LDA without the priors, fitted by EM; it can overfit small corpora.
- Correlated topic model — Lets topics go together (a document about one topic is likelier to cover a related one); slower than LDA.
- HDP (finds the number of topics) — Hierarchical Dirichlet process: uses as many topics as the text supports, up to Topics.
- Author-topic (needs Authors) — Topics per author instead of per document; each document mixes its authors' topics.
- Topicsdefault 5
Number of topics to find (for HDP, the most it may use). Try a few values; Choose topics compares them.
- Document-topic prior (α)default —
How many topics each document mixes. Smaller values give documents fewer topics. Empty uses the default.
- Topic-word prior (η)default —
How many words each topic spreads over. Smaller values give more focused topics. Empty uses the default.
- Passes over the corpusdefault 50
Passes over the whole corpus when fitting the model.
- Iterationsdefault 200
Iterations when fitting NMF or PLSA.
- Learningdefault batch
Batch uses every document in each update; online updates from small batches, which scales to large corpora.
- Batch(default) — Every pass uses all documents (the default).
- Online (stochastic variational) — Updates after each mini-batch with a shrinking step size (Hoffman, Blei and Bach 2010).
Advanced
- Random startsdefault 10
The fit finds a local optimum; the start with the highest log-likelihood of the word counts is kept.
- Document iterations per passdefault 20
Iterations per document in each pass.
- Documents per batchdefault 128
Documents in each online update, taken in row order.
- Step offset (τ₀)default 10
Larger values make the first online updates smaller.
- Step decay (κ)default 0.7
How fast the online step size shrinks; between 0.5 and 1.
- Document concentration (α₀)default 1
Larger values let each document use more topics.
- Corpus concentration (γ)default 1
Larger values let the corpus use more topics.
preprocess
- Minimum documents per worddefault 2
Ignore words that appear in fewer documents than this.
- Maximum share of documents per worddefault 0.95
Ignore words that appear in more than this share of documents (too common to be informative).
- Vocabulary sizedefault 2000
Largest vocabulary kept, by frequency.
options
- Top terms per topicdefault 10
Words listed for each topic.
What it reports
- n_docs
- How many independent units the analysis used; it sets precision and power.
- n_terms
- How many distinct words a text method kept after lower-casing, removing stop words and dropping words in too few or too many documents.
- n_topics
- How many independent units the analysis used; it sets precision and power.
- mean_coherence
- How often a topic's top terms appear together in the same documents; closer to 0 is more coherent.
- doc_check
- A check number, the row-weighted mean of each text's share of topic 1, used to confirm runs match. Not for interpretation.
- loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
Per group, level or term: prevalence[<topic>], coherence[<topic>], weight[<topic>:<term>], top_term[<topic>], n_periods, share_first[<topic>], share_last[<topic>], truncation, n_authors, topic_corr[<topic>:<topic>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, scipy; R uses codesplashr.
Default traps between the two languages
- Both engines run the same twins (codesplash.ml.text ↔ codesplashr ml_text.R) with shared starting values (LDA keeps the best of several starts by the log-likelihood of the counts); LDA differs only by digamma/matrix-product rounding accumulated over the passes (≪ 1e-6). scikit-learn's LatentDirichletAllocation and topicmodels use their own random starts and stopping rules and are not called.
- The tokenizer keeps letter runs (Python [^\W\d_]+, R \p{L}+), which agree on letters; Python's pattern also keeps non-decimal number characters such as "½", which R drops.
The exact script CodeSplash ran for example “Lda three” · 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,
})
The exact script CodeSplash ran for example “Lda three” · 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)
))
Sources
- Blei DM, Ng AY, Jordan MI (2003). Latent Dirichlet allocation. JMLR 3:993–1022.
- Hoffman M, Bach F, Blei D (2010). Online learning for latent Dirichlet allocation. NeurIPS 23.
- Lee DD, Seung HS (2001). Algorithms for non-negative matrix factorization. NeurIPS 13.
- Mimno D, Wallach H, Talley E, Leenders M, McCallum A (2011). Optimizing semantic coherence in topic models. EMNLP 2011.
- Hofmann T (1999). Probabilistic latent semantic indexing. SIGIR 1999, 50–57.
- Gaussier E, Goutte C (2005). Relation between PLSA and NMF and implications. SIGIR 2005, 601–602.
- Blei DM, Lafferty JD (2007). A correlated topic model of Science. Annals of Applied Statistics 1(1):17–35.
- Teh YW, Jordan MI, Beal MJ, Blei DM (2006). Hierarchical Dirichlet processes. JASA 101(476):1566–1581.
- Wang C, Paisley J, Blei DM (2011). Online variational inference for the hierarchical Dirichlet process. AISTATS 2011.
- Rosen-Zvi M, Griffiths T, Steyvers M, Smyth P (2004). The author-topic model for authors and documents. UAI 2004.
From the CodeSplash method registry · discover.topics v1.2.0.