Skip to content

More topic models: PLSA, correlated topics, HDP, authors and online LDA

Five more ways to find topics in a text column. Learn what each one adds to LDA, when it helps, and what to check before you trust it.

Advanced ~14 min8 steps

What runs in CodeSplash

You will be able to

  • Tell PLSA, the correlated topic model, HDP and the author-topic model apart from LDA
  • Read topic correlations and the topics an HDP keeps
  • Decide when online LDA is worth using

Read first

01

One idea, five variations

Read

Every model here shares LDA's picture: a topicTopic modelRepresents each document as a mix of topics and each topic as a weighted list of words. is a list of word weights, and a document is a mix of topics. They differ in what they assume about the mixes and how they're fitted.

ModelWhat it changesPick it when
PLSANo priors; fitted by EMYou want the plain likelihood fit, on a large corpus
Correlated topic modelTopic shares can go togetherThemes travel in pairs
HDPDecides the number of topicsYou have no idea how many topics there are
Author-topicTopic mixes belong to authorsEach document has known writers
Online LDAUpdates from small batchesThe corpus is too large for batch passes
02

PLSA: LDA without the priors

Read

PLSAProbabilistic latent semantic analysis (PLSA)A topic model fitted by EM: each document mixes topics, each topic is a word distribution, with no priors on either. fits topic and document distributions by EM. Its updates are the same as NMF with the KL divergence, so it's fast. With no prior pulling documents toward a few topics, it can fit noise in a small corpus. Compare its coherence with LDA's before switching.

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

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

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
ratesTopic 10.0877
interestTopic 10.0614
bankTopic 10.0526
higherTopic 10.0526
inflationTopic 10.0439
marketsTopic 10.0439
profitsTopic 10.0439
sharesTopic 10.0439
bakeTopic 10.0351
investorsTopic 10.0351
teamTopic 20.0976
matchTopic 20.0854
strikerTopic 20.0610
fansTopic 20.0488
leagueTopic 20.0488
coachTopic 20.0366
cupTopic 20.0366
finalTopic 20.0366
goalTopic 20.0366
goalkeeperTopic 20.0366
garlicTopic 30.0862
onionsTopic 30.0690
sauceTopic 30.0690
addTopic 30.0517
herbsTopic 30.0517
lemonTopic 30.0517
oilTopic 30.0517
oliveTopic 30.0517
saltTopic 30.0517
simmerTopic 30.0517

Topics

TopicShare of textCoherence (UMass)Top terms
144.0%−1.273rates, interest, bank, higher, inflation, markets, profits, shares, bake, investors
232.2%−1.150team, match, striker, fans, league, coach, cup, final, goal, goalkeeper
322.1%−0.8421garlic, onions, sauce, add, herbs, lemon, oil, olive, salt, simmer
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec dd1d08d531ad1cde
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
TIME <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c(TEXT, TIME)))
rows <- which(!is.na(df[[TEXT]])) - 1L  # documents with text (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))

# %% Topic model
K <- 3
SEED <- 42
# PLSA by EM (KL-NMF multiplicative updates) from 2 host-drawn starts; the best log-likelihood is kept.
fit <- cs_topics_best_of(function(sd) c(cs_topics_plsa(X, K, 100, sd), list(extra = NULL)), X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
top_terms <- cs_topics_top_terms  # weights equal to 12 decimals rank in vocabulary order
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/plsa_three/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
  j <- top_terms(topic_term[t, ], 30)
  data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))

# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
               mean_coherence = if (length(finite)) mean(finite) else NaN,
               doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
  values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
  values[[sprintf("coherence[%d]", t)]] <- coherence[t]
  values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
  for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

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

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

Topics

TopicShare of textCoherence (UMass)Top terms
144.0%−1.273rates, interest, bank, higher, inflation, markets, profits, shares, bake, investors
232.2%−1.150team, match, striker, fans, league, coach, cup, final, goal, goalkeeper
322.1%−0.8421garlic, onions, sauce, add, herbs, lemon, oil, olive, salt, simmer
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec dd1d08d531ad1cde
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
TIME = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT] if TIME is None else [TEXT, TIME])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())  # documents with text (0-based input rows)
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
    cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
    warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")

# %% Topic model
K = 3
SEED = 42
# PLSA by EM (KL-NMF multiplicative updates) from 2 host-drawn starts; the best log-likelihood is kept.
doc_topic, topic_term, loglik, start, _ = cstopics.best_of(
    lambda sd: cstopics.plsa(X, K, 100, sd) + (None,), X, 2, SEED)
top_terms = cstopics.top_terms  # weights equal to 12 decimals rank in vocabulary order
order = cstext.canonical(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/plsa_three/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
    topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
    for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
        term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)

# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
    "n_docs": len(rows),
    "n_terms": len(vocab),
    "n_topics": K,
    "mean_coherence": float(np.mean(finite)) if finite else float("nan"),
    "doc_check": csembed.checksum(doc_topic[:, 0], rows),
    "loglik": loglik,
}
for t in range(K):
    values[f"prevalence[{t + 1}]"] = float(prevalence[t])
    values[f"coherence[{t + 1}]"] = coherence[t]
    values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
    for j in tops[t][:5]:
        values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
    for j in tops[t]:
        chart_topic.append(f"Topic {t + 1}")
        chart_term.append(vocab[j])
        chart_weight.append(float(topic_term[t, j]))
cs.publish({
    "title": "Topic model",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
    "tables": [{
        "key": "topics",
        "title": "Topics",
        "columns": [
            {"key": "topic", "label": "Topic", "type": "integer"},
            {"key": "prevalence", "label": "Share of text", "type": "percent"},
            {"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
            {"key": "terms", "label": "Top terms"},
        ],
        "rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
                  "terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
    }] + extra_tables,
    "charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
        "topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
        "term": cs.col("Term", chart_term, "categorical"),
        "weight": cs.col("Weight", chart_weight, "numeric"),
    }, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
        {"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
    ] + extra_artifacts,
})
03

Correlated topics

Read

LDA's Dirichlet prior can't say "documents about cooking often also talk about health". The correlated topic modelCorrelated topic model (CTM)A topic model whose topic shares are logistic-normal, so topics can go together or exclude each other across documents. gives topic shares a logistic-normal prior with a full covariance, so pairs of topics can rise and fall together. CodeSplash starts it from a short LDA fit, because a random start often collapses to one topic on small collections.

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

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

