Richer topic models: correlated, open-ended, changing, authored, nested
LDA treats topics as unrelated, fixed in number, constant in time, ignorant of authors and flat. Five extensions lift one assumption each - CTM, HDP, the dynamic topic model, the author-topic model and pachinko allocation.
What runs in CodeSplash
- REP044Correlated topic model (CTM) Partly runs in CodeSplash
- REP045Hierarchical Dirichlet process topic model Partly runs in CodeSplash
- REP046Dynamic topic model Runs in CodeSplash (Experimental)
- REP047Author-topic model Partly runs in CodeSplash
- REP048Pachinko allocation model (PAM) Runs as a notebook
- Topic model Verified in Python and R
- Dynamic topic model Experimental
You will be able to
- Say which LDA assumption each extension relaxes and what new parameter it introduces
- Read topic correlations, the number of topics HDP keeps, and topic drift over time
- Explain the pitfalls each extension adds, such as weakly supported correlations and time bins that look like drift
Five assumptions, five fixes
Read| LDA assumes | Extension | Relaxed by |
|---|---|---|
| topics occur independently | CTMCorrelated topic model (CTM)A topic model whose topic shares are logistic-normal, so topics can go together or exclude each other across documents. | a logistic-normal prior with a covariance |
| a fixed number of topics | HDPHierarchical Dirichlet process (HDP) topic modelA topic model that decides how many topics the text supports, up to a maximum, instead of being told. | a Dirichlet process over topics |
| topics never change | Dynamic topicsDynamic topic modelTopics whose word weights drift between periods as a random walk; each document mixes topics. | word weights that drift per period |
| documents choose their own mix | Author-topicAuthor-topic modelTopics per author: each word comes from one of the document's authors and that author's topic mix. | mixes that belong to authors |
| topics are flat | Pachinko allocationPachinko allocation modelA topic model where words reach topics through a network of supertopics and subtopics, so groups of topics can occur together. | a network of supertopics |
Each fix adds flexibility and a new way to fool yourself.
CTM: topics that go together
ReadA Dirichlet can't say "documents about finance often also discuss politics". The correlated topic model draws and sets , so carries correlations between topics.
3 topics in 61 documents (85 terms); topic 1 (team, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| team | Topic 1 | 0.0543 |
| match | Topic 1 | 0.0478 |
| striker | Topic 1 | 0.0346 |
| garlic | Topic 1 | 0.0346 |
| league | Topic 1 | 0.0281 |
| fans | Topic 1 | 0.0281 |
| onions | Topic 1 | 0.0252 |
| goal | Topic 1 | 0.0216 |
| oil | Topic 1 | 0.0216 |
| olive | Topic 1 | 0.0216 |
| rates | Topic 2 | 0.0983 |
| interest | Topic 2 | 0.0710 |
| bank | Topic 2 | 0.0603 |
| markets | Topic 2 | 0.0515 |
| inflation | Topic 2 | 0.0511 |
| investors | Topic 2 | 0.0418 |
| higher | Topic 2 | 0.0362 |
| shares | Topic 2 | 0.0325 |
| fell | Topic 2 | 0.0321 |
| stock | Topic 2 | 0.0320 |
| profits | Topic 3 | 0.0594 |
| bake | Topic 3 | 0.0493 |
| sauce | Topic 3 | 0.0462 |
| salt | Topic 3 | 0.0386 |
| add | Topic 3 | 0.0284 |
| company | Topic 3 | 0.0279 |
| simmer | Topic 3 | 0.0276 |
| pepper | Topic 3 | 0.0271 |
| soup | Topic 3 | 0.0271 |
| serve | Topic 3 | 0.0270 |
Correlation of the topics' centered log-ratio shares across documents: positive pairs tend to appear in the same documents.
View data
| Topic 1 | Topic 2 | Topic 3 |
|---|---|---|
| 2.416 | −1.571 | −0.8457 |
| 2.142 | −1.419 | −0.7236 |
| 2.294 | −1.506 | −0.7876 |
| 2.086 | −1.343 | −0.7430 |
| 2.142 | −1.419 | −0.7233 |
| 2.230 | −1.468 | −0.7619 |
| 2.139 | −1.418 | −0.7216 |
| 2.027 | −1.354 | −0.6731 |
| 2.026 | −1.350 | −0.6759 |
| 2.034 | −1.356 | −0.6770 |
| 2.145 | −1.417 | −0.7280 |
| 2.294 | −1.506 | −0.7883 |
| 2.044 | −1.360 | −0.6844 |
| 2.237 | −1.470 | −0.7666 |
| 1.638 | −1.262 | −0.3757 |
| 1.752 | −1.318 | −0.4338 |
| 2.139 | −1.415 | −0.7241 |
| 2.174 | −1.471 | −0.7031 |
| 1.673 | −1.133 | −0.5401 |
| 2.212 | −1.462 | −0.7496 |
| 2.289 | −1.509 | −0.7795 |
| 0.2896 | −2.062 | 1.772 |
| 0.4289 | −2.004 | 1.575 |
| 1.829 | −1.538 | −0.2907 |
| 2.253 | −1.525 | −0.7287 |
| 1.574 | −1.590 | 0.0161 |
| 0.5970 | −1.881 | 1.284 |
| 1.696 | −1.326 | −0.3698 |
| 0.6897 | −1.942 | 1.252 |
| 0.4610 | −2.001 | 1.540 |
| 2.028 | −1.454 | −0.5741 |
| 0.9788 | −1.797 | 0.8184 |
| −0.0059 | 1.421 | −1.416 |
| 0.5965 | −1.745 | 1.148 |
| 1.718 | −1.078 | −0.6396 |
| 0.3849 | −2.079 | 1.694 |
| 2.225 | −1.467 | −0.7586 |
| 0.3313 | −2.075 | 1.744 |
| 0.5602 | −1.893 | 1.333 |
| 2.251 | −1.522 | −0.7286 |
| −0.1903 | 2.068 | −1.877 |
| −0.1367 | 1.938 | −1.802 |
| −0.0487 | 1.758 | −1.710 |
| 0.1972 | −2.024 | 1.826 |
| −0.1325 | 1.967 | −1.835 |
| −0.0728 | 1.839 | −1.766 |
| 0.4052 | −1.688 | 1.283 |
| 0.8789 | 0.5847 | −1.464 |
| 0.4484 | −0.1501 | −0.2983 |
| −0.1311 | 1.947 | −1.816 |
| −0.2437 | 2.156 | −1.912 |
| 0.1716 | 1.329 | −1.500 |
| −0.0544 | 1.751 | −1.697 |
| −0.3260 | 0.2102 | 0.1158 |
| −0.0605 | 1.662 | −1.602 |
| 0.0140 | 1.661 | −1.675 |
| −0.0614 | 1.821 | −1.760 |
| −0.1249 | 1.875 | −1.750 |
| 0.2639 | −1.952 | 1.688 |
| −0.0609 | 1.775 | −1.714 |
First 60 of 61 rows.
Topics
| Topic | Share of text | Coherence (UMass) | Top terms |
|---|---|---|---|
| 1 | 55.4% | −1.310 | team, match, striker, garlic, league, fans, onions, goal, oil, olive |
| 2 | 24.6% | −1.124 | rates, interest, bank, markets, inflation, investors, higher, shares, fell, stock |
| 3 | 20.0% | −1.018 | profits, bake, sauce, salt, add, company, simmer, pepper, soup, serve |
Topic correlations
| Topic | With topic | Correlation (centered log-ratio) |
|---|---|---|
| 1 | 2 | −0.6493 |
| 1 | 3 | −0.0110 |
| 2 | 3 | −0.7533 |
- 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 8c765cbff4751af5
# 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
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# Correlated topic model: variational EM, 10 passes from a host-drawn start.
ctm_fit <- cs_topics_ctm(X, K, 10, 10, eta, SEED)
doc_topic <- ctm_fit$doc_topic
topic_term <- ctm_fit$topic_term
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/ctm_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()
corr <- cs_topics_clr_correlations(doc_topic)
for (i in seq_len(K)) for (j in seq_len(K)) if (j > i) values[[sprintf("topic_corr[%d:%d]", i, j)]] <- corr[i, j]
Lg <- log(pmax(doc_topic, 1e-300))
clr <- Lg - rowMeans(Lg)
extra_charts <- list(cs_chart("correlations", "corr-heatmap", "How topics go together across documents",
list(vars = lapply(seq_len(K), function(t) cs_col(paste("Topic", t), clr[, t], "numeric"))),
note = "Correlation of the topics' centered log-ratio shares across documents: positive pairs tend to appear in the same documents."))
pairs <- do.call(rbind, lapply(seq_len(K), function(i) if (i < K) cbind(i, (i + 1):K)))
extra_tables <- list(list(
key = "correlations", title = "Topic correlations",
columns = list(list(key = "a", label = "Topic", type = "integer"), list(key = "b", label = "With topic", type = "integer"),
list(key = "r", label = "Correlation (centered log-ratio)", type = "number")),
rows = lapply(seq_len(nrow(pairs)), function(r) list(a = pairs[r, 1], b = pairs[r, 2], r = corr[pairs[r, 1], pairs[r, 2]]))
))
# %% 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 | 55.4% | −1.310 | team, match, striker, garlic, league, fans, onions, goal, oil, olive |
| 2 | 24.6% | −1.124 | rates, interest, bank, markets, inflation, investors, higher, shares, fell, stock |
| 3 | 20.0% | −1.018 | profits, bake, sauce, salt, add, company, simmer, pepper, soup, serve |
Topic correlations
| Topic | With topic | Correlation (centered log-ratio) |
|---|---|---|
| 1 | 2 | −0.6493 |
| 1 | 3 | −0.0110 |
| 2 | 3 | −0.7533 |
- 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 8c765cbff4751af5
# 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
eta = None or 1.0 / K
# Correlated topic model: variational EM, 10 passes from a host-drawn start.
ctm_fit = cstopics.ctm(X, K, 10, 10, eta, SEED)
doc_topic, topic_term = ctm_fit["doc_topic"], ctm_fit["topic_term"]
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/ctm_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 = [], [], []
corr = cstopics.clr_correlations(doc_topic)
for i in range(K):
for j in range(i + 1, K):
values[f"topic_corr[{i + 1}:{j + 1}]"] = float(corr[i, j])
L = np.log(np.maximum(doc_topic, 1e-300))
clr = L - L.mean(axis=1)[:, None]
extra_charts.append(cs.chart("correlations", "corr-heatmap", "How topics go together across documents",
{"vars": [cs.col(f"Topic {t + 1}", clr[:, t].tolist(), "numeric") for t in range(K)]},
note="Correlation of the topics' centered log-ratio shares across documents: positive pairs tend to appear in the same documents."))
extra_tables.append({
"key": "correlations",
"title": "Topic correlations",
"columns": [{"key": "a", "label": "Topic", "type": "integer"}, {"key": "b", "label": "With topic", "type": "integer"},
{"key": "r", "label": "Correlation (centered log-ratio)", "type": "number"}],
"rows": [{"a": i + 1, "b": j + 1, "r": float(corr[i, j])} for i in range(K) for j in range(i + 1, K)],
})
# %% 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,
})
Here topics 1 and 2 correlate at −0.65 and topics 2 and 3 at −0.75: documents tend to be about one theme, not several. Inference is harder than for LDA, and correlations supported by few documents are unstable.
HDP: let the data set the number
ReadThe hierarchical Dirichlet process places a Dirichlet process prior over topics: a shared, potentially unlimited pool, which every document draws from. In practice a truncation caps the pool, and the model uses as many topics as the text supports.
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,
})
With up to 8 topics allowed, it kept 6, the largest covering 58% of the text. "Nonparametric" doesn't mean free of tuning: the count depends on concentration parameters and corpus size, and tiny topics can be noise.
Predict
PredictPredict first
HDP may use up to 8 topics on a small corpus of sports, finance and cooking texts. How many will it keep?
Reveal
Fewer than 8. The Dirichlet process lets unused topics fade, so it settles where the text stops supporting new themes. It can't exceed the cap you set.
Dynamic topics: drift over time
ReadThe dynamic topic model lets each topic's word weights wander from one period to the next, , mapped to probabilities by softmax. A topic keeps its identity while its vocabulary shifts.
3 topics in 61 documents over 7 periods; topic 1 (league, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| league | Topic 1 | 0.0418 |
| bake | Topic 1 | 0.0418 |
| fans | Topic 1 | 0.0416 |
| match | Topic 1 | 0.0413 |
| team | Topic 1 | 0.0397 |
| sauce | Topic 1 | 0.0329 |
| profits | Topic 1 | 0.0314 |
| stadium | Topic 1 | 0.0311 |
| coach | Topic 1 | 0.0311 |
| final | Topic 1 | 0.0286 |
| rates | Topic 2 | 0.1154 |
| interest | Topic 2 | 0.0808 |
| bank | Topic 2 | 0.0692 |
| inflation | Topic 2 | 0.0571 |
| higher | Topic 2 | 0.0463 |
| markets | Topic 2 | 0.0458 |
| bond | Topic 2 | 0.0334 |
| fell | Topic 2 | 0.0322 |
| lemon | Topic 2 | 0.0315 |
| simmer | Topic 2 | 0.0221 |
| striker | Topic 3 | 0.0578 |
| team | Topic 3 | 0.0476 |
| garlic | Topic 3 | 0.0449 |
| match | Topic 3 | 0.0345 |
| kept | Topic 3 | 0.0339 |
| made | Topic 3 | 0.0337 |
| home | Topic 3 | 0.0337 |
| olive | Topic 3 | 0.0335 |
| oil | Topic 3 | 0.0334 |
| shares | Topic 3 | 0.0333 |
View data
| year | Topic | Documents (topic shares summed) |
|---|---|---|
| 2,018 | Topic 1 | 0.1750 |
| 2,018 | Topic 2 | 2.282 |
| 2,018 | Topic 3 | 0.5429 |
| 2,019 | Topic 1 | 1.981 |
| 2,019 | Topic 2 | 2.966 |
| 2,019 | Topic 3 | 1.053 |
| 2,020 | Topic 1 | 3.497 |
| 2,020 | Topic 2 | 4.917 |
| 2,020 | Topic 3 | 5.586 |
| 2,021 | Topic 1 | 5.981 |
| 2,021 | Topic 2 | 6.124 |
| 2,021 | Topic 3 | 3.896 |
| 2,022 | Topic 1 | 6.440 |
| 2,022 | Topic 2 | 2.791 |
| 2,022 | Topic 3 | 4.769 |
| 2,023 | Topic 1 | 3.593 |
| 2,023 | Topic 2 | 0.4776 |
| 2,023 | Topic 3 | 1.930 |
| 2,024 | Topic 1 | 0.6865 |
| 2,024 | Topic 2 | 0.2245 |
| 2,024 | Topic 3 | 1.089 |
Topics
| Topic | Share of text | Coherence (UMass) | Drift, first → last period | Top terms (all periods) |
|---|---|---|---|---|
| 1 | 36.6% | −1.269 | 0.4% | league, bake, fans, match, team, sauce, profits, stadium, coach, final |
| 2 | 32.4% | −1.283 | 0.5% | rates, interest, bank, inflation, higher, markets, bond, fell, lemon, simmer |
| 3 | 30.9% | −1.254 | 0.5% | striker, team, garlic, match, kept, made, home, olive, oil, shares |
Top terms in the first and last periods
| Topic | First period | Last period |
|---|---|---|
| 1 | bake, league, fans, match, team | league, fans, match, bake, team |
| 2 | rates, interest, bank, inflation, markets | rates, interest, bank, inflation, higher |
| 3 | striker, team, garlic, match, shares | striker, team, garlic, kept, match |
- 1 rows have no text or no year 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)
# Dynamic topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.dynamic_topics 1.0.0 · spec 74118944601eb45a
# Dataset: ml_corpus_dated (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Documents and periods
TEXT <- "text"
TIME <- "year"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus_dated.parquet", col_select = c(TEXT, TIME)))
cs_check_finite_columns(df, c(TIME))
.t <- df[[TIME]]
t_all <- suppressWarnings(as.numeric(.t))
rows <- which(!is.na(df[[TEXT]]) & !is.na(t_all)) - 1L # documents with text and a time (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text or no %s and are left out.", nrow(df) - length(rows), TIME))
cs_check_rows(length(rows), 2, "A dynamic 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 dynamic 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))
sl <- cs_dtm_slices(t_all[rows + 1L]) # every distinct time up to 12, else 10 equal-width periods
period <- sl$slice
labels <- sl$labels
S <- length(labels)
if (S < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = TIME, min = 2, k = S)
# %% Dynamic topic model
K <- 3
SEED <- 42
alpha <- NULL
if (is.null(alpha)) alpha <- 1 / K
# Variational EM: documents under their period's topics, then 20 majorize-maximize steps per topic path.
fit <- cs_dtm_fit(X, period, S, K, 10, 20, alpha, 0.005, SEED, 20)
doc_topic <- cs_ml_shares(fit$gamma)
beta <- fit$beta
V <- length(vocab)
overall <- matrix(0, K, V)
for (s in seq_len(S)) overall <- overall + matrix(beta[s, , ], K, V)
overall <- overall / S # topic-term weights averaged over periods
ord <- cs_ml_canonical_topics(doc_topic, overall, vocab) # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
beta <- beta[, ord, , drop = FALSE]
overall <- overall[ord, , drop = FALSE]
loglik <- cs_dtm_loglik(X, period, doc_topic, beta)
TOP <- 10
bt <- function(s, t) as.vector(beta[s, t, ])
tops <- lapply(seq_len(K), function(t) cs_topics_top_terms(overall[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))
first <- lapply(seq_len(K), function(t) cs_topics_top_terms(bt(1, t), TOP))
last <- lapply(seq_len(K), function(t) cs_topics_top_terms(bt(S, t), TOP))
drift <- vapply(seq_len(K), function(t) 0.5 * sum(abs(bt(S, t) - bt(1, t))), numeric(1)) # total variation, first -> last period
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-88877/discover.dynamic_topics/years_three/out-r")
topics <- data.frame(row = as.integer(rows), period = as.integer(period) + 1L)
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(S), function(s) do.call(rbind, lapply(seq_len(K), function(t) {
j <- cs_topics_top_terms(bt(s, t), 30)
data.frame(period = s, topic = t, term = vocab[j], weight = bt(s, t)[j], rank = seq_along(j))
}))))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))
# %% Result
prevalence <- colMeans(doc_topic)
weight <- t(vapply(seq_len(S), function(s) colSums(doc_topic[period == s - 1L, , drop = FALSE]), numeric(K))) # periods x topics
if (K == 1) weight <- t(weight)
share <- weight / rowSums(weight)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = V, n_topics = K, n_periods = S,
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]]
values[[sprintf("top_term_first[%d]", t)]] <- vocab[first[[t]][1]]
values[[sprintf("top_term_last[%d]", t)]] <- vocab[last[[t]][1]]
values[[sprintf("drift[%d]", t)]] <- drift[t]
values[[sprintf("share_first[%d]", t)]] <- share[1, t]
values[[sprintf("share_last[%d]", t)]] <- share[S, t]
for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- overall[t, j]
}
names_k <- paste("Topic", seq_len(K))
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(names_k[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) overall[t, tops[[t]]]))
TIME_KIND <- "numeric"
cs_publish(list(
title = "Dynamic topic model",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = sprintf("%d topics in %d documents over %d periods; topic 1 (%s, …) is the most common.",
K, length(rows), S, vocab[tops[[1]][1]]),
tables = 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 = "drift", label = "Drift, first → last period", type = "percent"),
list(key = "terms", label = "Top terms (all periods)")),
rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t], drift = drift[t],
terms = paste(vocab[tops[[t]]], collapse = ", ")))
), list(
key = "change", title = "Top terms in the first and last periods",
columns = list(list(key = "topic", label = "Topic", type = "integer"),
list(key = "first", label = "First period"),
list(key = "last", label = "Last period")),
rows = lapply(seq_len(K), function(t) list(topic = t, first = paste(vocab[utils::head(first[[t]], 5)], collapse = ", "),
last = paste(vocab[utils::head(last[[t]], 5)], collapse = ", ")))
)),
charts = list(
cs_chart("terms", "topic-terms", "Top terms per topic (all periods)", list(
topic = cs_col("Topic", chart_topic, "categorical", names_k),
term = cs_col("Term", chart_term, "categorical"),
weight = cs_col("Weight", chart_weight, "numeric")
), controls = list(top = TOP)),
cs_chart("over-time", "topics-over-time", sprintf("Topics over %s", TIME), list(
time = cs_col(TIME, rep(labels, each = K), TIME_KIND),
topic = cs_col("Topic", rep(names_k, times = S), "categorical", names_k),
weight = cs_col("Documents (topic shares summed)", as.vector(t(weight)), "numeric")
), controls = list(top = K))
),
values = values,
warnings = warnings,
artifacts = list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet"))
))
3 topics in 61 documents over 7 periods; topic 1 (league, …) 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) | Drift, first → last period | Top terms (all periods) |
|---|---|---|---|---|
| 1 | 36.6% | −1.269 | 0.4% | league, bake, fans, match, team, sauce, profits, stadium, coach, final |
| 2 | 32.4% | −1.283 | 0.5% | rates, interest, bank, inflation, higher, markets, bond, fell, lemon, simmer |
| 3 | 30.9% | −1.254 | 0.5% | striker, team, garlic, match, kept, made, home, olive, oil, shares |
Top terms in the first and last periods
| Topic | First period | Last period |
|---|---|---|
| 1 | bake, league, fans, match, team | league, fans, match, bake, team |
| 2 | rates, interest, bank, inflation, markets | rates, interest, bank, inflation, higher |
| 3 | striker, team, garlic, match, shares | striker, team, garlic, kept, match |
- 1 rows have no text or no year 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
# Dynamic topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.dynamic_topics 1.0.0 · spec 74118944601eb45a
# Dataset: ml_corpus_dated (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_dynamic as csdtm
from codesplash.ml import topics_ext as cstopics
# %% Documents and periods
TEXT = "text"
TIME = "year"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus_dated.parquet", columns=[TEXT, TIME])
cs.check_finite_columns(df, [TIME])
t_all = pd.to_numeric(df[TIME], errors="coerce").to_numpy(dtype=float)
rows = np.flatnonzero(df[TEXT].notna().to_numpy() & ~np.isnan(t_all)) # documents with text and a time (0-based input rows)
warnings = []
if len(rows) < len(df):
warnings.append(f"{len(df) - len(rows)} rows have no text or no {TIME} and are left out.")
cs.check_rows(len(rows), 2, "A dynamic 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 dynamic 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.")
period, labels = csdtm.slices(t_all[rows]) # every distinct time up to 12, else 10 equal-width periods
S = len(labels)
if S < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=TIME, min=2, k=S)
# %% Dynamic topic model
K = 3
SEED = 42
alpha = None or 1.0 / K
# Variational EM: documents under their period's topics, then 20 majorize-maximize steps per topic path.
gamma, beta = csdtm.dtm(X, period, S, K, 10, 20, alpha, 0.005, SEED, 20)
doc_topic = cstext.shares(gamma)
overall = beta.mean(axis=0) # topic-term weights averaged over periods
order = cstext.canonical(doc_topic, overall, vocab) # topics by prevalence
doc_topic = doc_topic[:, order]
beta = beta[:, order, :]
overall = overall[order]
loglik = csdtm.loglik(X, period, doc_topic, beta)
TOP = 10
tops = [cstopics.top_terms(overall[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]
first = [cstopics.top_terms(beta[0, t], TOP) for t in range(K)]
last = [cstopics.top_terms(beta[-1, t], TOP) for t in range(K)]
drift = [0.5 * float(np.abs(beta[-1, t] - beta[0, t]).sum()) for t in range(K)] # total variation, first → last period
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-88877/discover.dynamic_topics/years_three/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64), "period": period.astype(np.int64) + 1})
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 s in range(S):
for t in range(K):
for rank, j in enumerate(cstopics.top_terms(beta[s, t], 30), start=1):
term_rows.append({"period": s + 1, "topic": t + 1, "term": vocab[j], "weight": float(beta[s, 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)
weight = np.array([doc_topic[period == s].sum(axis=0) for s in range(S)]) # periods × topics
share = weight / weight.sum(axis=1, keepdims=True)
finite = [c for c in coherence if not np.isnan(c)]
values = {
"n_docs": len(rows),
"n_terms": len(vocab),
"n_topics": K,
"n_periods": S,
"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]]
values[f"top_term_first[{t + 1}]"] = vocab[first[t][0]]
values[f"top_term_last[{t + 1}]"] = vocab[last[t][0]]
values[f"drift[{t + 1}]"] = drift[t]
values[f"share_first[{t + 1}]"] = float(share[0, t])
values[f"share_last[{t + 1}]"] = float(share[-1, t])
for j in tops[t][:5]:
values[f"weight[{t + 1}:{vocab[j]}]"] = float(overall[t, j])
names = [f"Topic {t + 1}" for t in range(K)]
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
for j in tops[t]:
chart_topic.append(names[t])
chart_term.append(vocab[j])
chart_weight.append(float(overall[t, j]))
TIME_KIND = "numeric"
cs.publish({
"title": "Dynamic topic model",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": len(rows),
"summary": f"{K} topics in {len(rows)} documents over {S} periods; 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": "drift", "label": "Drift, first → last period", "type": "percent"},
{"key": "terms", "label": "Top terms (all periods)"},
],
"rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t], "drift": drift[t],
"terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
}, {
"key": "change",
"title": "Top terms in the first and last periods",
"columns": [
{"key": "topic", "label": "Topic", "type": "integer"},
{"key": "first", "label": "First period"},
{"key": "last", "label": "Last period"},
],
"rows": [{"topic": t + 1, "first": ", ".join(vocab[j] for j in first[t][:5]),
"last": ", ".join(vocab[j] for j in last[t][:5])} for t in range(K)],
}],
"charts": [
cs.chart("terms", "topic-terms", "Top terms per topic (all periods)", {
"topic": cs.col("Topic", chart_topic, "categorical", names),
"term": cs.col("Term", chart_term, "categorical"),
"weight": cs.col("Weight", chart_weight, "numeric"),
}, controls={"top": TOP}),
cs.chart("over-time", "topics-over-time", f"Topics over {TIME}", {
"time": cs.col(TIME, [float(p) for p in labels for _ in range(K)], TIME_KIND),
"topic": cs.col("Topic", [n for _ in labels for n in names], "categorical", names),
"weight": cs.col("Documents (topic shares summed)", weight.ravel().tolist(), "numeric"),
}, controls={"top": K}),
],
"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"},
],
})
Over 7 periods, topic 2's share of the text fell from 76% to 11%, while its driftTopic driftHow much of a topic's word weight moved between the first and last periods (total variation, 0 to 100%). in vocabulary was only 0.5%. Sparse periods, sudden events and changing sources can all mimic drift.
Pachinko allocation: nested topics
ReadPachinko allocation routes each word through a network: a document picks a supertopic, the supertopic picks a subtopic, the subtopic picks a word. Summing over paths gives the word's probability:
In the reference's small example, mixing two supertopics over two subtopics gives word probabilities 0.290, 0.20, 0.224 and 0.286. On small corpora many networks fit almost equally well.
Readiness
Read- CTM, HDP and author-topic (REP044, REP045, REP047) partly run: they are methods of Discover → Topic model (author-topic needs an authors column).
- Dynamic topics (REP046) run: Discover → Dynamic topic model.
- Pachinko allocation (REP048) runs as a notebook only: the reference's example runs in both engines, but no CodeSplash method fits it.
Check: topic extensions
CheckpointCheck yourself
Why can't LDA represent "documents about topic A usually also cover topic B"?
Show the answer
Answer: a
Under a Dirichlet, topic proportions are only negatively correlated (they share a fixed total). CTM's logistic-normal covariance allows any correlation.
Check yourself
A CTM reports a strong correlation between two small topics, each in about 15 documents. How much should you trust it?
Show the answer
Answer: a
Covariances need many co-occurrences to estimate. Refit on subsamples before reading anything into it.
Check yourself
HDP keeps 6 topics on a corpus. Does that prove the corpus has 6 themes?
Show the answer
Answer: a
Nonparametric priors still have hyperparameters. Small topics near the end of the list may be noise.
Check yourself
HDP uses every topic up to its truncation limit. What should you do?
Show the answer
Answer: a
A truncation is a computational ceiling. If all slots are in use, the ceiling is binding.
Check yourself
A dynamic topic model shows a topic's vocabulary shifting sharply in one year. Which explanation should you rule out first?
Show the answer
Answer: a
Sparse time bins and changing sampling move word weights without any change in meaning. Check counts and sources per period.
Check yourself
A topic's share of the text falls by half while its drift stays small. What happened?
Show the answer
Answer: a
Share measures how much text a topic covers; drift measures how its word weights moved. They answer different questions.
Check yourself
In the author-topic model, where does a coauthored document's topic mix come from?
Show the answer
Answer: a
Under uniform attribution, averages the authors' word distributions.
Check yourself
An author-topic model says an author's main interest is "genetics". What exactly has it estimated?
Show the answer
Answer: a
Coauthorship confounds attribution, and sparse authors are weakly identified. Treat the estimate as descriptive.
Check yourself
A document picks supertopic 1 with probability . Supertopic 1 picks subtopic A with probability , and subtopic A gives word probability . No other path leads to . What is ?
Show the answer
Answer: 0.12
One path reaches , so multiply along it: .
Check yourself
Pachinko allocation learns a network of supertopics and subtopics. Is that network a validated taxonomy of the field?
Show the answer
Answer: a
Many paths explain the same word counts nearly equally well. Treat the structure as a hypothesis.
Recap
Recap- CTM lets topics correlate, HDP lets the data choose how many, dynamic topics let words drift, author-topic ties mixes to people, PAM nests topics.
- Each adds a parameter and a pitfall: unstable correlations, prior-driven counts, sparse periods, confounded authors, unidentified paths.
- CTM, HDP and author-topic partly run in Topic model; dynamic topics run; PAM is a notebook example.
Concepts in this lesson