More topic models: PLSA, correlated topics, HDP, authors and online LDA
Five more ways to find topics in a text column. Learn what each one adds to LDA, when it helps, and what to check before you trust it.
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
- Tell PLSA, the correlated topic model, HDP and the author-topic model apart from LDA
- Read topic correlations and the topics an HDP keeps
- Decide when online LDA is worth using
Read first
One idea, five variations
ReadEvery model here shares LDA's picture: a topicTopic modelRepresents each document as a mix of topics and each topic as a weighted list of words. is a list of word weights, and a document is a mix of topics. They differ in what they assume about the mixes and how they're fitted.
| Model | What it changes | Pick it when |
|---|---|---|
| PLSA | No priors; fitted by EM | You want the plain likelihood fit, on a large corpus |
| Correlated topic model | Topic shares can go together | Themes travel in pairs |
| HDP | Decides the number of topics | You have no idea how many topics there are |
| Author-topic | Topic mixes belong to authors | Each document has known writers |
| Online LDA | Updates from small batches | The corpus is too large for batch passes |
PLSA: LDA without the priors
ReadPLSAProbabilistic 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. fits topic and document distributions by EM. Its updates are the same as NMF with the KL divergence, so it's fast. With no prior pulling documents toward a few topics, it can fit noise in a small corpus. Compare its coherence with LDA's before switching.
3 topics in 61 documents (85 terms); topic 1 (rates, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| rates | Topic 1 | 0.0877 |
| interest | Topic 1 | 0.0614 |
| bank | Topic 1 | 0.0526 |
| higher | Topic 1 | 0.0526 |
| inflation | Topic 1 | 0.0439 |
| markets | Topic 1 | 0.0439 |
| profits | Topic 1 | 0.0439 |
| shares | Topic 1 | 0.0439 |
| bake | Topic 1 | 0.0351 |
| investors | Topic 1 | 0.0351 |
| team | Topic 2 | 0.0976 |
| match | Topic 2 | 0.0854 |
| striker | Topic 2 | 0.0610 |
| fans | Topic 2 | 0.0488 |
| league | Topic 2 | 0.0488 |
| coach | Topic 2 | 0.0366 |
| cup | Topic 2 | 0.0366 |
| final | Topic 2 | 0.0366 |
| goal | Topic 2 | 0.0366 |
| goalkeeper | Topic 2 | 0.0366 |
| garlic | Topic 3 | 0.0862 |
| onions | Topic 3 | 0.0690 |
| sauce | Topic 3 | 0.0690 |
| add | Topic 3 | 0.0517 |
| herbs | Topic 3 | 0.0517 |
| lemon | Topic 3 | 0.0517 |
| oil | Topic 3 | 0.0517 |
| olive | Topic 3 | 0.0517 |
| salt | Topic 3 | 0.0517 |
| simmer | Topic 3 | 0.0517 |
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 44.0% | −1.273 | rates, interest, bank, higher, inflation, markets, profits, shares, bake, investors |
| 2 | 32.2% | −1.150 | team, match, striker, fans, league, coach, cup, final, goal, goalkeeper |
| 3 | 22.1% | −0.8421 | garlic, onions, sauce, add, herbs, lemon, oil, olive, salt, simmer |
- 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 dd1d08d531ad1cde
# 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
# PLSA by EM (KL-NMF multiplicative updates) from 2 host-drawn starts; the best log-likelihood is kept.
fit <- cs_topics_best_of(function(sd) c(cs_topics_plsa(X, K, 100, sd), list(extra = NULL)), X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
top_terms <- cs_topics_top_terms # weights equal to 12 decimals rank in vocabulary order
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/plsa_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 (rates, …) 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 | 44.0% | −1.273 | rates, interest, bank, higher, inflation, markets, profits, shares, bake, investors |
| 2 | 32.2% | −1.150 | team, match, striker, fans, league, coach, cup, final, goal, goalkeeper |
| 3 | 22.1% | −0.8421 | garlic, onions, sauce, add, herbs, lemon, oil, olive, salt, simmer |
- 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 dd1d08d531ad1cde
# 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
# PLSA by EM (KL-NMF multiplicative updates) from 2 host-drawn starts; the best log-likelihood is kept.
doc_topic, topic_term, loglik, start, _ = cstopics.best_of(
lambda sd: cstopics.plsa(X, K, 100, sd) + (None,), X, 2, SEED)
top_terms = cstopics.top_terms # weights equal to 12 decimals rank in vocabulary order
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/plsa_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,
})
HDP: let the text choose the number
ReadThe HDPHierarchical Dirichlet process (HDP) topic modelA topic model that decides how many topics the text supports, up to a maximum, instead of being told. puts a prior on an unlimited set of topics and lets the data decide how many get used. You set the most it may use. Topics holding under 1% of the words are left out, and the card says how many.
6 topics in 61 documents (85 terms); topic 1 (rates, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| rates | Topic 1 | 0.0618 |
| interest | Topic 1 | 0.0435 |
| bank | Topic 1 | 0.0373 |
| higher | Topic 1 | 0.0313 |
| shares | Topic 1 | 0.0313 |
| profits | Topic 1 | 0.0313 |
| garlic | Topic 1 | 0.0313 |
| markets | Topic 1 | 0.0252 |
| investors | Topic 1 | 0.0252 |
| onions | Topic 1 | 0.0251 |
| team | Topic 2 | 0.0743 |
| match | Topic 2 | 0.0684 |
| striker | Topic 2 | 0.0603 |
| fans | Topic 2 | 0.0593 |
| stadium | Topic 2 | 0.0449 |
| penalty | Topic 2 | 0.0449 |
| cup | Topic 2 | 0.0306 |
| final | Topic 2 | 0.0305 |
| leaders | Topic 2 | 0.0305 |
| scored | Topic 2 | 0.0305 |
| bake | Topic 3 | 0.0959 |
| yields | Topic 3 | 0.0650 |
| bond | Topic 3 | 0.0649 |
| bread | Topic 3 | 0.0648 |
| inflation | Topic 3 | 0.0648 |
| let | Topic 3 | 0.0346 |
| minutes | Topic 3 | 0.0344 |
| pasta | Topic 3 | 0.0344 |
| currency | Topic 3 | 0.0343 |
| golden | Topic 3 | 0.0343 |
| rivals | Topic 4 | 0.1030 |
| match | Topic 4 | 0.0550 |
| goal | Topic 4 | 0.0545 |
| late | Topic 4 | 0.0545 |
| ended | Topic 4 | 0.0545 |
| final | Topic 4 | 0.0545 |
| cup | Topic 4 | 0.0545 |
| league | Topic 4 | 0.0542 |
| team | Topic 4 | 0.0535 |
| coach | Topic 4 | 0.0061 |
| minutes | Topic 5 | 0.0719 |
| tomatoes | Topic 5 | 0.0719 |
| add | Topic 5 | 0.0719 |
| simmer | Topic 5 | 0.0719 |
| sauce | Topic 5 | 0.0717 |
| team | Topic 5 | 0.0081 |
| onions | Topic 5 | 0.0081 |
| coach | Topic 5 | 0.0081 |
| match | Topic 5 | 0.0080 |
| salt | Topic 5 | 0.0080 |
| pepper | Topic 6 | 0.0720 |
| sugar | Topic 6 | 0.0720 |
| add | Topic 6 | 0.0719 |
| salt | Topic 6 | 0.0718 |
| sauce | Topic 6 | 0.0717 |
| team | Topic 6 | 0.0080 |
| gently | Topic 6 | 0.0080 |
| coach | Topic 6 | 0.0080 |
| match | Topic 6 | 0.0080 |
| soup | Topic 6 | 0.0080 |
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 57.7% | −1.359 | rates, interest, bank, higher, shares, profits, garlic, markets, investors, onions |
| 2 | 24.2% | −1.109 | team, match, striker, fans, stadium, penalty, cup, final, leaders, scored |
| 3 | 9.9% | −0.7964 | bake, yields, bond, bread, inflation, let, minutes, pasta, currency, golden |
| 4 | 3.3% | −0.5811 | rivals, match, goal, late, ended, final, cup, league, team, coach |
| 5 | 1.6% | −0.7367 | minutes, tomatoes, add, simmer, sauce, team, onions, coach, match, salt |
| 6 | 1.6% | −0.7765 | pepper, sugar, add, salt, sauce, team, gently, coach, match, soup |
- 1 rows have no text and are left out.
- 1 documents have no words left after stop words and frequency limits.
- 2 of the 8 possible topics hold under 1% of the words and are left out.
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 b2dd445350437ce0
# 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 <- 8
SEED <- 42
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# HDP: batch variational inference with at most 8 topics; topics holding under 1% of the words are dropped.
hf <- cs_topics_hdp(X, K, 15, 10, 1, 1, eta, SEED)
kept <- cs_topics_hdp_kept(hf$doc_counts)
if (length(kept) < K) warnings <- c(warnings, sprintf("%d of the %d possible topics hold under 1%% of the words and are left out.", K - length(kept), K))
TRUNCATION <- K
K <- length(kept)
doc_topic <- cs_ml_shares(hf$doc_counts[, kept, drop = FALSE])
topic_term <- cs_ml_shares(hf$lambda[kept, , drop = FALSE])
loglik <- cs_ml_loglik(X, doc_topic, topic_term)
top_terms <- cs_topics_top_terms # weights equal to 12 decimals rank in vocabulary order
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/hdp_up_to_eight/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()
values$truncation <- TRUNCATION
# %% 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)
))
6 topics in 61 documents (85 terms); topic 1 (rates, …) 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 | 57.7% | −1.359 | rates, interest, bank, higher, shares, profits, garlic, markets, investors, onions |
| 2 | 24.2% | −1.109 | team, match, striker, fans, stadium, penalty, cup, final, leaders, scored |
| 3 | 9.9% | −0.7964 | bake, yields, bond, bread, inflation, let, minutes, pasta, currency, golden |
| 4 | 3.3% | −0.5811 | rivals, match, goal, late, ended, final, cup, league, team, coach |
| 5 | 1.6% | −0.7367 | minutes, tomatoes, add, simmer, sauce, team, onions, coach, match, salt |
| 6 | 1.6% | −0.7765 | pepper, sugar, add, salt, sauce, team, gently, coach, match, soup |
- 1 rows have no text and are left out.
- 1 documents have no words left after stop words and frequency limits.
- 2 of the 8 possible topics hold under 1% of the words and are left out.
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 b2dd445350437ce0
# 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 = 8
SEED = 42
eta = None or 1.0 / K
# HDP: batch variational inference with at most 8 topics; topics holding under 1% of the words are dropped.
lam, doc_counts, _, _ = cstopics.hdp(X, K, 15, 10, 1, 1, eta, SEED)
kept = cstopics.hdp_kept(doc_counts)
if len(kept) < K:
warnings.append(f"{K - len(kept)} of the {K} possible topics hold under 1% of the words and are left out.")
TRUNCATION = K
K = len(kept)
doc_topic = cstext.shares(doc_counts[:, kept])
topic_term = cstext.shares(lam[kept])
loglik = cstext.loglik(X, doc_topic, topic_term)
top_terms = cstopics.top_terms # weights equal to 12 decimals rank in vocabulary order
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/hdp_up_to_eight/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 = [], [], []
values["truncation"] = TRUNCATION
# %% 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 a small corpus the count depends on the start, so treat it as a suggestion. Choose topics can then compare nearby counts with LDA or PLSA.
5 topics give the most coherent top terms (mean UMass -0.96) across 2–5 topics.
- Recommended topics
- 5
- Coherence (UMass)
- −0.9574
Plots
Higher (closer to 0) = top terms co-occur more often in the same documents.
View data
| Recommended | Topics | Mean coherence (UMass) |
|---|---|---|
| false | 2 | −1.258 |
| false | 3 | −1.088 |
| false | 4 | −1.073 |
| true | 5 | −0.9574 |
Scores by number of topics
| Topics | Mean coherence (UMass) | Log-likelihood |
|---|---|---|
| 2 | −1.258 | −956.83 |
| 3 | −1.088 | −852.39 |
| 4 | −1.073 | −839.98 |
| 5 | −0.9574 | −777.65 |
- 1 rows have no text and are left out.
The exact R script · R 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 5506f7b6455abeec
# 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 <- 5
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) {
fit <- cs_topics_best_of(function(sd) c(cs_topics_plsa(X, K, 80, sd), list(extra = NULL)), X, 2, SEED)
doc_topic <- fit$doc_topic; topic_term <- fit$topic_term
loglik <- fit$loglik
vals <- vapply(seq_len(K), function(t) cs_ml_umass(X, cs_topics_top_terms(topic_term[t, ], TOP)), numeric(1)) # ties to 12 decimals in vocabulary order
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
))
5 topics give the most coherent top terms (mean UMass -0.96) across 2–5 topics.
- Recommended topics
- 5
- Coherence (UMass)
- −0.9574
To keep this page light, the plots are shown once, under the R tab.
Scores by number of topics
| Topics | Mean coherence (UMass) | Log-likelihood |
|---|---|---|
| 2 | −1.258 | −956.83 |
| 3 | −1.088 | −852.39 |
| 4 | −1.073 | −839.98 |
| 5 | −0.9574 | −777.65 |
- 1 rows have no text and are left out.
The exact Python script · Python 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 5506f7b6455abeec
# 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
from codesplash.ml import topics_ext as cstopics
# %% 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, 5
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:
doc_topic, topic_term, loglik, _, _ = cstopics.best_of(
lambda sd: cstopics.plsa(X, K, 80, sd) + (None,), X, 2, SEED)
vals = [cstext.umass(X, cstopics.top_terms(topic_term[t], TOP)) for t in range(K)] # ties to 12 decimals in vocabulary order
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,
})
Online LDA
ReadOnline LDAOnline LDALDA updated from small batches of documents with a shrinking step size, so it scales to large corpora. updates the topics after each mini-batch of documents, with a step size that shrinks over time. On a small corpus it lands near batch LDA. Its value is on collections too large for many full passes.
3 topics in 61 documents (85 terms); topic 1 (higher, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| higher | Topic 1 | 0.0592 |
| bank | Topic 1 | 0.0590 |
| rates | Topic 1 | 0.0538 |
| profits | Topic 1 | 0.0475 |
| inflation | Topic 1 | 0.0472 |
| fans | Topic 1 | 0.0309 |
| interest | Topic 1 | 0.0297 |
| coach | Topic 1 | 0.0237 |
| team | Topic 1 | 0.0228 |
| bond | Topic 1 | 0.0213 |
| shares | Topic 2 | 0.0457 |
| rates | Topic 2 | 0.0447 |
| interest | Topic 2 | 0.0416 |
| markets | Topic 2 | 0.0405 |
| investors | Topic 2 | 0.0399 |
| team | Topic 2 | 0.0395 |
| match | Topic 2 | 0.0383 |
| striker | Topic 2 | 0.0377 |
| fell | Topic 2 | 0.0290 |
| made | Topic 2 | 0.0254 |
| garlic | Topic 3 | 0.0524 |
| onions | Topic 3 | 0.0422 |
| sauce | Topic 3 | 0.0419 |
| lemon | Topic 3 | 0.0334 |
| add | Topic 3 | 0.0329 |
| olive | Topic 3 | 0.0328 |
| herbs | Topic 3 | 0.0327 |
| oil | Topic 3 | 0.0327 |
| simmer | Topic 3 | 0.0327 |
| bake | Topic 3 | 0.0309 |
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 35.0% | −1.296 | higher, bank, rates, profits, inflation, fans, interest, coach, team, bond |
| 2 | 34.6% | −1.392 | shares, rates, interest, markets, investors, team, match, striker, fell, made |
| 3 | 30.5% | −0.9037 | garlic, onions, sauce, lemon, add, olive, herbs, oil, simmer, bake |
- 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 b02ad770d34d7157
# 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
# Online variational Bayes (mini-batches of 16 documents in row order) from 2 host-drawn starts.
fit <- cs_topics_best_of(function(sd) {
f <- cs_topics_lda_online(X, K, 10, 20, alpha, eta, sd, 16, 10, 0.7)
list(doc_topic = cs_ml_shares(f$gamma), topic_term = cs_ml_shares(f$lambda), extra = NULL)
}, X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
top_terms <- cs_topics_top_terms # weights equal to 12 decimals rank in vocabulary order
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_online/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 (higher, …) 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 | 35.0% | −1.296 | higher, bank, rates, profits, inflation, fans, interest, coach, team, bond |
| 2 | 34.6% | −1.392 | shares, rates, interest, markets, investors, team, match, striker, fell, made |
| 3 | 30.5% | −0.9037 | garlic, onions, sauce, lemon, add, olive, herbs, oil, simmer, bake |
- 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 b02ad770d34d7157
# 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
# Online variational Bayes (mini-batches of 16 documents in row order) from 2 host-drawn starts.
doc_topic, topic_term, loglik, start, _ = cstopics.best_of(lambda sd: tuple(cstext.shares(m) for m in cstopics.lda_online(
X, K, 10, 20, alpha, eta, sd, 16, 10, 0.7)) + (None,), X, 2, SEED)
top_terms = cstopics.top_terms # weights equal to 12 decimals rank in vocabulary order
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_online/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,
})
Check your understanding
CheckpointCheck yourself
An HDP with a limit of 20 topics reports 6. What does that mean?
Show the answer
Answer: b
The HDP's count is a fitted quantity that depends on the start and the priors, not a proof. Check nearby counts with Choose topics.
Check yourself
In a correlated topic model, topics 2 and 5 have a correlation of 0.6. What's the safe reading?
Show the answer
Answer: a
The correlation is across documents' topic shares. It describes co-occurrence in this corpus, not cause or word overlap.
Check yourself
PLSA and LDA give similar topics on a large corpus but PLSA's are noisier on 200 short documents. Why?
Show the answer
Answer: b
LDA's Dirichlet priors pull documents toward few topics and topics toward focused words. That regularization matters most on small collections.
Check yourself
An author with a single short document gets a main topic share of 95%. How much should you trust it?
Show the answer
Answer: b
An author's mix is estimated from that author's words only. Check the Documents column before reading a writer's profile.
Recap
Read- PLSA drops the priors; the correlated topic model lets topics go together; HDP picks the number of topics; the author-topic model gives mixes to authors; online LDA updates from batches.
- Correlations describe co-occurrence across documents, not causes.
- An HDP count and a single-document author profile are both weak evidence on small data.
Concepts in this lesson