Plots

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

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

View data
Topic 1Topic 2Topic 3
2.416−1.571−0.8457
2.142−1.419−0.7236
2.294−1.506−0.7876
2.086−1.343−0.7430
2.142−1.419−0.7233
2.230−1.468−0.7619
2.139−1.418−0.7216
2.027−1.354−0.6731
2.026−1.350−0.6759
2.034−1.356−0.6770
2.145−1.417−0.7280
2.294−1.506−0.7883
2.044−1.360−0.6844
2.237−1.470−0.7666
1.638−1.262−0.3757
1.752−1.318−0.4338
2.139−1.415−0.7241
2.174−1.471−0.7031
1.673−1.133−0.5401
2.212−1.462−0.7496
2.289−1.509−0.7795
0.2896−2.0621.772
0.4289−2.0041.575
1.829−1.538−0.2907
2.253−1.525−0.7287
1.574−1.5900.0161
0.5970−1.8811.284
1.696−1.326−0.3698
0.6897−1.9421.252
0.4610−2.0011.540
2.028−1.454−0.5741
0.9788−1.7970.8184
−0.00591.421−1.416
0.5965−1.7451.148
1.718−1.078−0.6396
0.3849−2.0791.694
2.225−1.467−0.7586
0.3313−2.0751.744
0.5602−1.8931.333
2.251−1.522−0.7286
−0.19032.068−1.877
−0.13671.938−1.802
−0.04871.758−1.710
0.1972−2.0241.826
−0.13251.967−1.835
−0.07281.839−1.766
0.4052−1.6881.283
0.87890.5847−1.464
0.4484−0.1501−0.2983
−0.13111.947−1.816
−0.24372.156−1.912
0.17161.329−1.500
−0.05441.751−1.697
−0.32600.21020.1158
−0.06051.662−1.602
0.01401.661−1.675
−0.06141.821−1.760
−0.12491.875−1.750
0.2639−1.9521.688
−0.06091.775−1.714

First 60 of 61 rows.

Topics

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

Topic correlations

TopicWith topicCorrelation (centered log-ratio)
12−0.6493
13−0.0110
23−0.7533
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec 8c765cbff4751af5
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
TIME <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c(TEXT, TIME)))
rows <- which(!is.na(df[[TEXT]])) - 1L  # documents with text (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))

# %% Topic model
K <- 3
SEED <- 42
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# Correlated topic model: variational EM, 10 passes from a host-drawn start.
ctm_fit <- cs_topics_ctm(X, K, 10, 10, eta, SEED)
doc_topic <- ctm_fit$doc_topic
topic_term <- ctm_fit$topic_term
loglik <- cs_ml_loglik(X, doc_topic, topic_term)
top_terms <- cs_topics_top_terms  # weights equal to 12 decimals rank in vocabulary order
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/ctm_three/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
  j <- top_terms(topic_term[t, ], 30)
  data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))

# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
               mean_coherence = if (length(finite)) mean(finite) else NaN,
               doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
  values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
  values[[sprintf("coherence[%d]", t)]] <- coherence[t]
  values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
  for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
corr <- cs_topics_clr_correlations(doc_topic)
for (i in seq_len(K)) for (j in seq_len(K)) if (j > i) values[[sprintf("topic_corr[%d:%d]", i, j)]] <- corr[i, j]
Lg <- log(pmax(doc_topic, 1e-300))
clr <- Lg - rowMeans(Lg)
extra_charts <- list(cs_chart("correlations", "corr-heatmap", "How topics go together across documents",
  list(vars = lapply(seq_len(K), function(t) cs_col(paste("Topic", t), clr[, t], "numeric"))),
  note = "Correlation of the topics' centered log-ratio shares across documents: positive pairs tend to appear in the same documents."))
pairs <- do.call(rbind, lapply(seq_len(K), function(i) if (i < K) cbind(i, (i + 1):K)))
extra_tables <- list(list(
  key = "correlations", title = "Topic correlations",
  columns = list(list(key = "a", label = "Topic", type = "integer"), list(key = "b", label = "With topic", type = "integer"),
                 list(key = "r", label = "Correlation (centered log-ratio)", type = "number")),
  rows = lapply(seq_len(nrow(pairs)), function(r) list(a = pairs[r, 1], b = pairs[r, 2], r = corr[pairs[r, 1], pairs[r, 2]]))
))
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

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

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

Topics

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

Topic correlations

TopicWith topicCorrelation (centered log-ratio)
12−0.6493
13−0.0110
23−0.7533
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec 8c765cbff4751af5
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
TIME = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT] if TIME is None else [TEXT, TIME])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())  # documents with text (0-based input rows)
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
    cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
    warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")

# %% Topic model
K = 3
SEED = 42
eta = None or 1.0 / K
# Correlated topic model: variational EM, 10 passes from a host-drawn start.
ctm_fit = cstopics.ctm(X, K, 10, 10, eta, SEED)
doc_topic, topic_term = ctm_fit["doc_topic"], ctm_fit["topic_term"]
loglik = cstext.loglik(X, doc_topic, topic_term)
top_terms = cstopics.top_terms  # weights equal to 12 decimals rank in vocabulary order
order = cstext.canonical(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/ctm_three/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
    topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
    for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
        term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)

# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
    "n_docs": len(rows),
    "n_terms": len(vocab),
    "n_topics": K,
    "mean_coherence": float(np.mean(finite)) if finite else float("nan"),
    "doc_check": csembed.checksum(doc_topic[:, 0], rows),
    "loglik": loglik,
}
for t in range(K):
    values[f"prevalence[{t + 1}]"] = float(prevalence[t])
    values[f"coherence[{t + 1}]"] = coherence[t]
    values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
    for j in tops[t][:5]:
        values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
corr = cstopics.clr_correlations(doc_topic)
for i in range(K):
    for j in range(i + 1, K):
        values[f"topic_corr[{i + 1}:{j + 1}]"] = float(corr[i, j])
L = np.log(np.maximum(doc_topic, 1e-300))
clr = L - L.mean(axis=1)[:, None]
extra_charts.append(cs.chart("correlations", "corr-heatmap", "How topics go together across documents",
    {"vars": [cs.col(f"Topic {t + 1}", clr[:, t].tolist(), "numeric") for t in range(K)]},
    note="Correlation of the topics' centered log-ratio shares across documents: positive pairs tend to appear in the same documents."))
