Skip to content

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.

Advanced ~12 min7 steps

What runs in CodeSplash

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

01

Same topic, new words

Read

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

02

Periods and drift

Read

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

03

Make a guess

Predict

Predict first

You raise topic drift to a hundred times the default. What happens to the reported drift of each topic?

More driftLess driftNo change
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.

04

Read the card

Read
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"},
    ],
})

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.

Topics over timeWhich topics are growing or fading?
View data
monthtopictickets
1,704,067,200,000delivery65
1,704,067,200,000pricing74
1,704,067,200,000support42
1,704,067,200,000quality42
1,704,067,200,000returns16
1,706,745,600,000delivery69
1,706,745,600,000pricing84
1,706,745,600,000support39
1,706,745,600,000quality29
1,706,745,600,000returns20
1,709,251,200,000delivery71
1,709,251,200,000pricing85
1,709,251,200,000support43
1,709,251,200,000quality34
1,709,251,200,000returns28
1,711,929,600,000delivery69
1,711,929,600,000pricing76
1,711,929,600,000support52
1,711,929,600,000quality39
1,711,929,600,000returns26
1,714,521,600,000delivery76
1,714,521,600,000pricing75
1,714,521,600,000support56
1,714,521,600,000quality33
1,714,521,600,000returns23
1,717,200,000,000delivery71
1,717,200,000,000pricing69
1,717,200,000,000support52
1,717,200,000,000quality35
1,717,200,000,000returns22
1,719,792,000,000delivery72
1,719,792,000,000pricing67
1,719,792,000,000support58
1,719,792,000,000quality40
1,719,792,000,000returns23
1,722,470,400,000delivery77
1,722,470,400,000pricing68
1,722,470,400,000support42
1,722,470,400,000quality48
1,722,470,400,000returns20
1,725,148,800,000delivery70
1,725,148,800,000pricing69
1,725,148,800,000support46
1,725,148,800,000quality39
1,725,148,800,000returns28
1,727,740,800,000delivery79
1,727,740,800,000pricing70
1,727,740,800,000support40
1,727,740,800,000quality37
1,727,740,800,000returns30
1,730,419,200,000delivery91
1,730,419,200,000pricing67
1,730,419,200,000support28
1,730,419,200,000quality37
1,730,419,200,000returns34
1,733,011,200,000delivery85
1,733,011,200,000pricing65
1,733,011,200,000support45
1,733,011,200,000quality42
1,733,011,200,000returns35

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.

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

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

Plots

Top terms per topic (all periods)What is each topic about?
View data
TermTopicWeight
matchTopic 10.0589
teamTopic 10.0365
leagueTopic 10.0276
bakeTopic 10.0271
fansTopic 10.0259
stadiumTopic 10.0258
sharesTopic 10.0256
profitsTopic 10.0247
companyTopic 10.0227
strikerTopic 10.0217
ratesTopic 20.0721
interestTopic 20.0491
bankTopic 20.0395
garlicTopic 20.0340
teamTopic 20.0313
higherTopic 20.0293
onionsTopic 20.0264
marketsTopic 20.0252
penaltyTopic 20.0219
keptTopic 20.0210
Topics over yearWhich topics are growing or fading?
View data
yearTopicDocuments (topic shares summed)
2,018Topic 11.023
2,018Topic 21.977
2,019Topic 12.384
2,019Topic 23.616
2,020Topic 16.076
2,020Topic 27.924
2,021Topic 17.608
2,021Topic 28.392
2,022Topic 18.805
2,022Topic 25.195
2,023Topic 13.756
2,023Topic 22.244
2,024Topic 10.8942
2,024Topic 21.106

Topics

TopicShare of textCoherence (UMass)Drift, first → last periodTop terms (all periods)
150.1%−1.35432.6%match, team, league, bake, fans, stadium, shares, profits, company, striker
249.9%−1.56337.8%rates, interest, bank, garlic, team, higher, onions, markets, penalty, kept

Top terms in the first and last periods

TopicFirst periodLast period
1shares, profits, inflation, yields, bondmatch, team, fans, stadium, league
2rates, interest, bank, investors, inflationteam, 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"))
))
Python

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

TopicShare of textCoherence (UMass)Drift, first → last periodTop terms (all periods)
150.1%−1.35432.6%match, team, league, bake, fans, stadium, shares, profits, company, striker
249.9%−1.56337.8%rates, interest, bank, garlic, team, higher, onions, markets, penalty, kept

Top terms in the first and last periods

TopicFirst periodLast period
1shares, profits, inflation, yields, bondmatch, team, fans, stadium, league
2rates, interest, bank, investors, inflationteam, 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"},
    ],
})
05

How it's fitted

Read

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

06

Check your understanding

Checkpoint

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

07

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