Skip to content

CDiscover · discover.choose_topics

Choose the number of topics

How many topics does this text support?

Fits a topic model for every number of topics in a range and scores each one by the mean UMass coherence of its top terms (do the top words of a topic actually co-occur in documents?) and the log-likelihood of the word counts. Recommends the most coherent number, with a curve to judge whether neighboring choices are as good. Uses the same NMF, LDA, PLSA and correlated-topic-model twins as the topic model.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called topic coherence, number of topics, choose k topics…

A real result

Example “Corpus nmf”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Choose the number of topicsRecorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

5 topics give the most coherent top terms (mean UMass -0.80) across 2–6 topics.

Recommended topics
5
Coherence (UMass)
−0.7994

Plots

Topic coherence by number of topicsHow many clusters does the data support?

Higher (closer to 0) = top terms co-occur more often in the same documents.

View data
RecommendedTopicsMean coherence (UMass)
false2−1.147
false3−1.000
false4−0.8443
true5−0.7994
false6−0.8164

Scores by number of topics

TopicsMean coherence (UMass)Log-likelihood
2−1.147−1251.98
3−1.000−858.80
4−0.8443−∞
5−0.7994−789.27
6−0.8164−766.00
  • 1 rows have no text and are left out.
Python

5 topics give the most coherent top terms (mean UMass -0.80) across 2–6 topics.

Recommended topics
5
Coherence (UMass)
−0.7994

To keep this page light, the plots are shown once, under the R tab.

Scores by number of topics

TopicsMean coherence (UMass)Log-likelihood
2−1.147−1251.98
3−1.000−858.80
4−0.8443−∞
5−0.7994−789.27
6−0.8164−766.00
  • 1 rows have no text and are left out.

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

  • Corpus nmfml_corpus · text: text
  • Corpus ldaml_corpus · text: text
  • Corpus plsaml_corpus · text: text
  • Corpus ctmml_corpus · text: text
  • Degenerate n1ml_corpus · text: text
  • Degenerate all naml_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
  • Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Textcategorical · 1 column
The free-text column to model.

Choices you make

model

Modeldefault nmf

NMF is fast and sharp; LDA is probabilistic and slower.

  • NMF (tf-idf, matrix factorization)(default) — Fast; good for short texts.
  • LDA (word counts, probabilistic) — Slower; each document is a mixture of topics.
  • PLSA (word counts, EM) — LDA without the priors; fast, but can overfit small corpora.
  • Correlated topic model — Topics may go together; the slowest to compare.
Fewest topicsdefault 2

Smallest number of topics to try.

Most topicsdefault 10

Largest number of topics to try.

Advanced

Iterationsdefault 200

Multiplicative-update passes per fit (NMF and PLSA).

Passesdefault 30

Passes over the corpus per fit (LDA and the correlated topic model).

Random startsdefault 3

Random starts per number of topics; the best log-likelihood is kept.

Document iterations per passdefault 20

Inner variational iterations per document and pass.

preprocess

Minimum documents per worddefault 2

Words in fewer documents are dropped.

Maximum share of documents per worddefault 0.95

Words in more documents than this are dropped as too common.

Vocabulary sizedefault 2000

Keep at most this many of the most frequent words.

options

Top terms scoreddefault 10

Coherence is computed over each topic's top this-many terms.

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.
recommended_k
Represents each document as a mix of topics and each topic as a weighted list of words.
best_coherence
How often a topic's top terms appear together in the same documents; closer to 0 is more coherent.

Per group, level or term: coherence[<k>], loglik[<k>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses scipy; R uses codesplashr.

Default traps between the two languages

  • Uses discover.topics' NMF and LDA twins (same tokenizer, document-term matrix and host-drawn starts) for every number of topics; gensim and ldatuning/textmineR compute coherence over their own models and tokenizations.
Python

The exact script CodeSplash ran for example “Corpus nmf” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Choose the number of topics
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_topics 1.1.0 · spec ce346c2de975f3ce
# 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 numpy as np
import pandas as pd

import codesplash as cs
from codesplash.ml import text as cstext

# %% Documents
TEXT = "text"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())
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, "Choosing the number of topics")
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="Choosing the number of topics", reason="no word appears in enough documents (lower the minimum documents per word)")
K_MIN, K_MAX = 2, 6
if K_MAX <= K_MIN:
    cs.cs_error("CS_E_INVALID_OPTION", option="Most topics", allowed="larger than Fewest topics", value=K_MAX)
SEED = 42
TOP = 10

# %% One model per number of topics
ks = list(range(K_MIN, K_MAX + 1))
coh, ll = [], []
for K in ks:
    W, H = cstext.nmf(cstext.tfidf(X), K, iterations=200, seed=SEED)
    doc_topic, topic_term = cstext.shares(W), cstext.shares(H)
    loglik = cstext.loglik(X, doc_topic, topic_term)
    vals = [cstext.umass(X, cstext.top_terms(topic_term[t], TOP)) for t in range(K)]
    vals = [v for v in vals if not np.isnan(v)]
    coh.append(float(np.mean(vals)) if vals else float("nan"))
    ll.append(float(loglik))
finite = [i for i, c in enumerate(coh) if not np.isnan(c)]
if not finite:
    cs.cs_error("CS_E_UNDEFINED", what="Topic coherence", reason="no topic had two top terms in common documents (lower the minimum documents per word)")