extra_tables.append({
    "key": "correlations",
    "title": "Topic correlations",
    "columns": [{"key": "a", "label": "Topic", "type": "integer"}, {"key": "b", "label": "With topic", "type": "integer"},
                {"key": "r", "label": "Correlation (centered log-ratio)", "type": "number"}],
    "rows": [{"a": i + 1, "b": j + 1, "r": float(corr[i, j])} for i in range(K) for j in range(i + 1, K)],
})
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
    for j in tops[t]:
        chart_topic.append(f"Topic {t + 1}")
        chart_term.append(vocab[j])
        chart_weight.append(float(topic_term[t, j]))
cs.publish({
    "title": "Topic model",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
    "tables": [{
        "key": "topics",
        "title": "Topics",
        "columns": [
            {"key": "topic", "label": "Topic", "type": "integer"},
            {"key": "prevalence", "label": "Share of text", "type": "percent"},
            {"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
            {"key": "terms", "label": "Top terms"},
        ],
        "rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
                  "terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
    }] + extra_tables,
    "charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
        "topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
        "term": cs.col("Term", chart_term, "categorical"),
        "weight": cs.col("Weight", chart_weight, "numeric"),
    }, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
        {"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
    ] + extra_artifacts,
})
Correlation heatmapWhich numeric variables move together, and how strongly?
View data
income_kmonthly_spendtenure_monthssite_visitschurn_risksupport_ticketsage
80.930780.2634.08034.8500.18002.28032.190
47.270461.2519.96017.3300.41001.20034.480
95521.3244.61024.3000.38002.80052.640
95.540586.0915.32018.0700.58004.39043.750
50.310543.2129.97017.4900.34001.44050.340
91.180674.8517.87025.2700.35002.70029.910
81.700545.9827.18014.0200.35002.73042.510
29.490319.705.1607.7000.55003.70056.400
19.100314.1925.93016.9300.27005.98033.040
57.250511.9433.10029.0300.40003.73041.990
86.670567.0135.29028.6400.39000.800059.170
87.070735.23−9.26014.6900.62005.70047.630
37.850213.549.19020.3000.47005.97049.180
47.320422.6916.83022.8100.34003.50049.840
97.670830.0428.34022.5300.22002.86036.090
54.480409.6229.57019.0600.49002.18045.740
61.230654.4452.78026.1100.24002.38044.130
76.080648.1746.35022.4000.25003.62040.060
64.910570.3329.69014.8600.43003.40047.290
80.450539.3227.72019.4400.16002.75035.610
102.86741.7748.44021.5500.16002.36078.900
69.970369.2525.41012.5500.45003.75055.480
95.010552.4210.85019.5700.41006.20030.310
63.690461.6021.75021.8800.34003.05055.910
60.500494.6818.40025.9900.50000.640038.830
46.610601.9429.41016.1500.33001.85045.970
44.760429.0846.50017.0700.30005.14039.360
70.490464.4927.08018.5900.41005.13060.150
54.720275.7729.10016.0900.41006.75047.780
61.250438.5715.27011.2100.46004.30036.610
48.210512.9349.55020.8000.34003.18035.480
32.800449.1823.48015.0600.51004.04041.050
89.020550.964.94015.4000.49005.39031.200
74.990574.9326.60016.9900.45002.10035.990
67.050448.2845.51022.4600.35003.54053.600
78.700622.64−3.80023.0200.54005.72035.440
45.410477.037.73018.7900.44003.20029.950
39.300520.8552.96018.2300.37001.36026.920
123.55813.5534.43032.1300.09002.44037.210
43.770395.3528.42021.1600.32003.14058.220
22.950254.4216.85012.2400.47005.19022.720
57.680491.689.91021.6900.43005.47043.110
55.730593.4915.80016.2200.47003.26045.730
51.720511.7940.13021.9300.21004.82026.720
64.070466.4811.5809.5300.66004.04014.300
33.160476.9633.25012.0600.51003.79046.760
66.850688.5461.86025.5900.27001.74056.240
55.790509.9855.80021.4300.24002.69042.950
54.110532.3228.60022.4500.54003.96033.850
79.290587.2048.12026.5700.10001.37033.010
95.640772.6223.15025.7100.34001.13056.280
71.930524.4512.02017.8300.45002.24047.710
17.270158.8438.32020.4600.23003.95057.810
70.720445.3629.12018.0400.20001.80039.940
91.290563.83−6.96013.7400.64004.55019.740
62.140422.8127.23012.5300.34005.57038.320
52.110505.4618.11017.2600.44004.09045.020
94.160754.5813.85021.3200.34004.51034.180
68.950609.4851.99017.9600.21002.84030.840
100.4365332.33013.4500.38002.78060.990

First 60 of 400 rows.

The heatmap shows the topic correlationsTopic correlationCorrelation of two topics' centered log-ratio shares across documents; positive = they tend to appear together. across documents. Each document's shares are log-ratio scaled first, which removes the fact that shares always add to one.

04

HDP: let the text choose the number

Read

The HDPHierarchical Dirichlet process (HDP) topic modelA topic model that decides how many topics the text supports, up to a maximum, instead of being told. puts a prior on an unlimited set of topics and lets the data decide how many get used. You set the most it may use. Topics holding under 1% of the words are left out, and the card says how many.

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

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

Plots

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

Topics

TopicShare of textCoherence (UMass)Top terms
157.7%−1.359rates, interest, bank, higher, shares, profits, garlic, markets, investors, onions
224.2%−1.109team, match, striker, fans, stadium, penalty, cup, final, leaders, scored
39.9%−0.7964bake, yields, bond, bread, inflation, let, minutes, pasta, currency, golden
43.3%−0.5811rivals, match, goal, late, ended, final, cup, league, team, coach
51.6%−0.7367minutes, tomatoes, add, simmer, sauce, team, onions, coach, match, salt
61.6%−0.7765pepper, sugar, add, salt, sauce, team, gently, coach, match, soup
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
  • 2 of the 8 possible topics hold under 1% of the words and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec b2dd445350437ce0
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
TIME <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c(TEXT, TIME)))
rows <- which(!is.na(df[[TEXT]])) - 1L  # documents with text (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))

