Skip to content

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.

Applied ~12 min10 steps

What runs in CodeSplash

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
01

Words that travel together

Read

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

02

LDA or NMF?

Read
LDANMF
InputWord countstf-idf weights
IdeaEach document is a probability mixEach document is a sum of parts
FeelSofter, broader topicsOften crisper topics
SpeedSlower, many startsFaster

Both find local optima, and both draw starts from the shared random stream, so Python and R agree.

03

Make a guess

Predict

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

04

What coherence measures

Read

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

05

Read the top words

Explore
Topic termsWhat is each topic about?
View data
topictermP(word | topic)
Topic 1 · pricingprice0.0927
Topic 1 · pricingcheap0.0712
Topic 1 · pricingexpensive0.0538
Topic 1 · pricingvalue0.0399
Topic 1 · pricingdiscount0.0307
Topic 1 · pricingcost0.0222
Topic 1 · pricingdeal0.0192
Topic 1 · pricingmoney0.0160
Topic 1 · pricingworth0.0106
Topic 1 · pricingsale0.0095
Topic 2 · deliverydelivery0.0937
Topic 2 · deliverylate0.0712
Topic 2 · deliveryshipping0.0533
Topic 2 · deliveryarrived0.0383
Topic 2 · deliverydays0.0306
Topic 2 · deliverypackage0.0236
Topic 2 · deliverycourier0.0194
Topic 2 · deliverytracking0.0145
Topic 2 · deliveryweek0.0095
Topic 2 · deliveryfast0.0103
Topic 3 · qualityquality0.0936
Topic 3 · qualitybroke0.0681
Topic 3 · qualitymaterial0.0543
Topic 3 · qualitysturdy0.0382
Topic 3 · qualitycheaply0.0312
Topic 3 · qualityworks0.0240
Topic 3 · qualitybattery0.0194
Topic 3 · qualityscreen0.0134
Topic 3 · qualitybuild0.0126
Topic 3 · qualitydurable0.0069
Topic 4 · servicesupport0.0935
Topic 4 · servicerefund0.0685
Topic 4 · serviceservice0.0511
Topic 4 · serviceemail0.0389
Topic 4 · servicereplied0.0314
Topic 4 · servicehelpful0.0247
Topic 4 · servicestaff0.0201
Topic 4 · servicereturn0.0154
Topic 4 · servicecall0.0120
Topic 4 · servicerude0.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.

06

Read the card

In the app
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,
})

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.

Topics over timeWhich topics are growing or fading?
View data
monthtopictickets
1,704,067,200,000delivery65
1,704,067,200,000pricing74
1,704,067,200,000support42
1,704,067,200,000quality42
1,704,067,200,000returns16
1,706,745,600,000delivery69
1,706,745,600,000pricing84
1,706,745,600,000support39
1,706,745,600,000quality29
1,706,745,600,000returns20
1,709,251,200,000delivery71
1,709,251,200,000pricing85
1,709,251,200,000support43
1,709,251,200,000quality34
1,709,251,200,000returns28
1,711,929,600,000delivery69
1,711,929,600,000pricing76
1,711,929,600,000support52
1,711,929,600,000quality39
1,711,929,600,000returns26
1,714,521,600,000delivery76
1,714,521,600,000pricing75
1,714,521,600,000support56
1,714,521,600,000quality33
1,714,521,600,000returns23
1,717,200,000,000delivery71
1,717,200,000,000pricing69
1,717,200,000,000support52
1,717,200,000,000quality35
1,717,200,000,000returns22
1,719,792,000,000delivery72
1,719,792,000,000pricing67
1,719,792,000,000support58
1,719,792,000,000quality40
1,719,792,000,000returns23
1,722,470,400,000delivery77
1,722,470,400,000pricing68
1,722,470,400,000support42
1,722,470,400,000quality48
1,722,470,400,000returns20
1,725,148,800,000delivery70
1,725,148,800,000pricing69
1,725,148,800,000support46
1,725,148,800,000quality39
1,725,148,800,000returns28
1,727,740,800,000delivery79
1,727,740,800,000pricing70
1,727,740,800,000support40
1,727,740,800,000quality37
1,727,740,800,000returns30
1,730,419,200,000delivery91
1,730,419,200,000pricing67
1,730,419,200,000support28
1,730,419,200,000quality37
1,730,419,200,000returns34
1,733,011,200,000delivery85
1,733,011,200,000pricing65
1,733,011,200,000support45
1,733,011,200,000quality42
1,733,011,200,000returns35

First 60 of 120 rows.

07

Naming topics with AI

Read

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

08

Check your understanding

Checkpoint

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

09

Do it on your own data

In the app

Choose Topics in text, and run Choose the number of topics from Checks first. Then fit a Topic model with the count you pick.

Python
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]])
R
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.

10

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