Skip to content

CDiscover · discover.dynamic_topics

Dynamic topic model

How do the topics in a collection of texts change over time?

Topics whose word weights drift from one period to the next (Blei and Lafferty's dynamic topic model): documents are grouped into periods by a time column, each topic's words follow a random walk across periods, and each document mixes topics. Shows each topic's top words overall and in the first and last periods, how far each topic drifted, and topic shares over time. Fitted by variational EM with point estimates of the topic paths, the same way in Python and R.

Experimental Python and R agree to 6 decimals Also called DTM, topics over time, topic drift…

A real result

Example “Years three”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Years threeml_corpus_dated · text: text · time: year
  • Dates ten periodsml_corpus_dated · text: text · time: posted
  • Years loose driftml_corpus_dated · text: text · time: year
  • Degenerate all naml_corpus_dated · text: text · time: year
  • Degenerate n1ml_corpus_dated · text: text · time: year
  • Degenerate constantml_corpus_dated · text: text · time: year
  • Degenerate infml_corpus_dated · text: text · time: year

In the guides

Where it sits in the decision guides

  • Topic modeling (LDA, NMF, BERTopic) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Textcategorical · 1 column
The text column; each row is one document.
Timetemporal / numeric · 1 column
When each document was written. Each distinct time is a period (up to 12); otherwise 10 equal periods.

Choices you make

model

Topicsdefault 5

Number of topics, the same in every period.

Topic drift (σ²)default 0.005

How much a topic's word weights may change from one period to the next. Larger values let topics drift more.

Document-topic prior (α)default —

How many topics each document mixes. Smaller values give documents fewer topics. Empty uses the default.

EM passesdefault 20

Rounds of updating the documents and then the topic paths.

Advanced

Document iterations per passdefault 20

Iterations per document in each pass.

Topic-path steps per passdefault 20

Steps that update each topic's path through the periods in each pass; each step never lowers the fit.

preprocess

Minimum documents per worddefault 2

Ignore words that appear in fewer documents than this.

Maximum share of documents per worddefault 0.95

Ignore words that appear in more than this share of documents (too common to be informative).

Vocabulary sizedefault 2000

Largest vocabulary kept, by frequency.

options

Top terms per topicdefault 10

Words listed for each topic.

What it reports

n_docs
Rows with both text and a time that went into the model.
n_terms
Rows with both text and a time that went into the model.
n_topics
Rows with both text and a time that went into the model.
n_periods
Time slices the documents are grouped into: each distinct time up to 12, otherwise 10 equal-width periods.
mean_coherence
Mean UMass coherence of each topic's top words averaged over periods; closer to 0 = top words co-occur more.
doc_check
Sum over words of log(document topic shares × its period's topic weights); higher fits the counts better.
loglik
Sum over words of log(document topic shares × its period's topic weights); higher fits the counts better.

Per group, level or term: prevalence[<topic>], coherence[<topic>], top_term[<topic>], top_term_first[<topic>], top_term_last[<topic>], drift[<topic>], share_first[<topic>], share_last[<topic>], weight[<topic>:<term>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, scipy; R uses codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.ml.topics_dynamic ↔ codesplashr ml_topics_dynamic.R) from the same host-drawn start with fixed iterations; they differ only by matrix-product and solve rounding (≪ 1e-6).
  • The topic paths are point (MAP) estimates found by majorize-maximize steps, not the variational Kalman filter of Blei and Lafferty (2006) or gensim's LdaSeqModel, so numbers differ from those implementations; the model is the same.
  • The tokenizer is discover.topics' (letter runs, stop words removed, frequency limits).
Python

The exact script CodeSplash ran for example “Years three” · 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"},
    ],
})
R

The exact script CodeSplash ran for example “Years three” · 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"))
))

Sources

  • Blei DM, Lafferty JD (2006). Dynamic topic models. ICML 2006, 113–120.
  • Blei DM, Ng AY, Jordan MI (2003). Latent Dirichlet allocation. JMLR 3:993–1022.
  • Böhning D (1992). Multinomial logistic regression algorithm. Annals of the Institute of Statistical Mathematics 44(1):197–200.
  • Mimno D, Wallach H, Talley E, Leenders M, McCallum A (2011). Optimizing semantic coherence in topic models. EMNLP 2011.

From the CodeSplash method registry · discover.dynamic_topics v1.0.0.