# %% Topic model
K <- 8
SEED <- 42
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# HDP: batch variational inference with at most 8 topics; topics holding under 1% of the words are dropped.
hf <- cs_topics_hdp(X, K, 15, 10, 1, 1, eta, SEED)
kept <- cs_topics_hdp_kept(hf$doc_counts)
if (length(kept) < K) warnings <- c(warnings, sprintf("%d of the %d possible topics hold under 1%% of the words and are left out.", K - length(kept), K))
TRUNCATION <- K
K <- length(kept)
doc_topic <- cs_ml_shares(hf$doc_counts[, kept, drop = FALSE])
topic_term <- cs_ml_shares(hf$lambda[kept, , drop = FALSE])
loglik <- cs_ml_loglik(X, doc_topic, topic_term)
top_terms <- cs_topics_top_terms  # weights equal to 12 decimals rank in vocabulary order
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/hdp_up_to_eight/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
  j <- top_terms(topic_term[t, ], 30)
  data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))

# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
               mean_coherence = if (length(finite)) mean(finite) else NaN,
               doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
  values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
  values[[sprintf("coherence[%d]", t)]] <- coherence[t]
  values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
  for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
values$truncation <- TRUNCATION
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

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

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

Topics

TopicShare of textCoherence (UMass)Top terms
157.7%−1.359rates, interest, bank, higher, shares, profits, garlic, markets, investors, onions
224.2%−1.109team, match, striker, fans, stadium, penalty, cup, final, leaders, scored
39.9%−0.7964bake, yields, bond, bread, inflation, let, minutes, pasta, currency, golden
43.3%−0.5811rivals, match, goal, late, ended, final, cup, league, team, coach
51.6%−0.7367minutes, tomatoes, add, simmer, sauce, team, onions, coach, match, salt
61.6%−0.7765pepper, sugar, add, salt, sauce, team, gently, coach, match, soup
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
  • 2 of the 8 possible topics hold under 1% of the words and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec b2dd445350437ce0
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
TIME = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT] if TIME is None else [TEXT, TIME])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())  # documents with text (0-based input rows)
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
    cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
    warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")

# %% Topic model
K = 8
SEED = 42
eta = None or 1.0 / K
# HDP: batch variational inference with at most 8 topics; topics holding under 1% of the words are dropped.
lam, doc_counts, _, _ = cstopics.hdp(X, K, 15, 10, 1, 1, eta, SEED)
kept = cstopics.hdp_kept(doc_counts)
if len(kept) < K:
    warnings.append(f"{K - len(kept)} of the {K} possible topics hold under 1% of the words and are left out.")
TRUNCATION = K
K = len(kept)
doc_topic = cstext.shares(doc_counts[:, kept])
topic_term = cstext.shares(lam[kept])
loglik = cstext.loglik(X, doc_topic, topic_term)
top_terms = cstopics.top_terms  # weights equal to 12 decimals rank in vocabulary order
order = cstext.canonical(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/hdp_up_to_eight/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
    topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
    for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
        term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)

# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
    "n_docs": len(rows),
    "n_terms": len(vocab),
    "n_topics": K,
    "mean_coherence": float(np.mean(finite)) if finite else float("nan"),
    "doc_check": csembed.checksum(doc_topic[:, 0], rows),
    "loglik": loglik,
}
for t in range(K):
    values[f"prevalence[{t + 1}]"] = float(prevalence[t])
    values[f"coherence[{t + 1}]"] = coherence[t]
    values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
    for j in tops[t][:5]:
        values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
values["truncation"] = TRUNCATION
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
    for j in tops[t]:
        chart_topic.append(f"Topic {t + 1}")
        chart_term.append(vocab[j])
        chart_weight.append(float(topic_term[t, j]))
cs.publish({
    "title": "Topic model",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
    "tables": [{
        "key": "topics",
        "title": "Topics",
        "columns": [
            {"key": "topic", "label": "Topic", "type": "integer"},
            {"key": "prevalence", "label": "Share of text", "type": "percent"},
            {"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
            {"key": "terms", "label": "Top terms"},
        ],
        "rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
                  "terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
    }] + extra_tables,
    "charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
        "topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
        "term": cs.col("Term", chart_term, "categorical"),
        "weight": cs.col("Weight", chart_weight, "numeric"),
    }, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
        {"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
    ] + extra_artifacts,
})

On a small corpus the count depends on the start, so treat it as a suggestion. Choose topics can then compare nearby counts with LDA or PLSA.

Choose the number of topicsRecorded · Python and R agreeRecorded 2026-11-21 · 12 values compared
R

5 topics give the most coherent top terms (mean UMass -0.96) across 2–5 topics.

Recommended topics
5
Coherence (UMass)
−0.9574

Plots

Topic coherence by number of topicsHow many clusters does the data support?

Higher (closer to 0) = top terms co-occur more often in the same documents.

View data
RecommendedTopicsMean coherence (UMass)
false2−1.258
false3−1.088
false4−1.073
true5−0.9574

Scores by number of topics

TopicsMean coherence (UMass)Log-likelihood
2−1.258−956.83
3−1.088−852.39
4−1.073−839.98
5−0.9574−777.65
  • 1 rows have no text and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Choose the number of topics
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_topics 1.1.0 · spec 5506f7b6455abeec
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = TEXT))
rows <- which(!is.na(df[[TEXT]])) - 1L
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "Choosing the number of topics")
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 = "Choosing the number of topics", reason = "no word appears in enough documents (lower the minimum documents per word)")
K_MIN <- 2; K_MAX <- 5
if (K_MAX <= K_MIN) cs_error("CS_E_INVALID_OPTION", option = "Most topics", allowed = "larger than Fewest topics", value = K_MAX)
SEED <- 42
TOP <- 10

