Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

Read first

01

Five assumptions, five fixes

Read
LDA assumesExtensionRelaxed by
topics occur independentlyCTMCorrelated 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 topicsHDPHierarchical 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 changeDynamic 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 mixAuthor-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 flatPachinko 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.

02

CTM: topics that go together

Read

A Dirichlet can't say "documents about finance often also discuss politics". The correlated topic model draws ηd∼N(μ,Σ)\eta_d \sim N(\mu, \Sigma) and sets θd=softmax⁡(ηd)\theta_d = \operatorname{softmax}(\eta_d), so Σ\Sigma carries correlations between topics.

Topic modelRecorded · Python and R agreeRecorded 2026-11-21 · 33 values compared · largest relative difference 5.2e-8
R

3 topics in 61 documents (85 terms); topic 1 (team, …) is the most common.

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
teamTopic 10.0543
matchTopic 10.0478
strikerTopic 10.0346
garlicTopic 10.0346
leagueTopic 10.0281
fansTopic 10.0281
onionsTopic 10.0252
goalTopic 10.0216
oilTopic 10.0216
oliveTopic 10.0216
ratesTopic 20.0983
interestTopic 20.0710
bankTopic 20.0603
marketsTopic 20.0515
inflationTopic 20.0511
investorsTopic 20.0418
higherTopic 20.0362
sharesTopic 20.0325
fellTopic 20.0321
stockTopic 20.0320
profitsTopic 30.0594
bakeTopic 30.0493
sauceTopic 30.0462
saltTopic 30.0386
addTopic 30.0284
companyTopic 30.0279
simmerTopic 30.0276
pepperTopic 30.0271
soupTopic 30.0271
serveTopic 30.0270
How topics go together across documentsWhich numeric variables move together, and how strongly?

Correlation of the topics' centered log-ratio shares across documents: positive pairs tend to appear in the same documents.

View data
Topic 1Topic 2Topic 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.0621.772
0.4289−2.0041.575
1.829−1.538−0.2907
2.253−1.525−0.7287
1.574−1.5900.0161
0.5970−1.8811.284
1.696−1.326−0.3698
0.6897−1.9421.252
0.4610−2.0011.540
2.028−1.454−0.5741
0.9788−1.7970.8184
−0.00591.421−1.416
0.5965−1.7451.148
1.718−1.078−0.6396
0.3849−2.0791.694
2.225−1.467−0.7586
0.3313−2.0751.744
0.5602−1.8931.333
2.251−1.522−0.7286
−0.19032.068−1.877
−0.13671.938−1.802
−0.04871.758−1.710
0.1972−2.0241.826
−0.13251.967−1.835
−0.07281.839−1.766
0.4052−1.6881.283
0.87890.5847−1.464
0.4484−0.1501−0.2983
−0.13111.947−1.816
−0.24372.156−1.912
0.17161.329−1.500
−0.05441.751−1.697
−0.32600.21020.1158
−0.06051.662−1.602
0.01401.661−1.675
−0.06141.821−1.760
−0.12491.875−1.750
0.2639−1.9521.688
−0.06091.775−1.714

First 60 of 61 rows.

Topics

TopicShare of textCoherence (UMass)Top terms
155.4%−1.310team, match, striker, garlic, league, fans, onions, goal, oil, olive
224.6%−1.124rates, interest, bank, markets, inflation, investors, higher, shares, fell, stock
320.0%−1.018profits, bake, sauce, salt, add, company, simmer, pepper, soup, serve

Topic correlations

TopicWith topicCorrelation (centered log-ratio)
12−0.6493
13−0.0110
23−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)
))
Python

3 topics in 61 documents (85 terms); topic 1 (team, …) is the most common.

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

Topics

TopicShare of textCoherence (UMass)Top terms
155.4%−1.310team, match, striker, garlic, league, fans, onions, goal, oil, olive
224.6%−1.124rates, interest, bank, markets, inflation, investors, higher, shares, fell, stock
320.0%−1.018profits, bake, sauce, salt, add, company, simmer, pepper, soup, serve

Topic correlations

TopicWith topicCorrelation (centered log-ratio)
12−0.6493
13−0.0110
23−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.

03

HDP: let the data set the number

Read

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

Topic modelRecorded · Python and R agreeRecorded 2026-11-21 · 55 values compared
R

