Topics from meaning with BERTopic
BERTopic turns each document into an embedding, groups dense regions into topics and names them with class-based TF-IDF. Learn what the outlier topic means, when a pretrained embedder helps, and how much to trust the result.
What runs in CodeSplash
- BERTopic (embeddings, clustering, c-TF-IDF) Experimental
You will be able to
- Describe the four stages of BERTopic and what each one decides
- Read the outlier group and the topic sizes honestly
- Choose between TF-IDF + SVD and a pretrained sentence embedder
Four stages, four choices
ReadBERTopic chains four steps. Each document becomes an embeddingSentence embeddingA fixed-length vector for a whole text from a model trained so that texts with similar meaning get nearby vectors., a list of numbers. UMAP squeezes those into a few dimensions. HDBSCAN finds dense groups, and those groups are the topics. Finally class-based TF-IDFClass-based TF-IDF (c-TF-IDF)TF-IDF with each topic's documents joined into one document: a word ranks high when it is frequent in this topic and rare in the others. names each topic by the words that are common in it and rare elsewhere.
Unlike LDA, a document belongs to one topic, or to none.
Guess the outliers
PredictPredict first
On 180 short documents in six themes, with a smallest topic of 12, what share of documents will fit no topic?
Make your guess between 0 and 50 %, then reveal.
Reveal
The run left 0.0% as outliers and found 6 topics. Clear themes give few outliers; mixed text gives many.
The outlier group is information
ExploreView data
| topic | documents | top terms | outliers |
|---|---|---|---|
| Topic 1 | 219 | goal, match, striker, league | false |
| Topic 2 | 159 | dough, oven, bread, yeast | false |
| Topic 3 | 145 | rates, bond, inflation, yields | false |
| Topic 4 | 107 | storm, rain, forecast, wind | false |
| Topic 5 | 61 | roses, compost, pruning, soil | false |
| Outliers | 108 | said, people, week | true |
The gray bar holds outliersOutlier topicDocuments that HDBSCAN leaves in no dense group; BERTopic reports them as topic −1.: documents in no dense region. They're short, generic or off-topic. Raise the smallest topic size and the gray bar grows; lower it and you get many tiny topics.
Assign outliers to the nearest topic empties the bar, but it also hides which documents fit poorly. Keep them visible while you explore.
Which embedding?
CheckpointTF-IDF + SVD needs no download and runs anywhere. It groups documents that share words.
all-MiniLM-L6-v2 is a small pretrained sentence model, about 90 MB, downloaded only after you agree on the Topics page. It places "refund" near "money back" even when no word is shared. It runs on this computer in Python and R, and your text is never sent anywhere.
Check yourself
Two reviews say "the parcel never came" and "my order was not delivered". Which embedding is more likely to put them in one topic?
Show the answer
Answer: b
The two share almost no words, so a word-count embedding sees them as far apart. A sentence model was trained so paraphrases land close together.
Read the card
In the app6 topics in 180 documents (TF-IDF + SVD embeddings); 0 outliers.
- Topics
- 6
- Outliers
- 0.0%
- Mean coherence (UMass)
- −0.6890
- Topic diversity
- 1
Plots
View data
| Documents | Outliers | Top terms | Topic |
|---|---|---|---|
| 30 | false | stadium, midfield, coach, striker | Topic 1 |
| 30 | false | pruning, seeds, mulch, compost | Topic 2 |
| 30 | false | sugar, knead, pastry, crust | Topic 3 |
| 30 | false | clouds, sunshine, storm, thunder | Topic 4 |
| 30 | false | galaxy, orbit, astronaut, probe | Topic 5 |
| 30 | false | dividend, yields, inflation, investors | Topic 6 |
View data
| Topic | PC 1 | PC 2 |
|---|---|---|
| 1 | 0.1187 | −0.0662 |
| 2 | 0.3927 | 0.4384 |
| 3 | −0.1624 | −0.6197 |
| 2 | 0.3803 | 0.4151 |
| 3 | −0.1175 | −0.5983 |
| 4 | 0.0464 | 0.0144 |
| 3 | −0.1648 | −0.6774 |
| 5 | 0.2908 | −0.1158 |
| 5 | 0.2699 | −0.1279 |
| 5 | 0.3176 | −0.1148 |
| 3 | −0.0912 | −0.5303 |
| 5 | 0.3111 | −0.1016 |
| 3 | −0.1856 | −0.4290 |
| 4 | 0.0812 | −0.0279 |
| 4 | 0.0964 | 0.0739 |
| 4 | −0.0086 | 0.0631 |
| 4 | 0.0365 | −0.0178 |
| 2 | 0.3113 | 0.4577 |
| 1 | 0.1106 | −0.0189 |
| 2 | 0.2762 | 0.2717 |
| 5 | 0.2425 | −0.0962 |
| 1 | 0.0856 | −0.0455 |
| 6 | −0.6543 | 0.4051 |
| 1 | 0.0975 | −0.0959 |
| 2 | 0.2799 | 0.3338 |
| 6 | −0.4140 | 0.2525 |
| 2 | 0.4348 | 0.4667 |
| 6 | −0.6139 | 0.3520 |
| 3 | −0.1181 | −0.5903 |
| 1 | 0.1215 | −0.0505 |
| 3 | −0.2477 | −0.5563 |
| 1 | 0.1953 | 0.0272 |
| 6 | −0.6393 | 0.3363 |
| 3 | −0.2152 | −0.5086 |
| 1 | 0.1631 | −0.0519 |
| 6 | −0.6519 | 0.2587 |
| 1 | 0.1322 | −0.0342 |
| 1 | 0.1706 | −0.0002 |
| 3 | −0.2270 | −0.5063 |
| 2 | 0.4201 | 0.4611 |
| 2 | 0.3757 | 0.3536 |
| 6 | −0.7198 | 0.3892 |
| 2 | 0.3943 | 0.4176 |
| 2 | 0.4009 | 0.3969 |
| 1 | 0.1749 | −0.0475 |
| 6 | −0.7050 | 0.3183 |
| 2 | 0.4004 | 0.4232 |
| 2 | 0.2653 | 0.4029 |
| 5 | 0.2783 | −0.1200 |
| 4 | 0.0551 | 0.0302 |
| 2 | 0.3449 | 0.4184 |
| 5 | 0.2786 | −0.1648 |
| 3 | −0.1177 | −0.6109 |
| 5 | 0.2751 | −0.0586 |
| 6 | −0.7221 | 0.3715 |
| 5 | 0.2187 | −0.0864 |
| 6 | −0.6132 | 0.2818 |
| 1 | 0.1290 | −0.0260 |
| 3 | −0.1572 | −0.6779 |
| 4 | −0.0082 | −0.0758 |
First 60 of 180 rows.
View data
| Term | Topic | c-TF-IDF |
|---|---|---|
| stadium | Topic 1 | 0.2161 |
| midfield | Topic 1 | 0.2026 |
| coach | Topic 1 | 0.1998 |
| striker | Topic 1 | 0.1912 |
| season | Topic 1 | 0.1792 |
| match | Topic 1 | 0.1773 |
| league | Topic 1 | 0.1697 |
| goal | Topic 1 | 0.1613 |
| pruning | Topic 2 | 0.2114 |
| seeds | Topic 2 | 0.2091 |
| mulch | Topic 2 | 0.1902 |
| compost | Topic 2 | 0.1850 |
| hedge | Topic 2 | 0.1847 |
| greenhouse | Topic 2 | 0.1790 |
| tomatoes | Topic 2 | 0.1645 |
| watering | Topic 2 | 0.1611 |
| sugar | Topic 3 | 0.2143 |
| knead | Topic 3 | 0.1934 |
| pastry | Topic 3 | 0.1934 |
| crust | Topic 3 | 0.1910 |
| oven | Topic 3 | 0.1782 |
| recipe | Topic 3 | 0.1782 |
| loaf | Topic 3 | 0.1605 |
| butter | Topic 3 | 0.1563 |
| clouds | Topic 4 | 0.2225 |
| sunshine | Topic 4 | 0.1921 |
| storm | Topic 4 | 0.1918 |
| thunder | Topic 4 | 0.1888 |
| rain | Topic 4 | 0.1770 |
| wind | Topic 4 | 0.1743 |
| temperature | Topic 4 | 0.1708 |
| showers | Topic 4 | 0.1608 |
| galaxy | Topic 5 | 0.2021 |
| orbit | Topic 5 | 0.2021 |
| astronaut | Topic 5 | 0.2018 |
| probe | Topic 5 | 0.1921 |
| planet | Topic 5 | 0.1845 |
| rocket | Topic 5 | 0.1710 |
| mission | Topic 5 | 0.1685 |
| launch | Topic 5 | 0.1629 |
| dividend | Topic 6 | 0.2174 |
| yields | Topic 6 | 0.1921 |
| inflation | Topic 6 | 0.1895 |
| investors | Topic 6 | 0.1870 |
| shares | Topic 6 | 0.1813 |
| rates | Topic 6 | 0.1792 |
| stocks | Topic 6 | 0.1785 |
| earnings | Topic 6 | 0.1757 |
Assumptions
- Enough documents — 180 documents for a smallest topic of 12. With so few documents, expect broad topics and many outliers.
- English text — The stop list and the pretrained embedder are English.
- Stochastic layout — PCA is deterministic: the same data give the same topics.
Topics
| Topic | Documents | Share of documents | Coherence (UMass) | Top terms (c-TF-IDF) |
|---|---|---|---|---|
| 1 | 30 | 16.7% | −0.7547 | stadium, midfield, coach, striker, season, match, league, goal |
| 2 | 30 | 16.7% | −0.6609 | pruning, seeds, mulch, compost, hedge, greenhouse, tomatoes, watering |
| 3 | 30 | 16.7% | −0.6620 | sugar, knead, pastry, crust, oven, recipe, loaf, butter |
| 4 | 30 | 16.7% | −0.7320 | clouds, sunshine, storm, thunder, rain, wind, temperature, showers |
| 5 | 30 | 16.7% | −0.6908 | galaxy, orbit, astronaut, probe, planet, rocket, mission, launch |
| 6 | 30 | 16.7% | −0.6336 | dividend, yields, inflation, investors, shares, rates, stocks, earnings |
- 3 rows have no text, or no words left after stop words and frequency limits, and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# BERTopic (embeddings, clustering, c-TF-IDF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bertopic 1.0.0 · spec 01804ede3fc6be52
# Dataset: ml_topics (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Documents (rows with text and at least one vocabulary word)
TEXT <- "text"
EMBEDDING <- "lsa"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_topics.parquet"))
warnings <- list()
txt <- as.character(df[[TEXT]])
has_text <- !is.na(txt) & nzchar(trimws(txt, whitespace = "[\\h\\v]"))
d <- cs_ml_dtm(ifelse(has_text, txt, NA), min_df = 2, max_df = 0.95, max_terms = 2000)
vocab <- d$vocab
if (!length(vocab)) stop("No word appears in enough documents — lower the minimum documents per word.")
rows <- which(has_text & rowSums(d$X) > 0) # 1-based input rows
n_left_out <- nrow(df) - length(rows)
if (n_left_out) warnings <- c(warnings, sprintf("%d rows have no text, or no words left after stop words and frequency limits, and are left out.", n_left_out))
X <- d$X[rows, , drop = FALSE]
texts <- txt[rows]
# %% Embeddings
embed_kept <- NULL
lsa <- cs_bt_embed_lsa(cs_ml_tfidf(X), 20) # TF-IDF + truncated SVD, unit rows
E <- lsa$E
embed_kept <- lsa$kept
n <- length(rows)
MIN_SIZE <- 12
if (MIN_SIZE >= n) stop(sprintf("The smallest topic size %d needs more than %d documents.", MIN_SIZE, MIN_SIZE))
# %% Dimension reduction
Z <- cs_bt_pca_scores(E, min(5, ncol(E)))
# %% Density clustering -> topics (1..k by size, -1 = outlier)
hd <- dbscan::hdbscan(Z, minPts = MIN_SIZE)
topics <- cs_bt_canonical_topics(ifelse(hd$cluster == 0L, -1L, hd$cluster - 1L))
n_outliers_found <- sum(topics == -1)
k <- if (any(topics > 0)) max(topics) else 0L
if (k == 0) warnings <- c(warnings, "No dense group of documents was found: every document is an outlier. Lower the smallest topic size.")
# %% Topic words: class-based TF-IDF (outliers are a class of their own, as in BERTopic)
classes <- c(seq_len(k), if (any(topics == -1)) -1L)
W <- if (length(classes)) cs_bt_ctfidf(X, topics, classes) else matrix(0, 0, length(vocab))
TOP <- 8
tops <- lapply(seq_along(classes), function(i) cs_bt_top_terms(W[i, ], TOP))
coherence <- vapply(seq_len(k), function(t) if (length(tops[[t]]) >= 2) cs_ml_umass(X, tops[[t]]) else NaN, 0)
finite <- coherence[!is.nan(coherence)]
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.bertopic/lsa_pca_deterministic/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows - 1L), topic = as.integer(topics)), file.path(out, "topics.parquet"))
term_rows <- do.call(rbind, c(list(data.frame(topic = integer(0), term = character(0), weight = numeric(0), rank = integer(0))),
lapply(seq_along(classes), function(i) {
j <- cs_bt_top_terms(W[i, ], 30)
if (!length(j)) return(NULL)
data.frame(topic = as.integer(classes[i]), term = vocab[j], weight = W[i, j], rank = seq_along(j))
})))
nanoparquet::write_parquet(term_rows, file.path(out, "terms.parquet"))
M <- cs_bt_pca_scores(E, 2)
if (ncol(M) < 2) M <- cbind(M[, 1], 0)
nanoparquet::write_parquet(data.frame(row = as.integer(rows - 1L), dim_1 = M[, 1], dim_2 = M[, 2]), file.path(out, "map.parquet"))
# %% Result
LABEL <- c(lsa = "TF-IDF + SVD", minilm = "all-MiniLM-L6-v2", ollama = "Ollama")[[EMBEDDING]]
values <- list(n_docs = n, n_left_out = n_left_out, n_terms = length(vocab), embedding = LABEL, embed_dims = ncol(E),
n_topics = k, n_outliers = sum(topics == -1), outlier_share = mean(topics == -1),
mean_coherence = if (length(finite)) mean(finite) else NULL,
diversity = if (k) cs_bt_diversity(tops[seq_len(k)]) else NULL)
if (!is.null(embed_kept)) values$embed_kept <- embed_kept
for (t in seq_len(k)) {
values[[sprintf("size[%d]", t)]] <- sum(topics == t)
values[[sprintf("share[%d]", t)]] <- mean(topics == t)
values[[sprintf("coherence[%d]", t)]] <- coherence[t]
if (length(tops[[t]])) {
values[[sprintf("top_term[%d]", t)]] <- vocab[tops[[t]][1]]
for (j in utils::head(tops[[t]], 3)) values[[sprintf("weight[%d:%s]", t, vocab[j])]] <- W[t, j]
}
}
names_c <- ifelse(classes == -1, "Outliers", paste("Topic", classes))
table_rows <- lapply(seq_along(classes), function(i) {
c <- classes[i]
list(topic = c, docs = sum(topics == c), prevalence = mean(topics == c),
coherence = if (c > 0) coherence[c] else NULL, terms = paste(vocab[tops[[i]]], collapse = ", "))
})
ok_n <- n >= 20 * max(MIN_SIZE, 1)
is_umap <- FALSE
assumptions <- list(
list(key = "enough_documents", label = "Enough documents", status = if (ok_n) "pass" else "warn",
detail = paste0(sprintf("%d documents for a smallest topic of %d.", n, MIN_SIZE), if (ok_n) "" else " With so few documents, expect broad topics and many outliers.")),
list(key = "language", label = "English text", status = "info", detail = "The stop list and the pretrained embedder are English."),
list(key = "stochastic", label = "Stochastic layout", status = if (is_umap) "info" else "pass",
detail = if (is_umap) "UMAP depends on the seed; rerun with another seed to see which topics are stable." else "PCA is deterministic: the same data give the same topics.")
)
if (values$outlier_share > 0.4) warnings <- c(warnings, sprintf("%s of documents are outliers; a smaller topic size or outlier assignment groups more of them.", paste0(round(values$outlier_share * 100), "%")))
show <- cs_ml_sample_rows(n, 5000)
level_names <- c(as.character(seq_len(k)), if (any(topics == -1)) "-1")
charts <- list(
cs_chart("sizes", "topic-sizes", "Topic sizes", list(
topic = cs_col("Topic", names_c, "categorical", names_c),
docs = cs_col("Documents", vapply(classes, function(c) sum(topics == c), 0), "numeric"),
terms = cs_col("Top terms", vapply(seq_along(classes), function(i) paste(vocab[utils::head(tops[[i]], 4)], collapse = ", "), ""), "categorical"),
outlier = cs_col("Outliers", classes == -1, "boolean")
)),
cs_chart("map", "cluster-scatter", "Documents by topic (PCA of the embeddings)", list(
x = cs_col("PC 1", M[show, 1], "numeric"),
y = cs_col("PC 2", M[show, 2], "numeric"),
cluster = cs_col("Topic", as.character(topics[show]), "categorical", level_names)
), note = if (length(show) == n) NULL else sprintf("%s of %s documents shown.", format(length(show), big.mark = ","), format(n, big.mark = ",")))
)
if (k) {
charts[[3]] <- cs_chart("terms", "topic-terms", "Top terms per topic (class-based TF-IDF)", list(
topic = cs_col("Topic", unlist(lapply(seq_len(k), function(t) rep(paste("Topic", t), length(tops[[t]])))), "categorical", paste("Topic", seq_len(k))),
term = cs_col("Term", unlist(lapply(seq_len(k), function(t) vocab[tops[[t]]])), "categorical"),
weight = cs_col("c-TF-IDF", unlist(lapply(seq_len(k), function(t) W[t, tops[[t]]])), "numeric")
), controls = list(top = TOP))
}
cs_publish(list(
title = "BERTopic (embeddings, clustering, c-TF-IDF)",
engine = cs_engine_info("codesplashr", "dbscan", "nanoparquet"),
n = n,
summary = sprintf("%d topics in %d documents (%s embeddings); %d outliers.", k, n, LABEL, values$n_outliers),
statistics = list(
list(key = "n_topics", label = "Topics", value = k),
list(key = "outlier_share", label = "Outliers", value = values$outlier_share, format = "percent"),
list(key = "mean_coherence", label = "Mean coherence (UMass)", value = values$mean_coherence),
list(key = "diversity", label = "Topic diversity", value = values$diversity)
),
tables = list(list(
key = "topics", title = "Topics",
columns = list(list(key = "topic", label = "Topic", type = "integer"),
list(key = "docs", label = "Documents", type = "integer"),
list(key = "prevalence", label = "Share of documents", type = "percent"),
list(key = "coherence", label = "Coherence (UMass)", type = "number"),
list(key = "terms", label = "Top terms (c-TF-IDF)")),
rows = table_rows
)),
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
notes = if (FALSE && n_outliers_found) list(sprintf("%d outliers were assigned to their nearest topic.", n_outliers_found)) else list(),
artifacts = list(list(key = "topics", path = file.path(out, "topics.parquet"), format = "parquet"),
list(key = "terms", path = file.path(out, "terms.parquet"), format = "parquet"),
list(key = "map", path = file.path(out, "map.parquet"), format = "parquet"))
))
6 topics in 180 documents (TF-IDF + SVD embeddings); 0 outliers.
- Topics
- 6
- Outliers
- 0.0%
- Mean coherence (UMass)
- −0.6890
- Topic diversity
- 1
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough documents — 180 documents for a smallest topic of 12. With so few documents, expect broad topics and many outliers.
- English text — The stop list and the pretrained embedder are English.
- Stochastic layout — PCA is deterministic: the same data give the same topics.
Topics
| Topic | Documents | Share of documents | Coherence (UMass) | Top terms (c-TF-IDF) |
|---|---|---|---|---|
| 1 | 30 | 16.7% | −0.7547 | stadium, midfield, coach, striker, season, match, league, goal |
| 2 | 30 | 16.7% | −0.6609 | pruning, seeds, mulch, compost, hedge, greenhouse, tomatoes, watering |
| 3 | 30 | 16.7% | −0.6620 | sugar, knead, pastry, crust, oven, recipe, loaf, butter |
| 4 | 30 | 16.7% | −0.7320 | clouds, sunshine, storm, thunder, rain, wind, temperature, showers |
| 5 | 30 | 16.7% | −0.6908 | galaxy, orbit, astronaut, probe, planet, rocket, mission, launch |
| 6 | 30 | 16.7% | −0.6336 | dividend, yields, inflation, investors, shares, rates, stocks, earnings |
- 3 rows have no text, or no words left after stop words and frequency limits, and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# BERTopic (embeddings, clustering, c-TF-IDF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bertopic 1.0.0 · spec 01804ede3fc6be52
# Dataset: ml_topics (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import warnings as _warnings
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.text import bertopic as bt
from sklearn.cluster import HDBSCAN
# %% Documents (rows with text and at least one vocabulary word)
TEXT = "text"
EMBEDDING = "lsa"
df = pd.read_parquet("tests/parity/fixtures/ml_topics.parquet")
warnings = []
has_text = df[TEXT].notna().to_numpy() & (df[TEXT].astype("string").str.strip().fillna("") != "").to_numpy()
X_all, vocab = cstext.dtm(df[TEXT].where(has_text, None).tolist(), min_df=2, max_df=0.95, max_terms=2000)
if not vocab:
raise ValueError("No word appears in enough documents — lower the minimum documents per word.")
rows = np.flatnonzero(has_text & (X_all.sum(axis=1) > 0)) # 0-based input rows
n_left_out = len(df) - len(rows)
if n_left_out:
warnings.append(f"{n_left_out} rows have no text, or no words left after stop words and frequency limits, and are left out.")
X = X_all[rows]
texts = [str(df[TEXT].iloc[i]) for i in rows]
# %% Embeddings
embed_kept = None
E, embed_kept = bt.embed_lsa(cstext.tfidf(X), 20) # TF-IDF + truncated SVD, unit rows
n = len(rows)
MIN_SIZE = 12
if MIN_SIZE >= n:
raise ValueError(f"The smallest topic size {MIN_SIZE} needs more than {MIN_SIZE} documents.")
# %% Dimension reduction
Z = bt.pca_scores(E, min(5, E.shape[1]))
# %% Density clustering → topics (1…k by size, −1 = outlier)
hd = HDBSCAN(min_cluster_size=MIN_SIZE, min_samples=MIN_SIZE, cluster_selection_method="eom", copy=True).fit(Z)
topics = bt.canonical_topics(hd.labels_.astype(np.int64))
n_outliers_found = int(np.sum(topics == -1))
k = int(topics.max()) if np.any(topics > 0) else 0
if k == 0:
warnings.append("No dense group of documents was found: every document is an outlier. Lower the smallest topic size.")
# %% Topic words: class-based TF-IDF (outliers are a class of their own, as in BERTopic)
classes = list(range(1, k + 1)) + ([-1] if np.any(topics == -1) else [])
W = bt.ctfidf(X, topics, classes) if classes else np.zeros((0, len(vocab)))
TOP = 8
tops = [bt.top_terms(W[i], TOP) for i in range(len(classes))]
coherence = [cstext.umass(X, tops[i]) if len(tops[i]) >= 2 else float("nan") for i in range(k)]
finite = [c for c in coherence if not np.isnan(c)]
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.bertopic/lsa_pca_deterministic/out-python")
pd.DataFrame({"row": rows.astype(np.int64), "topic": topics}).to_parquet(os.path.join(out, "topics.parquet"), index=False)
term_rows = [{"topic": c, "term": vocab[j], "weight": float(W[i, j]), "rank": r}
for i, c in enumerate(classes) for r, j in enumerate(bt.top_terms(W[i], 30), start=1)]
pd.DataFrame(term_rows, columns=["topic", "term", "weight", "rank"]).to_parquet(os.path.join(out, "terms.parquet"), index=False)
M = bt.pca_scores(E, 2)
if M.shape[1] < 2:
M = np.column_stack([M[:, 0], np.zeros(n)])
pd.DataFrame({"row": rows.astype(np.int64), "dim_1": M[:, 0], "dim_2": M[:, 1]}).to_parquet(os.path.join(out, "map.parquet"), index=False)
# %% Result
LABEL = {"lsa": "TF-IDF + SVD", "minilm": "all-MiniLM-L6-v2", "ollama": "Ollama"}[EMBEDDING]
values = {
"n_docs": n, "n_left_out": n_left_out, "n_terms": len(vocab), "embedding": LABEL, "embed_dims": int(E.shape[1]),
"n_topics": k, "n_outliers": int(np.sum(topics == -1)), "outlier_share": float(np.mean(topics == -1)),
"mean_coherence": float(np.mean(finite)) if finite else None,
"diversity": bt.diversity([tops[i] for i in range(k)]) if k else None,
}
if embed_kept is not None:
values["embed_kept"] = embed_kept
for t in range(1, k + 1):
values[f"size[{t}]"] = int(np.sum(topics == t))
values[f"share[{t}]"] = float(np.mean(topics == t))
values[f"coherence[{t}]"] = coherence[t - 1]
if tops[t - 1]:
values[f"top_term[{t}]"] = vocab[tops[t - 1][0]]
for j in tops[t - 1][:3]:
values[f"weight[{t}:{vocab[j]}]"] = float(W[t - 1, j])
names = {c: ("Outliers" if c == -1 else f"Topic {c}") for c in classes}
table_rows = [{"topic": c, "docs": int(np.sum(topics == c)), "prevalence": float(np.mean(topics == c)),
"coherence": coherence[c - 1] if c > 0 else None, "terms": ", ".join(vocab[j] for j in tops[i])}
for i, c in enumerate(classes)]
assumptions = [
{"key": "enough_documents", "label": "Enough documents", "status": "pass" if n >= 20 * max(MIN_SIZE, 1) else "warn",
"detail": f"{n} documents for a smallest topic of {MIN_SIZE}." + ("" if n >= 20 * max(MIN_SIZE, 1) else " With so few documents, expect broad topics and many outliers.")},
{"key": "language", "label": "English text", "status": "info", "detail": "The stop list and the pretrained embedder are English."},
{"key": "stochastic", "label": "Stochastic layout", "status": "info" if "pca" == "umap" else "pass",
"detail": "UMAP depends on the seed; rerun with another seed to see which topics are stable." if "pca" == "umap" else "PCA is deterministic: the same data give the same topics."},
]
if values["outlier_share"] > 0.4:
warnings.append(f"{values['outlier_share']:.0%} of documents are outliers; a smaller topic size or outlier assignment groups more of them.")
show = csembed.sample_rows(n, 5000)
level_names = [str(t) for t in range(1, k + 1)] + (["-1"] if np.any(topics == -1) else [])
charts = [
cs.chart("sizes", "topic-sizes", "Topic sizes", {
"topic": cs.col("Topic", [names[c] for c in classes], "categorical", [names[c] for c in classes]),
"docs": cs.col("Documents", [int(np.sum(topics == c)) for c in classes], "numeric"),
"terms": cs.col("Top terms", [", ".join(vocab[j] for j in tops[i][:4]) for i in range(len(classes))], "categorical"),
"outlier": cs.col("Outliers", [c == -1 for c in classes], "boolean"),
}),
cs.chart("map", "cluster-scatter", "Documents by topic (PCA of the embeddings)", {
"x": cs.col("PC 1", M[show, 0], "numeric"),
"y": cs.col("PC 2", M[show, 1], "numeric"),
"cluster": cs.col("Topic", [str(int(t)) for t in topics[show]], "categorical", level_names),
}, note=None if len(show) == n else f"{len(show):,} of {n:,} documents shown."),
]
if k:
charts.append(cs.chart("terms", "topic-terms", "Top terms per topic (class-based TF-IDF)", {
"topic": cs.col("Topic", [f"Topic {t}" for t in range(1, k + 1) for _ in tops[t - 1]], "categorical", [f"Topic {t}" for t in range(1, k + 1)]),
"term": cs.col("Term", [vocab[j] for t in range(k) for j in tops[t]], "categorical"),
"weight": cs.col("c-TF-IDF", [float(W[t, j]) for t in range(k) for j in tops[t]], "numeric"),
}, controls={"top": TOP}))
cs.publish({
"title": "BERTopic (embeddings, clustering, c-TF-IDF)",
"engine": cs.engine_info("numpy", "scikit-learn", "pandas"),
"n": n,
"summary": f"{k} topics in {n} documents ({LABEL} embeddings); {values['n_outliers']} outliers.",
"statistics": [
{"key": "n_topics", "label": "Topics", "value": k},
{"key": "outlier_share", "label": "Outliers", "value": values["outlier_share"], "format": "percent"},
{"key": "mean_coherence", "label": "Mean coherence (UMass)", "value": values["mean_coherence"]},
{"key": "diversity", "label": "Topic diversity", "value": values["diversity"]},
],
"tables": [{
"key": "topics", "title": "Topics",
"columns": [
{"key": "topic", "label": "Topic", "type": "integer"},
{"key": "docs", "label": "Documents", "type": "integer"},
{"key": "prevalence", "label": "Share of documents", "type": "percent"},
{"key": "coherence", "label": "Coherence (UMass)", "type": "number"},
{"key": "terms", "label": "Top terms (c-TF-IDF)"},
],
"rows": table_rows,
}],
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"notes": [f"{n_outliers_found} outliers were assigned to their nearest topic."] if False and n_outliers_found else [],
"artifacts": [
{"key": "topics", "path": os.path.join(out, "topics.parquet"), "format": "parquet"},
{"key": "terms", "path": os.path.join(out, "terms.parquet"), "format": "parquet"},
{"key": "map", "path": os.path.join(out, "map.parquet"), "format": "parquet"},
],
})
The table lists each topic's size and its distinctive words. With PCA instead of UMAP the run is deterministic: 6 topics with a mean coherence of −0.689. UMAP depends on the seed, so rerun with another seed before you name a small topic.
Check your understanding
CheckpointCheck yourself
What makes a word rank high in a topic's c-TF-IDF list?
Show the answer
Answer: b
c-TF-IDF treats all of a topic's documents as one class document and down-weights words spread across every class.
Check yourself
A run leaves 45% of documents as outliers. What's the most useful next step?
Show the answer
Answer: b
Outliers tell you the settings or the embedding don't separate this text well. Hiding them by assignment doesn't fix that.
Do it on your own data
In the appChoose Topics in text, then BERTopic. Start with TF-IDF + SVD; download the pretrained model if topics mix paraphrases.
import codesplash as cs
from codesplash.ml import text as cstext
from codesplash.text import bertopic as bt
docs = cs.table("reviews")["text"].dropna().tolist()
X, vocab = cstext.dtm(docs)
E, kept = bt.embed_lsa(cstext.tfidf(X), 50) # or minilm.embed(docs) after the download
Z = bt.pca_scores(E, 5)
# then sklearn.cluster.HDBSCAN(min_cluster_size=10).fit(Z) and bt.ctfidf(X, topics, classes)library(codesplashr)
docs <- na.omit(cs_table("reviews")$text)
d <- cs_ml_dtm(docs)
E <- cs_bt_embed_lsa(cs_ml_tfidf(d$X), 50)$E # or cs_minilm_embed(docs) after the download
Z <- cs_bt_pca_scores(E, 5)
# then dbscan::hdbscan(Z, minPts = 10) and cs_bt_ctfidf(d$X, topics, classes)Recap
Recap- BERTopic embeds, reduces, clusters and then names topics with class-based TF-IDF.
- The outlier group is part of the answer: read it before you hide it.
- A pretrained sentence embedder joins paraphrases that share no words, and it runs locally after a download you approve.
Concepts in this lesson