# %% One model per number of topics
ks <- K_MIN:K_MAX
coh <- numeric(0); ll <- numeric(0)
for (K in ks) {
  fit <- cs_topics_best_of(function(sd) c(cs_topics_plsa(X, K, 80, sd), list(extra = NULL)), X, 2, SEED)
  doc_topic <- fit$doc_topic; topic_term <- fit$topic_term
  loglik <- fit$loglik
  vals <- vapply(seq_len(K), function(t) cs_ml_umass(X, cs_topics_top_terms(topic_term[t, ], TOP)), numeric(1))  # ties to 12 decimals in vocabulary order
  vals <- vals[!is.nan(vals)]
  coh <- c(coh, if (length(vals)) mean(vals) else NaN)
  ll <- c(ll, loglik)
}
finite <- which(!is.nan(coh))
if (!length(finite)) cs_error("CS_E_UNDEFINED", what = "Topic coherence", reason = "no topic had two top terms in common documents (lower the minimum documents per word)")
best <- finite[order(-round(coh[finite], 10), finite)[1]]  # most coherent; ties -> fewer topics
values <- list(n_docs = length(rows), n_terms = length(vocab), recommended_k = ks[best], best_coherence = coh[best])
for (i in seq_along(ks)) {
  values[[sprintf("coherence[%d]", ks[i])]] <- coh[i]
  values[[sprintf("loglik[%d]", ks[i])]] <- ll[i]
}
cs_publish(list(
  title = "Choose the number of topics",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics give the most coherent top terms (mean UMass %.2f) across %d–%d topics.", ks[best], coh[best], K_MIN, K_MAX),
  statistics = list(list(key = "recommended_k", label = "Recommended topics", value = ks[best], format = "integer"),
                    list(key = "best_coherence", label = "Coherence (UMass)", value = coh[best])),
  tables = list(list(key = "scores", title = "Scores by number of topics",
                     columns = list(list(key = "k", label = "Topics", type = "integer"),
                                    list(key = "coherence", label = "Mean coherence (UMass)", type = "number"),
                                    list(key = "loglik", label = "Log-likelihood", type = "number")),
                     rows = lapply(seq_along(ks), function(i) list(k = ks[i], coherence = coh[i], loglik = ll[i])))),
  charts = list(cs_chart("coherence", "elbow-plot", "Topic coherence by number of topics", list(
    k = cs_col("Topics", ks, "numeric"),
    score = cs_col("Mean coherence (UMass)", coh, "numeric"),
    chosen = cs_col("Recommended", seq_along(ks) == best, "boolean")
  ), note = "Higher (closer to 0) = top terms co-occur more often in the same documents.")),
  values = values,
  warnings = warnings
))
Python

5 topics give the most coherent top terms (mean UMass -0.96) across 2–5 topics.

Recommended topics
5
Coherence (UMass)
−0.9574

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

Scores by number of topics

TopicsMean coherence (UMass)Log-likelihood
2−1.258−956.83
3−1.088−852.39
4−1.073−839.98
5−0.9574−777.65
  • 1 rows have no text and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Choose the number of topics
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.choose_topics 1.1.0 · spec 5506f7b6455abeec
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "Choosing the number of topics")
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="Choosing the number of topics", reason="no word appears in enough documents (lower the minimum documents per word)")
K_MIN, K_MAX = 2, 5
if K_MAX <= K_MIN:
    cs.cs_error("CS_E_INVALID_OPTION", option="Most topics", allowed="larger than Fewest topics", value=K_MAX)
SEED = 42
TOP = 10

# %% One model per number of topics
ks = list(range(K_MIN, K_MAX + 1))
coh, ll = [], []
for K in ks:
    doc_topic, topic_term, loglik, _, _ = cstopics.best_of(
        lambda sd: cstopics.plsa(X, K, 80, sd) + (None,), X, 2, SEED)
    vals = [cstext.umass(X, cstopics.top_terms(topic_term[t], TOP)) for t in range(K)]  # ties to 12 decimals in vocabulary order
    vals = [v for v in vals if not np.isnan(v)]
    coh.append(float(np.mean(vals)) if vals else float("nan"))
    ll.append(float(loglik))
finite = [i for i, c in enumerate(coh) if not np.isnan(c)]
if not finite:
    cs.cs_error("CS_E_UNDEFINED", what="Topic coherence", reason="no topic had two top terms in common documents (lower the minimum documents per word)")
best = max(finite, key=lambda i: (round(coh[i], 10), -i))  # most coherent; ties → fewer topics
values = {"n_docs": len(rows), "n_terms": len(vocab), "recommended_k": ks[best], "best_coherence": coh[best]}
for K, c, l in zip(ks, coh, ll):
    values[f"coherence[{K}]"] = c
    values[f"loglik[{K}]"] = l
cs.publish({
    "title": "Choose the number of topics",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{ks[best]} topics give the most coherent top terms (mean UMass {coh[best]:.2f}) across {K_MIN}–{K_MAX} topics.",
    "statistics": [
        {"key": "recommended_k", "label": "Recommended topics", "value": ks[best], "format": "integer"},
        {"key": "best_coherence", "label": "Coherence (UMass)", "value": coh[best]},
    ],
    "tables": [{
        "key": "scores",
        "title": "Scores by number of topics",
        "columns": [{"key": "k", "label": "Topics", "type": "integer"}, {"key": "coherence", "label": "Mean coherence (UMass)", "type": "number"},
                    {"key": "loglik", "label": "Log-likelihood", "type": "number"}],
        "rows": [{"k": K, "coherence": c, "loglik": l} for K, c, l in zip(ks, coh, ll)],
    }],
    "charts": [cs.chart("coherence", "elbow-plot", "Topic coherence by number of topics", {
        "k": cs.col("Topics", ks, "numeric"),
        "score": cs.col("Mean coherence (UMass)", coh, "numeric"),
        "chosen": cs.col("Recommended", [i == best for i in range(len(ks))], "boolean"),
    }, note="Higher (closer to 0) = top terms co-occur more often in the same documents.")],
    "values": values,
    "warnings": warnings,
})
05

Topics per author

Read

The author-topic modelAuthor-topic modelTopics per author: each word comes from one of the document's authors and that author's topic mix. gives each author a topic mix. A document's words come from its authors' mixes. Put several authors in one cell with a semicolon between them. The Authors table lists each writer's main topic and document count, so you can discount writers with only one or two documents.

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

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

Plots

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

Topics

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

Authors

AuthorDocumentsMain topicShare of main topic
Ada13398.1%
Ben10398.4%
Cleo15198.5%
Dev10198.5%
Eli14298.5%
Fay10298.3%
  • 2 rows have no text or no author and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec 7d132cf53d761fde
# Dataset: top_authored (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
TIME <- NULL
AUTHORS <- "authors"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/top_authored.parquet", col_select = c(TEXT, TIME, AUTHORS)))
author_lists <- lapply(df[[AUTHORS]], cs_topics_split_authors)
rows <- which(!is.na(df[[TEXT]]) & vapply(author_lists, length, integer(1)) > 0) - 1L
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text or no author and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))