6 topics in 61 documents (85 terms); topic 1 (rates, …) is the most common.

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
ratesTopic 10.0618
interestTopic 10.0435
bankTopic 10.0373
higherTopic 10.0313
sharesTopic 10.0313
profitsTopic 10.0313
garlicTopic 10.0313
marketsTopic 10.0252
investorsTopic 10.0252
onionsTopic 10.0251
teamTopic 20.0743
matchTopic 20.0684
strikerTopic 20.0603
fansTopic 20.0593
stadiumTopic 20.0449
penaltyTopic 20.0449
cupTopic 20.0306
finalTopic 20.0305
leadersTopic 20.0305
scoredTopic 20.0305
bakeTopic 30.0959
yieldsTopic 30.0650
bondTopic 30.0649
breadTopic 30.0648
inflationTopic 30.0648
letTopic 30.0346
minutesTopic 30.0344
pastaTopic 30.0344
currencyTopic 30.0343
goldenTopic 30.0343
rivalsTopic 40.1030
matchTopic 40.0550
goalTopic 40.0545
lateTopic 40.0545
endedTopic 40.0545
finalTopic 40.0545
cupTopic 40.0545
leagueTopic 40.0542
teamTopic 40.0535
coachTopic 40.0061
minutesTopic 50.0719
tomatoesTopic 50.0719
addTopic 50.0719
simmerTopic 50.0719
sauceTopic 50.0717
teamTopic 50.0081
onionsTopic 50.0081
coachTopic 50.0081
matchTopic 50.0080
saltTopic 50.0080
pepperTopic 60.0720
sugarTopic 60.0720
addTopic 60.0719
saltTopic 60.0718
sauceTopic 60.0717
teamTopic 60.0080
gentlyTopic 60.0080
coachTopic 60.0080
matchTopic 60.0080
soupTopic 60.0080

Topics

TopicShare of textCoherence (UMass)Top terms
157.7%−1.359rates, interest, bank, higher, shares, profits, garlic, markets, investors, onions
224.2%−1.109team, match, striker, fans, stadium, penalty, cup, final, leaders, scored
39.9%−0.7964bake, yields, bond, bread, inflation, let, minutes, pasta, currency, golden
43.3%−0.5811rivals, match, goal, late, ended, final, cup, league, team, coach
51.6%−0.7367minutes, tomatoes, add, simmer, sauce, team, onions, coach, match, salt
61.6%−0.7765pepper, 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)
))
Python

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

TopicShare of textCoherence (UMass)Top terms
157.7%−1.359rates, interest, bank, higher, shares, profits, garlic, markets, investors, onions
224.2%−1.109team, match, striker, fans, stadium, penalty, cup, final, leaders, scored
39.9%−0.7964bake, yields, bond, bread, inflation, let, minutes, pasta, currency, golden
43.3%−0.5811rivals, match, goal, late, ended, final, cup, league, team, coach
51.6%−0.7367minutes, tomatoes, add, simmer, sauce, team, onions, coach, match, salt
61.6%−0.7765pepper, 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.

04

Predict

Predict

Predict first

HDP may use up to 8 topics on a small corpus of sports, finance and cooking texts. How many will it keep?

All 8Fewer than 8More than 8
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.

05

Dynamic topics: drift over time

Read

The dynamic topic model lets each topic's word weights wander from one period to the next, βt,k∼N(βt−1,k,σ2I)\beta_{t,k} \sim N(\beta_{t-1,k}, \sigma^2 I), mapped to probabilities by softmax. A topic keeps its identity while its vocabulary shifts.

Dynamic topic modelRecorded · Python and R agreeRecorded 2026-11-21 · 46 values compared
R

3 topics in 61 documents over 7 periods; topic 1 (league, …) is the most common.

Plots

Top terms per topic (all periods)What is each topic about?
View data
TermTopicWeight
leagueTopic 10.0418
bakeTopic 10.0418
fansTopic 10.0416
matchTopic 10.0413
teamTopic 10.0397
sauceTopic 10.0329
profitsTopic 10.0314
stadiumTopic 10.0311
coachTopic 10.0311
finalTopic 10.0286
ratesTopic 20.1154
interestTopic 20.0808
bankTopic 20.0692
inflationTopic 20.0571
higherTopic 20.0463
marketsTopic 20.0458
bondTopic 20.0334
fellTopic 20.0322
lemonTopic 20.0315
simmerTopic 20.0221
strikerTopic 30.0578
teamTopic 30.0476
garlicTopic 30.0449
matchTopic 30.0345
keptTopic 30.0339
madeTopic 30.0337
homeTopic 30.0337
oliveTopic 30.0335
oilTopic 30.0334
sharesTopic 30.0333
Topics over yearWhich topics are growing or fading?
View data
yearTopicDocuments (topic shares summed)
2,018Topic 10.1750
2,018Topic 22.282
2,018Topic 30.5429
2,019Topic 11.981
2,019Topic 22.966
2,019Topic 31.053
2,020Topic 13.497
2,020Topic 24.917
2,020Topic 35.586
2,021Topic 15.981
2,021Topic 26.124
2,021Topic 33.896
2,022Topic 16.440
2,022Topic 22.791
2,022Topic 34.769
2,023Topic 13.593
2,023Topic 20.4776
2,023Topic 31.930
2,024Topic 10.6865
2,024Topic 20.2245
2,024Topic 31.089

