Topic models for a pile of text
LDA and NMF turn a text column into themes and each document's mix of them. Learn to choose the number of topics, read coherence, and label topics honestly.
What 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 how LDA and NMF represent documents and topics
- Choose a number of topics with UMass coherence and judgment
- Label topics with AI while keeping documents private
Words that travel together
ReadA topic modelTopic modelRepresents each document as a mix of topics and each topic as a weighted list of words. reads word counts, never meaning. A topic is a list of words with weights. A document is a mix of topics. You supply the interpretation when you read the top words.
It has no idea that "refund" and "charged" are about billing. It notices that they occur in the same documents.
Before modeling, the app lower-cases words, removes stop words, and limits the vocabulary. Words in too few or too many documents are dropped, because they can't separate topics.
LDA or NMF?
Read| LDA | NMF | |
|---|---|---|
| Input | Word counts | tf-idf weights |
| Idea | Each document is a probability mix | Each document is a sum of parts |
| Feel | Softer, broader topics | Often crisper topics |
| Speed | Slower, many starts | Faster |
Both find local optima, and both draw starts from the shared random stream, so Python and R agree.
Make a guess
PredictPredict first
A small corpus of 61 documents is scored for 2 to 6 topics with NMF. How many will coherence recommend?
Make your guess between 2 and 6 topics, then reveal.
Reveal
It recommends 5 topics, with a best mean coherence of −0.799. LDA on the same text recommends 4. Models disagree, and neither count is "the" answer.
What coherence measures
ReadUMass coherenceUMass coherenceHow often a topic's top terms appear together in the same documents; closer to 0 is more coherent. asks: do a topic's top words actually occur in the same documents? It's a log ratio, so it's usually negative, and closer to zero means more coherent.
Compare it only within one corpus. The same method across different texts isn't comparable, and small differences between neighboring topic counts rarely mean much.
Here three LDA topics have a mean coherence of −1.04 and three NMF topics −1.00. They differ only a little.
Read the top words
ExploreView data
| topic | term | P(word | topic) |
|---|---|---|
| Topic 1 · pricing | price | 0.0927 |
| Topic 1 · pricing | cheap | 0.0712 |
| Topic 1 · pricing | expensive | 0.0538 |
| Topic 1 · pricing | value | 0.0399 |
| Topic 1 · pricing | discount | 0.0307 |
| Topic 1 · pricing | cost | 0.0222 |
| Topic 1 · pricing | deal | 0.0192 |
| Topic 1 · pricing | money | 0.0160 |
| Topic 1 · pricing | worth | 0.0106 |
| Topic 1 · pricing | sale | 0.0095 |
| Topic 2 · delivery | delivery | 0.0937 |
| Topic 2 · delivery | late | 0.0712 |
| Topic 2 · delivery | shipping | 0.0533 |
| Topic 2 · delivery | arrived | 0.0383 |
| Topic 2 · delivery | days | 0.0306 |
| Topic 2 · delivery | package | 0.0236 |
| Topic 2 · delivery | courier | 0.0194 |
| Topic 2 · delivery | tracking | 0.0145 |
| Topic 2 · delivery | week | 0.0095 |
| Topic 2 · delivery | fast | 0.0103 |
| Topic 3 · quality | quality | 0.0936 |
| Topic 3 · quality | broke | 0.0681 |
| Topic 3 · quality | material | 0.0543 |
| Topic 3 · quality | sturdy | 0.0382 |
| Topic 3 · quality | cheaply | 0.0312 |
| Topic 3 · quality | works | 0.0240 |
| Topic 3 · quality | battery | 0.0194 |
| Topic 3 · quality | screen | 0.0134 |
| Topic 3 · quality | build | 0.0126 |
| Topic 3 · quality | durable | 0.0069 |
| Topic 4 · service | support | 0.0935 |
| Topic 4 · service | refund | 0.0685 |
| Topic 4 · service | service | 0.0511 |
| Topic 4 · service | 0.0389 | |
| Topic 4 · service | replied | 0.0314 |
| Topic 4 · service | helpful | 0.0247 |
| Topic 4 · service | staff | 0.0201 |
| Topic 4 · service | return | 0.0154 |
| Topic 4 · service | call | 0.0120 |
| Topic 4 · service | rude | 0.0104 |
Read the bars for a topic and try to name it in two words. If you can't, that's a useful signal: it may be a blend, in which case you can raise the topic count, or a junk topic of common words, in which case you can tighten the vocabulary limits.
Coherence is a guide. The real test is whether a person can use the topics.
Read the card
In the app3 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,
})
The card lists each topic's top words, its share of the text, and each document's mix. Open a few documents with a high share of one topic and check that they're actually about it. That one step catches most bad topic models.
If your text has dates, topics over time can show which themes rise and fall.
View data
| month | topic | tickets |
|---|---|---|
| 1,704,067,200,000 | delivery | 65 |
| 1,704,067,200,000 | pricing | 74 |
| 1,704,067,200,000 | support | 42 |
| 1,704,067,200,000 | quality | 42 |
| 1,704,067,200,000 | returns | 16 |
| 1,706,745,600,000 | delivery | 69 |
| 1,706,745,600,000 | pricing | 84 |
| 1,706,745,600,000 | support | 39 |
| 1,706,745,600,000 | quality | 29 |
| 1,706,745,600,000 | returns | 20 |
| 1,709,251,200,000 | delivery | 71 |
| 1,709,251,200,000 | pricing | 85 |
| 1,709,251,200,000 | support | 43 |
| 1,709,251,200,000 | quality | 34 |
| 1,709,251,200,000 | returns | 28 |
| 1,711,929,600,000 | delivery | 69 |
| 1,711,929,600,000 | pricing | 76 |
| 1,711,929,600,000 | support | 52 |
| 1,711,929,600,000 | quality | 39 |
| 1,711,929,600,000 | returns | 26 |
| 1,714,521,600,000 | delivery | 76 |
| 1,714,521,600,000 | pricing | 75 |
| 1,714,521,600,000 | support | 56 |
| 1,714,521,600,000 | quality | 33 |
| 1,714,521,600,000 | returns | 23 |
| 1,717,200,000,000 | delivery | 71 |
| 1,717,200,000,000 | pricing | 69 |
| 1,717,200,000,000 | support | 52 |
| 1,717,200,000,000 | quality | 35 |
| 1,717,200,000,000 | returns | 22 |
| 1,719,792,000,000 | delivery | 72 |
| 1,719,792,000,000 | pricing | 67 |
| 1,719,792,000,000 | support | 58 |
| 1,719,792,000,000 | quality | 40 |
| 1,719,792,000,000 | returns | 23 |
| 1,722,470,400,000 | delivery | 77 |
| 1,722,470,400,000 | pricing | 68 |
| 1,722,470,400,000 | support | 42 |
| 1,722,470,400,000 | quality | 48 |
| 1,722,470,400,000 | returns | 20 |
| 1,725,148,800,000 | delivery | 70 |
| 1,725,148,800,000 | pricing | 69 |
| 1,725,148,800,000 | support | 46 |
| 1,725,148,800,000 | quality | 39 |
| 1,725,148,800,000 | returns | 28 |
| 1,727,740,800,000 | delivery | 79 |
| 1,727,740,800,000 | pricing | 70 |
| 1,727,740,800,000 | support | 40 |
| 1,727,740,800,000 | quality | 37 |
| 1,727,740,800,000 | returns | 30 |
| 1,730,419,200,000 | delivery | 91 |
| 1,730,419,200,000 | pricing | 67 |
| 1,730,419,200,000 | support | 28 |
| 1,730,419,200,000 | quality | 37 |
| 1,730,419,200,000 | returns | 34 |
| 1,733,011,200,000 | delivery | 85 |
| 1,733,011,200,000 | pricing | 65 |
| 1,733,011,200,000 | support | 45 |
| 1,733,011,200,000 | quality | 42 |
| 1,733,011,200,000 | returns | 35 |
First 60 of 120 rows.
Naming topics with AI
ReadThe Label topics with AI button suggests names for topics. It's opt-in, and it sends only each topic's share and top words. It never sends documents. Each suggested label has to cite key terms that really are among that topic's top words. If it can't, the label falls back to the three heaviest terms, and it's shown as unverified.
The labels are suggestions, and they stay with the run. Nothing changes in your data.
Check your understanding
CheckpointCheck yourself
What does a topic model understand about your documents?
Show the answer
Answer: b
The interpretation is yours. Models work on counts, so synonyms that never co-occur may land in different topics.
Check yourself
Topic count 4 has a coherence of −1.10, and topic count 5 has −1.12. What's sensible?
Show the answer
Answer: b
A tiny gap isn't a verdict. Choose by whether the topics are useful and whether you can name them.
Check yourself
Several topics lead with the same very common words. What should you try first?
Show the answer
Answer: a
Words found nearly everywhere can't separate topics. max_df removes them, and it's usually cheaper than other changes.
Do it on your own data
In the appChoose Topics in text, and run Choose the number of topics from Checks first. Then fit a Topic model with the count you pick.
import pandas as pd
from sklearn.decomposition import NMF
from sklearn.feature_extraction.text import TfidfVectorizer
docs = pd.read_csv("corpus.csv")["text"]
vec = TfidfVectorizer(stop_words="english", min_df=2, max_df=0.95)
X = vec.fit_transform(docs)
nmf = NMF(n_components=3, init="nndsvda", max_iter=500, random_state=1).fit(X)
terms = vec.get_feature_names_out()
for k, w in enumerate(nmf.components_):
print(k, [terms[i] for i in w.argsort()[::-1][:6]])library(tm)
library(topicmodels)
docs <- read.csv("corpus.csv")$text
corpus <- VCorpus(VectorSource(docs))
dtm <- DocumentTermMatrix(corpus, control = list(
tolower = TRUE, removePunctuation = TRUE, stopwords = TRUE, bounds = list(global = c(2, Inf))
))
fit <- LDA(dtm, k = 3, control = list(seed = 1))
terms(fit, 6)These use each library's own preprocessing, so topics won't match the app's exactly.
Recap
Recap- A topic is a weighted list of words, and a document is a mix of topics.
- Coherence helps, but only a person can tell you whether topics are useful.
- Read the documents behind a topic before you trust its name.
Concepts in this lesson