# %% Topic model
K <- 3
SEED <- 42
alpha <- NULL
if (is.null(alpha)) alpha <- 1 / K
eta <- NULL
if (is.null(eta)) eta <- 1 / K
am <- cs_topics_author_matrix(author_lists[rows + 1L])
A <- am$A
author_names <- am$names
# Author-topic model: variational Bayes from 2 host-drawn starts; the best log-likelihood is kept.
fit <- cs_topics_best_of(function(sd) {
  f <- cs_topics_author_topic(X, A, K, 15, 20, alpha, eta, sd)
  th <- cs_ml_shares(f$gamma)
  list(doc_topic = cs_topics_author_doc_topic(A, th), topic_term = cs_ml_shares(f$lambda), extra = th)
}, X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
author_theta <- fit$extra
top_terms <- cs_topics_top_terms  # weights equal to 12 decimals rank in vocabulary order
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/author_topics/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
  j <- top_terms(topic_term[t, ], 30)
  data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))

# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
               mean_coherence = if (length(finite)) mean(finite) else NaN,
               doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
  values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
  values[[sprintf("coherence[%d]", t)]] <- coherence[t]
  values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
  for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
author_theta <- author_theta[, ord, drop = FALSE]
values$n_authors <- length(author_names)
n_docs_author <- colSums(A)
authors_df <- data.frame(author = author_names, documents = as.integer(n_docs_author))
for (t in seq_len(K)) authors_df[[paste0("topic_", t)]] <- author_theta[, t]
nanoparquet::write_parquet(authors_df, file.path(out, "authors.parquet"))
extra_artifacts <- list(list(key = "authors", path = file.path(out, "authors.parquet"), format = "parquet"))
main <- apply(author_theta, 1, which.max)
extra_tables <- list(list(
  key = "authors", title = "Authors",
  columns = list(list(key = "author", label = "Author"), list(key = "documents", label = "Documents", type = "integer"),
                 list(key = "topic", label = "Main topic", type = "integer"), list(key = "share", label = "Share of main topic", type = "percent")),
  rows = lapply(seq_along(author_names), function(a) list(author = author_names[a], documents = as.integer(n_docs_author[a]),
                                                         topic = main[a], share = author_theta[a, main[a]]))
))
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

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

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

Topics

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

Authors

AuthorDocumentsMain topicShare of main topic
Ada13398.1%
Ben10398.4%
Cleo15198.5%
Dev10198.5%
Eli14298.5%
Fay10298.3%
  • 2 rows have no text or no author and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec 7d132cf53d761fde
# Dataset: top_authored (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
TIME = None
AUTHORS = "authors"
df = pd.read_parquet("tests/parity/fixtures/top_authored.parquet", columns=[c for c in (TEXT, TIME, AUTHORS) if c is not None])
author_lists = [cstopics.split_authors(a) for a in df[AUTHORS].tolist()]
rows = np.flatnonzero(df[TEXT].notna().to_numpy() & np.array([len(a) > 0 for a in author_lists], dtype=bool))
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text or no author and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
    cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
    warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")

# %% Topic model
K = 3
SEED = 42
alpha = None or 1.0 / K
eta = None or 1.0 / K
A, author_names = cstopics.author_matrix([author_lists[i] for i in rows])


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


# Author-topic model: variational Bayes from 2 host-drawn starts; the best log-likelihood is kept.
doc_topic, topic_term, loglik, start, author_theta = cstopics.best_of(_author_fit, X, 2, SEED)
top_terms = cstopics.top_terms  # weights equal to 12 decimals rank in vocabulary order
order = cstext.canonical(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/author_topics/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
    topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
    for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
        term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)

# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
    "n_docs": len(rows),
    "n_terms": len(vocab),
    "n_topics": K,
    "mean_coherence": float(np.mean(finite)) if finite else float("nan"),
    "doc_check": csembed.checksum(doc_topic[:, 0], rows),
    "loglik": loglik,
}
for t in range(K):
    values[f"prevalence[{t + 1}]"] = float(prevalence[t])
    values[f"coherence[{t + 1}]"] = coherence[t]
    values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
    for j in tops[t][:5]:
        values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
author_theta = author_theta[:, order]
values["n_authors"] = len(author_names)
n_docs_author = A.sum(axis=0)
authors_df = pd.DataFrame({"author": author_names, "documents": n_docs_author.astype(np.int64)})
for t in range(K):
    authors_df[f"topic_{t + 1}"] = author_theta[:, t]
authors_df.to_parquet(os.path.join(out, "authors.parquet"), index=False)
extra_artifacts.append({"key": "authors", "path": os.path.join(out, "authors.parquet"), "format": "parquet"})
main = np.argmax(author_theta, axis=1)
extra_tables.append({
    "key": "authors",
    "title": "Authors",
    "columns": [{"key": "author", "label": "Author"}, {"key": "documents", "label": "Documents", "type": "integer"},
                {"key": "topic", "label": "Main topic", "type": "integer"}, {"key": "share", "label": "Share of main topic", "type": "percent"}],
    "rows": [{"author": author_names[a], "documents": int(n_docs_author[a]), "topic": int(main[a]) + 1,
              "share": float(author_theta[a, main[a]])} for a in range(len(author_names))],
})
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
    for j in tops[t]:
        chart_topic.append(f"Topic {t + 1}")
        chart_term.append(vocab[j])
        chart_weight.append(float(topic_term[t, j]))
cs.publish({
    "title": "Topic model",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
    "tables": [{
        "key": "topics",
        "title": "Topics",
        "columns": [
            {"key": "topic", "label": "Topic", "type": "integer"},
            {"key": "prevalence", "label": "Share of text", "type": "percent"},
            {"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
            {"key": "terms", "label": "Top terms"},
        ],
        "rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
                  "terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
    }] + extra_tables,
    "charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
        "topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
        "term": cs.col("Term", chart_term, "categorical"),
        "weight": cs.col("Weight", chart_weight, "numeric"),
    }, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
        {"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
    ] + extra_artifacts,
})
06

Online LDA

Read

Online LDAOnline LDALDA updated from small batches of documents with a shrinking step size, so it scales to large corpora. updates the topics after each mini-batch of documents, with a step size that shrinks over time. On a small corpus it lands near batch LDA. Its value is on collections too large for many full passes.

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

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

Plots