Topics

TopicShare of textCoherence (UMass)Drift, first → last periodTop terms (all periods)
136.6%−1.2690.4%league, bake, fans, match, team, sauce, profits, stadium, coach, final
232.4%−1.2830.5%rates, interest, bank, inflation, higher, markets, bond, fell, lemon, simmer
330.9%−1.2540.5%striker, team, garlic, match, kept, made, home, olive, oil, shares

Top terms in the first and last periods

TopicFirst periodLast period
1bake, league, fans, match, teamleague, fans, match, bake, team
2rates, interest, bank, inflation, marketsrates, interest, bank, inflation, higher
3striker, team, garlic, match, sharesstriker, 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"))
))
Python

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

TopicShare of textCoherence (UMass)Drift, first → last periodTop terms (all periods)
136.6%−1.2690.4%league, bake, fans, match, team, sauce, profits, stadium, coach, final
232.4%−1.2830.5%rates, interest, bank, inflation, higher, markets, bond, fell, lemon, simmer
330.9%−1.2540.5%striker, team, garlic, match, kept, made, home, olive, oil, shares

Top terms in the first and last periods

TopicFirst periodLast period
1bake, league, fans, match, teamleague, fans, match, bake, team
2rates, interest, bank, inflation, marketsrates, interest, bank, inflation, higher
3striker, team, garlic, match, sharesstriker, 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.

06

Author-topic: mixes belong to people

Read

In the author-topic model each author has a topic mix θa\theta_a. For each word, pick one of the document's authors, then a topic from that author's mix, then a word. A coauthored document blends its authors' interests.

Topic modelRecorded · Python and R agreeRecorded 2026-11-21 · 31 values compared
R

3 topics in 60 documents (85 terms); topic 1 (rates, …) is the most common.

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
ratesTopic 10.0869
interestTopic 10.0616
higherTopic 10.0532
bankTopic 10.0532
inflationTopic 10.0449
profitsTopic 10.0449
marketsTopic 10.0448
sharesTopic 10.0448
investorsTopic 10.0352
bondTopic 10.0281
garlicTopic 20.0480
bakeTopic 20.0392
onionsTopic 20.0390
sauceTopic 20.0390
saltTopic 20.0301
simmerTopic 20.0301
addTopic 20.0301
letTopic 20.0301
oilTopic 20.0299
oliveTopic 20.0299
matchTopic 30.0695
teamTopic 30.0693
strikerTopic 30.0505
leagueTopic 30.0410
fansTopic 30.0409
penaltyTopic 30.0316
stadiumTopic 30.0316
goalTopic 30.0316
keptTopic 30.0314
finalTopic 30.0312

Topics

TopicShare of textCoherence (UMass)Top terms
135.0%−1.194rates, interest, higher, bank, inflation, profits, markets, shares, investors, bond
233.3%−0.9909garlic, bake, onions, sauce, salt, simmer, add, let, oil, olive
331.6%−1.114match, team, striker, league, fans, penalty, stadium, goal, kept, final

Authors

AuthorDocumentsMain topicShare of main topic
Ada13398.1%
Ben10398.4%
Cleo15198.5%
Dev10198.5%
Eli14298.5%
Fay10298.3%
  • 2 rows have no text or no author 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 7d132cf53d761fde
