Topics that change over time
The dynamic topic model lets each topic's words drift from one period to the next. Learn to set the drift, read first-versus-last top words, and tell a growing topic from a changing one.
What runs in CodeSplash
- Dynamic topic model Experimental
You will be able to
- Explain how a dynamic topic model links topics across periods
- Choose the topic drift setting
- Tell a topic's share over time from a change in its words
Read first
Same topic, new words
ReadA topic model with a time chart shows which topics grow or fade. It assumes each topic uses the same words in every period. Language moves: a "phones" topic in 2008 leads with keyboards, and in 2018 with apps.
The dynamic topic modelDynamic topic modelTopics whose word weights drift between periods as a random walk; each document mixes topics. gives every topic its own word weights in each period. A topic's weights move as a random walk, so neighboring periods stay similar and distant ones can differ.
Periods and drift
ReadPick a time column. Each distinct time becomes a period when there are 12 or fewer; otherwise the range is cut into 10 equal periods.
Topic drift (σ²) sets how far a topic may move per period. Small values, like the default, keep topics nearly fixed, so changes need strong evidence. Larger values let topics wander and can split one theme into unrelated word lists across periods.
Make a guess
PredictPredict first
You raise topic drift to a hundred times the default. What happens to the reported drift of each topic?
Reveal
More drift. The prior allows bigger steps between periods, so the first and last periods' word weights end up further apart. With the default drift, topic 1 moved 0.4% of its weight; the looser fit below lets topics move more.
Read the card
Read3 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"},
],
})
The Topics table gives each topic's share of the text and its driftTopic driftHow much of a topic's word weight moved between the first and last periods (total variation, 0 to 100%)., the share of its word weight that moved between the first and last periods. The second table puts the first and last periods' top words side by side.
View data
| month | topic | tickets |
|---|---|---|
| 1,704,067,200,000 | delivery | 65 |
| 1,704,067,200,000 | pricing | 74 |
| 1,704,067,200,000 | support | 42 |
| 1,704,067,200,000 | quality | 42 |
| 1,704,067,200,000 | returns | 16 |
| 1,706,745,600,000 | delivery | 69 |
| 1,706,745,600,000 | pricing | 84 |
| 1,706,745,600,000 | support | 39 |
| 1,706,745,600,000 | quality | 29 |
| 1,706,745,600,000 | returns | 20 |
| 1,709,251,200,000 | delivery | 71 |
| 1,709,251,200,000 | pricing | 85 |
| 1,709,251,200,000 | support | 43 |
| 1,709,251,200,000 | quality | 34 |
| 1,709,251,200,000 | returns | 28 |
| 1,711,929,600,000 | delivery | 69 |
| 1,711,929,600,000 | pricing | 76 |
| 1,711,929,600,000 | support | 52 |
| 1,711,929,600,000 | quality | 39 |
| 1,711,929,600,000 | returns | 26 |
| 1,714,521,600,000 | delivery | 76 |
| 1,714,521,600,000 | pricing | 75 |
| 1,714,521,600,000 | support | 56 |
| 1,714,521,600,000 | quality | 33 |
| 1,714,521,600,000 | returns | 23 |
| 1,717,200,000,000 | delivery | 71 |
| 1,717,200,000,000 | pricing | 69 |
| 1,717,200,000,000 | support | 52 |
| 1,717,200,000,000 | quality | 35 |
| 1,717,200,000,000 | returns | 22 |
| 1,719,792,000,000 | delivery | 72 |
| 1,719,792,000,000 | pricing | 67 |
| 1,719,792,000,000 | support | 58 |
| 1,719,792,000,000 | quality | 40 |
| 1,719,792,000,000 | returns | 23 |
| 1,722,470,400,000 | delivery | 77 |
| 1,722,470,400,000 | pricing | 68 |
| 1,722,470,400,000 | support | 42 |
| 1,722,470,400,000 | quality | 48 |
| 1,722,470,400,000 | returns | 20 |
| 1,725,148,800,000 | delivery | 70 |
| 1,725,148,800,000 | pricing | 69 |
| 1,725,148,800,000 | support | 46 |
| 1,725,148,800,000 | quality | 39 |
| 1,725,148,800,000 | returns | 28 |
| 1,727,740,800,000 | delivery | 79 |
| 1,727,740,800,000 | pricing | 70 |
| 1,727,740,800,000 | support | 40 |
| 1,727,740,800,000 | quality | 37 |
| 1,727,740,800,000 | returns | 30 |
| 1,730,419,200,000 | delivery | 91 |
| 1,730,419,200,000 | pricing | 67 |
| 1,730,419,200,000 | support | 28 |
| 1,730,419,200,000 | quality | 37 |
| 1,730,419,200,000 | returns | 34 |
| 1,733,011,200,000 | delivery | 85 |
| 1,733,011,200,000 | pricing | 65 |
| 1,733,011,200,000 | support | 45 |
| 1,733,011,200,000 | quality | 42 |
| 1,733,011,200,000 | returns | 35 |
First 60 of 120 rows.
A widening band is a topic taking a bigger share. That's a different finding from drift. A topic can hold its share while its words change, or grow while its words stay put.
2 topics in 61 documents over 7 periods; topic 1 (match, …) is the most common.
Plots
View data
| Term | Topic | Weight |
|---|---|---|
| match | Topic 1 | 0.0589 |
| team | Topic 1 | 0.0365 |
| league | Topic 1 | 0.0276 |
| bake | Topic 1 | 0.0271 |
| fans | Topic 1 | 0.0259 |
| stadium | Topic 1 | 0.0258 |
| shares | Topic 1 | 0.0256 |
| profits | Topic 1 | 0.0247 |
| company | Topic 1 | 0.0227 |
| striker | Topic 1 | 0.0217 |
| rates | Topic 2 | 0.0721 |
| interest | Topic 2 | 0.0491 |
| bank | Topic 2 | 0.0395 |
| garlic | Topic 2 | 0.0340 |
| team | Topic 2 | 0.0313 |
| higher | Topic 2 | 0.0293 |
| onions | Topic 2 | 0.0264 |
| markets | Topic 2 | 0.0252 |
| penalty | Topic 2 | 0.0219 |
| kept | Topic 2 | 0.0210 |
View data
| year | Topic | Documents (topic shares summed) |
|---|---|---|
| 2,018 | Topic 1 | 1.023 |
| 2,018 | Topic 2 | 1.977 |
| 2,019 | Topic 1 | 2.384 |
| 2,019 | Topic 2 | 3.616 |
| 2,020 | Topic 1 | 6.076 |
| 2,020 | Topic 2 | 7.924 |
| 2,021 | Topic 1 | 7.608 |
| 2,021 | Topic 2 | 8.392 |
| 2,022 | Topic 1 | 8.805 |
| 2,022 | Topic 2 | 5.195 |
| 2,023 | Topic 1 | 3.756 |
| 2,023 | Topic 2 | 2.244 |
| 2,024 | Topic 1 | 0.8942 |
| 2,024 | Topic 2 | 1.106 |
Topics
| Topic | Share of text | Coherence (UMass) | Drift, first → last period | Top terms (all periods) |
|---|---|---|---|---|
| 1 | 50.1% | −1.354 | 32.6% | match, team, league, bake, fans, stadium, shares, profits, company, striker |
| 2 | 49.9% | −1.563 | 37.8% | rates, interest, bank, garlic, team, higher, onions, markets, penalty, kept |
Top terms in the first and last periods
| Topic | First period | Last period |
|---|---|---|
| 1 | shares, profits, inflation, yields, bond | match, team, fans, stadium, league |
| 2 | rates, interest, bank, investors, inflation | team, kept, higher, goalkeeper, garlic |
- 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 a7ac4f99ea857d9e
# 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 <- 2
SEED <- 42
alpha <- 0.2
if (is.null(alpha)) alpha <- 1 / K
# Variational EM: documents under their period's topics, then 10 majorize-maximize steps per topic path.
fit <- cs_dtm_fit(X, period, S, K, 8, 20, alpha, 0.5, SEED, 10)
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_loose_drift/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"))
))
2 topics in 61 documents over 7 periods; topic 1 (match, …) 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 | 50.1% | −1.354 | 32.6% | match, team, league, bake, fans, stadium, shares, profits, company, striker |
| 2 | 49.9% | −1.563 | 37.8% | rates, interest, bank, garlic, team, higher, onions, markets, penalty, kept |
Top terms in the first and last periods
| Topic | First period | Last period |
|---|---|---|
| 1 | shares, profits, inflation, yields, bond | match, team, fans, stadium, league |
| 2 | rates, interest, bank, investors, inflation | team, kept, higher, goalkeeper, garlic |
- 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 a7ac4f99ea857d9e
# 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 = 2
SEED = 42
alpha = 0.2 or 1.0 / K
# Variational EM: documents under their period's topics, then 10 majorize-maximize steps per topic path.
gamma, beta = csdtm.dtm(X, period, S, K, 8, 20, alpha, 0.5, SEED, 10)
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_loose_drift/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"},
],
})
How it's fitted
ReadEach pass first estimates every document's topic mix under its period's topics, then updates every topic's path through the periods. The path updates never lower the fit. Python and R start from the same values and run the same steps, so they agree to many digits.
Check your understanding
CheckpointCheck yourself
A topic's share stays at 30% in every period, but its drift is 40%. What happened?
Show the answer
Answer: b
Share and drift answer different questions. Read the first and last top words to see what changed.
Check yourself
With topic drift set very high, topic 2 leads with sports words in 2019 and finance words in 2023. What should you suspect?
Show the answer
Answer: a
A random walk with large steps can stitch different themes into one topic. Keep drift small unless the change is gradual and real.
Check yourself
Your time column has 300 distinct dates. How many periods does the model use?
Show the answer
Answer: c
Each distinct time is a period only when there are 12 or fewer; otherwise the range is cut into 10 equal periods.
Recap
Read- Each topic has its own word weights per period, linked by a random walk.
- Topic drift (σ²) controls how far topics move; keep it small by default.
- Share over time and drift in words are separate findings: check both.
Concepts in this lesson