Top terms per topicWhat is each topic about?
View data
TermTopicWeight
higherTopic 10.0592
bankTopic 10.0590
ratesTopic 10.0538
profitsTopic 10.0475
inflationTopic 10.0472
fansTopic 10.0309
interestTopic 10.0297
coachTopic 10.0237
teamTopic 10.0228
bondTopic 10.0213
sharesTopic 20.0457
ratesTopic 20.0447
interestTopic 20.0416
marketsTopic 20.0405
investorsTopic 20.0399
teamTopic 20.0395
matchTopic 20.0383
strikerTopic 20.0377
fellTopic 20.0290
madeTopic 20.0254
garlicTopic 30.0524
onionsTopic 30.0422
sauceTopic 30.0419
lemonTopic 30.0334
addTopic 30.0329
oliveTopic 30.0328
herbsTopic 30.0327
oilTopic 30.0327
simmerTopic 30.0327
bakeTopic 30.0309

Topics

TopicShare of textCoherence (UMass)Top terms
135.0%−1.296higher, bank, rates, profits, inflation, fans, interest, coach, team, bond
234.6%−1.392shares, rates, interest, markets, investors, team, match, striker, fell, made
330.5%−0.9037garlic, onions, sauce, lemon, add, olive, herbs, oil, simmer, bake
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec b02ad770d34d7157
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Documents
TEXT <- "text"
TIME <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c(TEXT, TIME)))
rows <- which(!is.na(df[[TEXT]])) - 1L  # documents with text (0-based input rows)
warnings <- list()
if (length(rows) < nrow(df)) warnings <- c(warnings, sprintf("%d rows have no text and are left out.", nrow(df) - length(rows)))
cs_check_rows(length(rows), 2, "A topic model")
texts <- as.character(df[[TEXT]][rows + 1L])
d <- cs_ml_dtm(texts, min_df = 2, max_df = 0.95, max_terms = 2000)
X <- d$X
vocab <- d$vocab
if (!length(vocab)) cs_error("CS_E_UNDEFINED", what = "A topic model", reason = "no word appears in enough documents (lower the minimum documents per word)")
empty <- sum(rowSums(X) == 0)
if (empty) warnings <- c(warnings, sprintf("%d documents have no words left after stop words and frequency limits.", empty))