# Dataset: top_authored (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
AUTHORS <- "authors"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/top_authored.parquet", col_select = c(TEXT, TIME, AUTHORS)))
author_lists <- lapply(df[[AUTHORS]], cs_topics_split_authors)
rows <- which(!is.na(df[[TEXT]]) & vapply(author_lists, length, integer(1)) > 0) - 1L
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text or no author 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
am <- cs_topics_author_matrix(author_lists[rows + 1L])
A <- am$A
author_names <- am$names
# Author-topic model: variational Bayes from 2 host-drawn starts; the best log-likelihood is kept.
fit <- cs_topics_best_of(function(sd) {
  f <- cs_topics_author_topic(X, A, K, 15, 20, alpha, eta, sd)
  th <- cs_ml_shares(f$gamma)
  list(doc_topic = cs_topics_author_doc_topic(A, th), topic_term = cs_ml_shares(f$lambda), extra = th)
}, X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
author_theta <- fit$extra
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/author_topics/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()
author_theta <- author_theta[, ord, drop = FALSE]
values$n_authors <- length(author_names)
n_docs_author <- colSums(A)
authors_df <- data.frame(author = author_names, documents = as.integer(n_docs_author))
for (t in seq_len(K)) authors_df[[paste0("topic_", t)]] <- author_theta[, t]
nanoparquet::write_parquet(authors_df, file.path(out, "authors.parquet"))
extra_artifacts <- list(list(key = "authors", path = file.path(out, "authors.parquet"), format = "parquet"))
main <- apply(author_theta, 1, which.max)
extra_tables <- list(list(
  key = "authors", title = "Authors",
  columns = list(list(key = "author", label = "Author"), list(key = "documents", label = "Documents", type = "integer"),
                 list(key = "topic", label = "Main topic", type = "integer"), list(key = "share", label = "Share of main topic", type = "percent")),
  rows = lapply(seq_along(author_names), function(a) list(author = author_names[a], documents = as.integer(n_docs_author[a]),
                                                         topic = main[a], share = author_theta[a, main[a]]))
))
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

3 topics in 60 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

TopicShare of textCoherence (UMass)Top terms
135.0%−1.194rates, interest, higher, bank, inflation, profits, markets, shares, investors, bond
233.3%−0.9909garlic, bake, onions, sauce, salt, simmer, add, let, oil, olive
331.6%−1.114match, team, striker, league, fans, penalty, stadium, goal, kept, final

Authors

AuthorDocumentsMain topicShare of main topic
Ada13398.1%
Ben10398.4%
Cleo15198.5%
Dev10198.5%
Eli14298.5%
Fay10298.3%
  • 2 rows have no text or no author 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 7d132cf53d761fde
# Dataset: top_authored (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
AUTHORS = "authors"
df = pd.read_parquet("tests/parity/fixtures/top_authored.parquet", columns=[c for c in (TEXT, TIME, AUTHORS) if c is not None])
author_lists = [cstopics.split_authors(a) for a in df[AUTHORS].tolist()]
rows = np.flatnonzero(df[TEXT].notna().to_numpy() & np.array([len(a) > 0 for a in author_lists], dtype=bool))
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text or no author 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
A, author_names = cstopics.author_matrix([author_lists[i] for i in rows])


def _author_fit(sd):
    g, lam = cstopics.author_topic(X, A, K, 15, 20, alpha, eta, sd)
    return cstopics.author_doc_topic(A, cstext.shares(g)), cstext.shares(lam), cstext.shares(g)


# Author-topic model: variational Bayes from 2 host-drawn starts; the best log-likelihood is kept.
doc_topic, topic_term, loglik, start, author_theta = cstopics.best_of(_author_fit, 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/author_topics/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 = [], [], []
author_theta = author_theta[:, order]
values["n_authors"] = len(author_names)
n_docs_author = A.sum(axis=0)
authors_df = pd.DataFrame({"author": author_names, "documents": n_docs_author.astype(np.int64)})
for t in range(K):
    authors_df[f"topic_{t + 1}"] = author_theta[:, t]
authors_df.to_parquet(os.path.join(out, "authors.parquet"), index=False)
extra_artifacts.append({"key": "authors", "path": os.path.join(out, "authors.parquet"), "format": "parquet"})
main = np.argmax(author_theta, axis=1)
extra_tables.append({
    "key": "authors",
    "title": "Authors",
    "columns": [{"key": "author", "label": "Author"}, {"key": "documents", "label": "Documents", "type": "integer"},
                {"key": "topic", "label": "Main topic", "type": "integer"}, {"key": "share", "label": "Share of main topic", "type": "percent"}],
    "rows": [{"author": author_names[a], "documents": int(n_docs_author[a]), "topic": int(main[a]) + 1,
              "share": float(author_theta[a, main[a]])} for a in range(len(author_names))],
})
# %% 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,
})

It estimated topic mixes for 6 authors. Splitting every word evenly among coauthors is a modeling choice, and an author's estimated "interests" are patterns in their text, not measured expertise.

07

Pachinko allocation: nested topics

Read

Pachinko 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:

p(w∣d)=∑sθds∑kψdsk ϕkw.p(w \mid d) = \sum_s \theta_{ds} \sum_k \psi_{dsk}\, \phi_{kw} .

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.

08

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.
Reference · REP048 · Runs as a notebookPachinko allocation model (PAM)Represent correlated and hierarchical topic relationships using a directed acyclic graph of topic choices rather than one flat mixture.
09

Check: topic extensions

Checkpoint

Check 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, p(w∣d)p(w \mid d) 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 0.60.6. Supertopic 1 picks subtopic A with probability 0.50.5, and subtopic A gives word ww probability 0.40.4. No other path leads to ww. What is p(w∣d)p(w \mid d)?

Show the answer

Answer: 0.12

One path reaches ww, so multiply along it: 0.6×0.5×0.4=0.120.6 \times 0.5 \times 0.4 = 0.12.

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.

10

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