best = max(finite, key=lambda i: (round(coh[i], 10), -i))  # most coherent; ties → fewer topics
values = {"n_docs": len(rows), "n_terms": len(vocab), "recommended_k": ks[best], "best_coherence": coh[best]}
for K, c, l in zip(ks, coh, ll):
    values[f"coherence[{K}]"] = c
    values[f"loglik[{K}]"] = l
cs.publish({
    "title": "Choose the number of topics",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{ks[best]} topics give the most coherent top terms (mean UMass {coh[best]:.2f}) across {K_MIN}–{K_MAX} topics.",
    "statistics": [
        {"key": "recommended_k", "label": "Recommended topics", "value": ks[best], "format": "integer"},
        {"key": "best_coherence", "label": "Coherence (UMass)", "value": coh[best]},
    ],
    "tables": [{
        "key": "scores",
        "title": "Scores by number of topics",
        "columns": [{"key": "k", "label": "Topics", "type": "integer"}, {"key": "coherence", "label": "Mean coherence (UMass)", "type": "number"},
                    {"key": "loglik", "label": "Log-likelihood", "type": "number"}],
        "rows": [{"k": K, "coherence": c, "loglik": l} for K, c, l in zip(ks, coh, ll)],
    }],
    "charts": [cs.chart("coherence", "elbow-plot", "Topic coherence by number of topics", {
        "k": cs.col("Topics", ks, "numeric"),
        "score": cs.col("Mean coherence (UMass)", coh, "numeric"),
        "chosen": cs.col("Recommended", [i == best for i in range(len(ks))], "boolean"),
    }, note="Higher (closer to 0) = top terms co-occur more often in the same documents.")],
    "values": values,
    "warnings": warnings,
})
R

The exact script CodeSplash ran for example “Corpus nmf” · R version 4.5.1 (2025-06-13)

# Choose the number of topics
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_topics 1.1.0 · spec ce346c2de975f3ce
# 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"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = TEXT))
rows <- which(!is.na(df[[TEXT]])) - 1L
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, "Choosing the number of topics")
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 = "Choosing the number of topics", reason = "no word appears in enough documents (lower the minimum documents per word)")
K_MIN <- 2; K_MAX <- 6
if (K_MAX <= K_MIN) cs_error("CS_E_INVALID_OPTION", option = "Most topics", allowed = "larger than Fewest topics", value = K_MAX)
SEED <- 42
TOP <- 10

# %% One model per number of topics
ks <- K_MIN:K_MAX
coh <- numeric(0); ll <- numeric(0)
for (K in ks) {
  f <- cs_ml_nmf(cs_ml_tfidf(X), K, iterations = 200, seed = SEED)
  doc_topic <- cs_ml_shares(f$W); topic_term <- cs_ml_shares(f$H)
  loglik <- cs_ml_loglik(X, doc_topic, topic_term)
  vals <- vapply(seq_len(K), function(t) cs_ml_umass(X, cs_ml_top_terms(topic_term[t, ], TOP)), numeric(1))
  vals <- vals[!is.nan(vals)]
  coh <- c(coh, if (length(vals)) mean(vals) else NaN)
  ll <- c(ll, loglik)
}
finite <- which(!is.nan(coh))
if (!length(finite)) cs_error("CS_E_UNDEFINED", what = "Topic coherence", reason = "no topic had two top terms in common documents (lower the minimum documents per word)")
best <- finite[order(-round(coh[finite], 10), finite)[1]]  # most coherent; ties -> fewer topics
values <- list(n_docs = length(rows), n_terms = length(vocab), recommended_k = ks[best], best_coherence = coh[best])
for (i in seq_along(ks)) {
  values[[sprintf("coherence[%d]", ks[i])]] <- coh[i]
  values[[sprintf("loglik[%d]", ks[i])]] <- ll[i]
}
cs_publish(list(
  title = "Choose the number of topics",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics give the most coherent top terms (mean UMass %.2f) across %d–%d topics.", ks[best], coh[best], K_MIN, K_MAX),
  statistics = list(list(key = "recommended_k", label = "Recommended topics", value = ks[best], format = "integer"),
                    list(key = "best_coherence", label = "Coherence (UMass)", value = coh[best])),
  tables = list(list(key = "scores", title = "Scores by number of topics",
                     columns = list(list(key = "k", label = "Topics", type = "integer"),
                                    list(key = "coherence", label = "Mean coherence (UMass)", type = "number"),
                                    list(key = "loglik", label = "Log-likelihood", type = "number")),
                     rows = lapply(seq_along(ks), function(i) list(k = ks[i], coherence = coh[i], loglik = ll[i])))),
  charts = list(cs_chart("coherence", "elbow-plot", "Topic coherence by number of topics", list(
    k = cs_col("Topics", ks, "numeric"),
    score = cs_col("Mean coherence (UMass)", coh, "numeric"),
    chosen = cs_col("Recommended", seq_along(ks) == best, "boolean")
  ), note = "Higher (closer to 0) = top terms co-occur more often in the same documents.")),
  values = values,
  warnings = warnings
))

Sources

  • Mimno D, Wallach HM, Talley E, Leenders M, McCallum A (2011). Optimizing semantic coherence in topic models. EMNLP 2011, 262–272.
  • Röder M, Both A, Hinneburg A (2015). Exploring the space of topic coherence measures. WSDM 2015, 399–408.

From the CodeSplash method registry · discover.choose_topics v1.1.0.