# %% Topic model
K <- 3
SEED <- 42
alpha <- NULL
if (is.null(alpha)) alpha <- 1 / K
eta <- NULL
if (is.null(eta)) eta <- 1 / K
# Online variational Bayes (mini-batches of 16 documents in row order) from 2 host-drawn starts.
fit <- cs_topics_best_of(function(sd) {
  f <- cs_topics_lda_online(X, K, 10, 20, alpha, eta, sd, 16, 10, 0.7)
  list(doc_topic = cs_ml_shares(f$gamma), topic_term = cs_ml_shares(f$lambda), extra = NULL)
}, X, 2, SEED)
doc_topic <- fit$doc_topic
topic_term <- fit$topic_term
loglik <- fit$loglik
top_terms <- cs_topics_top_terms  # weights equal to 12 decimals rank in vocabulary order
ord <- cs_ml_canonical_topics(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic <- doc_topic[, ord, drop = FALSE]
topic_term <- topic_term[ord, , drop = FALSE]
TOP <- 10
tops <- lapply(seq_len(K), function(t) top_terms(topic_term[t, ], TOP))
coherence <- vapply(seq_len(K), function(t) cs_ml_umass(X, tops[[t]]), numeric(1))

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-86516/discover.topics/lda_online/out-r")
topics <- data.frame(row = as.integer(rows))
for (t in seq_len(K)) topics[[paste0("topic_", t)]] <- doc_topic[, t]
nanoparquet::write_parquet(topics, file.path(out, "topics.parquet"))
terms <- do.call(rbind, lapply(seq_len(K), function(t) {
  j <- top_terms(topic_term[t, ], 30)
  data.frame(topic = t, term = vocab[j], weight = topic_term[t, j], rank = seq_along(j))
}))
nanoparquet::write_parquet(terms, file.path(out, "terms.parquet"))

# %% Result
prevalence <- colMeans(doc_topic)
finite <- coherence[!is.nan(coherence)]
values <- list(n_docs = length(rows), n_terms = length(vocab), n_topics = K,
               mean_coherence = if (length(finite)) mean(finite) else NaN,
               doc_check = cs_ml_checksum(doc_topic[, 1], rows), loglik = loglik)
for (t in seq_len(K)) {
  values[[sprintf("prevalence[%d]", t)]] <- prevalence[t]
  values[[sprintf("coherence[%d]", t)]] <- coherence[t]
  values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
  for (j in utils::head(tops[[t]], 5)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- topic_term[t, j]
}
extra_tables <- list(); extra_charts <- list(); extra_artifacts <- list()
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart <- NULL
chart_topic <- unlist(lapply(seq_len(K), function(t) rep(paste("Topic", t), length(tops[[t]]))))
chart_term <- unlist(lapply(seq_len(K), function(t) vocab[tops[[t]]]))
chart_weight <- unlist(lapply(seq_len(K), function(t) topic_term[t, tops[[t]]]))
cs_publish(list(
  title = "Topic model",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d topics in %d documents (%d terms); topic 1 (%s, …) is the most common.",
                    K, length(rows), length(vocab), vocab[tops[[1]][1]]),
  tables = c(list(list(
    key = "topics", title = "Topics",
    columns = list(list(key = "topic", label = "Topic", type = "integer"),
                   list(key = "prevalence", label = "Share of text", type = "percent"),
                   list(key = "coherence", label = "Coherence (UMass)", type = "number"),
                   list(key = "terms", label = "Top terms")),
    rows = lapply(seq_len(K), function(t) list(topic = t, prevalence = prevalence[t], coherence = coherence[t],
                                               terms = paste(vocab[tops[[t]]], collapse = ", ")))
  )), extra_tables),
  charts = c(list(cs_chart("terms", "topic-terms", "Top terms per topic", list(
    topic = cs_col("Topic", chart_topic, "categorical", paste("Topic", seq_len(K))),
    term = cs_col("Term", chart_term, "categorical"),
    weight = cs_col("Weight", chart_weight, "numeric")
  ), controls = list(top = TOP))), if (!is.null(time_chart)) list(time_chart), extra_charts),
  values = values,
  warnings = warnings,
  artifacts = c(list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
                     list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet")), extra_artifacts)
))
Python

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

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

Topics

TopicShare of textCoherence (UMass)Top terms
135.0%−1.296higher, bank, rates, profits, inflation, fans, interest, coach, team, bond
234.6%−1.392shares, rates, interest, markets, investors, team, match, striker, fell, made
330.5%−0.9037garlic, onions, sauce, lemon, add, olive, herbs, oil, simmer, bake
  • 1 rows have no text and are left out.
  • 1 documents have no words left after stop words and frequency limits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Topic model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.topics 1.2.0 · spec b02ad770d34d7157
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import text as cstext
from codesplash.ml import topics_ext as cstopics

# %% Documents
TEXT = "text"
TIME = None
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=[TEXT] if TIME is None else [TEXT, TIME])
rows = np.flatnonzero(df[TEXT].notna().to_numpy())  # documents with text (0-based input rows)
warnings = []
if len(rows) < len(df):
    warnings.append(f"{len(df) - len(rows)} rows have no text and are left out.")
cs.check_rows(len(rows), 2, "A topic model")
texts = df[TEXT].iloc[rows].tolist()
X, vocab = cstext.dtm(texts, min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
    cs.cs_error("CS_E_UNDEFINED", what="A topic model", reason="no word appears in enough documents (lower the minimum documents per word)")
empty = int((X.sum(axis=1) == 0).sum())
if empty:
    warnings.append(f"{empty} documents have no words left after stop words and frequency limits.")

# %% Topic model
K = 3
SEED = 42
alpha = None or 1.0 / K
eta = None or 1.0 / K
# Online variational Bayes (mini-batches of 16 documents in row order) from 2 host-drawn starts.
doc_topic, topic_term, loglik, start, _ = cstopics.best_of(lambda sd: tuple(cstext.shares(m) for m in cstopics.lda_online(
    X, K, 10, 20, alpha, eta, sd, 16, 10, 0.7)) + (None,), X, 2, SEED)
top_terms = cstopics.top_terms  # weights equal to 12 decimals rank in vocabulary order
order = cstext.canonical(doc_topic, topic_term, vocab)  # topics by prevalence
doc_topic = doc_topic[:, order]
topic_term = topic_term[order]
TOP = 10
tops = [top_terms(topic_term[t], TOP) for t in range(K)]
coherence = [cstext.umass(X, tops[t]) for t in range(K)]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-86516/discover.topics/lda_online/out-python")
topics = pd.DataFrame({"row": rows.astype(np.int64)})
for t in range(K):
    topics[f"topic_{t + 1}"] = doc_topic[:, t]
topics.to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = []
for t in range(K):
    for rank, j in enumerate(top_terms(topic_term[t], 30), start=1):
        term_rows.append({"topic": t + 1, "term": vocab[j], "weight": float(topic_term[t, j]), "rank": rank})
pd.DataFrame(term_rows).to_parquet(os.path.join(out, "terms.parquet"), index=False)

# %% Result
prevalence = doc_topic.mean(axis=0)
finite = [c for c in coherence if not np.isnan(c)]
values = {
    "n_docs": len(rows),
    "n_terms": len(vocab),
    "n_topics": K,
    "mean_coherence": float(np.mean(finite)) if finite else float("nan"),
    "doc_check": csembed.checksum(doc_topic[:, 0], rows),
    "loglik": loglik,
}
for t in range(K):
    values[f"prevalence[{t + 1}]"] = float(prevalence[t])
    values[f"coherence[{t + 1}]"] = coherence[t]
    values[f"top_term[{t + 1}]"] = vocab[tops[t][0]]
    for j in tops[t][:5]:
        values[f"weight[{t + 1}:{vocab[j]}]"] = float(topic_term[t, j])
extra_tables, extra_charts, extra_artifacts = [], [], []
# %% Topics over time: each document's topic shares summed per period (every distinct time up to 40, else 24 equal-width bins).
time_chart = None
chart_topic, chart_term, chart_weight = [], [], []
for t in range(K):
    for j in tops[t]:
        chart_topic.append(f"Topic {t + 1}")
        chart_term.append(vocab[j])
        chart_weight.append(float(topic_term[t, j]))
cs.publish({
    "title": "Topic model",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": len(rows),
    "summary": f"{K} topics in {len(rows)} documents ({len(vocab)} terms); topic 1 ({vocab[tops[0][0]]}, …) is the most common.",
    "tables": [{
        "key": "topics",
        "title": "Topics",
        "columns": [
            {"key": "topic", "label": "Topic", "type": "integer"},
            {"key": "prevalence", "label": "Share of text", "type": "percent"},
            {"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
            {"key": "terms", "label": "Top terms"},
        ],
        "rows": [{"topic": t + 1, "prevalence": prevalence[t], "coherence": coherence[t],
                  "terms": ", ".join(vocab[j] for j in tops[t])} for t in range(K)],
    }] + extra_tables,
    "charts": [cs.chart("terms", "topic-terms", "Top terms per topic", {
        "topic": cs.col("Topic", chart_topic, "categorical", [f"Topic {t + 1}" for t in range(K)]),
        "term": cs.col("Term", chart_term, "categorical"),
        "weight": cs.col("Weight", chart_weight, "numeric"),
    }, controls={"top": TOP})] + ([time_chart] if time_chart else []) + extra_charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [
        {"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
        {"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
    ] + extra_artifacts,
})
07

Check your understanding

Checkpoint

Check yourself

An HDP with a limit of 20 topics reports 6. What does that mean?

Show the answer

Answer: b

The HDP's count is a fitted quantity that depends on the start and the priors, not a proof. Check nearby counts with Choose topics.

Check yourself

In a correlated topic model, topics 2 and 5 have a correlation of 0.6. What's the safe reading?

Show the answer

Answer: a

The correlation is across documents' topic shares. It describes co-occurrence in this corpus, not cause or word overlap.

Check yourself

PLSA and LDA give similar topics on a large corpus but PLSA's are noisier on 200 short documents. Why?

Show the answer

Answer: b

LDA's Dirichlet priors pull documents toward few topics and topics toward focused words. That regularization matters most on small collections.

Check yourself

An author with a single short document gets a main topic share of 95%. How much should you trust it?

Show the answer

Answer: b

An author's mix is estimated from that author's words only. Check the Documents column before reading a writer's profile.

08

Recap

Read
  • PLSA drops the priors; the correlated topic model lets topics go together; HDP picks the number of topics; the author-topic model gives mixes to authors; online LDA updates from batches.
  • Correlations describe co-occurrence across documents, not causes.
  • An HDP count and a single-document author profile are both weak evidence on small data.

Concepts in this lesson