Skip to content

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.

Advanced ~12 min8 steps

What runs in CodeSplash

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
01

Four stages, four choices

Read

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

02

Guess the outliers

Predict

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

03

The outlier group is information

Explore
Topic sizesHow large is each topic, and how many documents fit no topic at all?
View data
topicdocumentstop termsoutliers
Topic 1219goal, match, striker, leaguefalse
Topic 2159dough, oven, bread, yeastfalse
Topic 3145rates, bond, inflation, yieldsfalse
Topic 4107storm, rain, forecast, windfalse
Topic 561roses, compost, pruning, soilfalse
Outliers108said, people, weektrue

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.

04

Which embedding?

Checkpoint

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

05

Read the card

In the app
BERTopic (embeddings, clustering, c-TF-IDF)Recorded · Python and R agreeRecorded 2026-11-25 · 53 values compared
R

6 topics in 180 documents (TF-IDF + SVD embeddings); 0 outliers.

Topics
6
Outliers
0.0%
Mean coherence (UMass)
−0.6890
Topic diversity
1

Plots

Topic sizesHow large is each topic, and how many documents fit no topic at all?
View data
DocumentsOutliersTop termsTopic
30falsestadium, midfield, coach, strikerTopic 1
30falsepruning, seeds, mulch, compostTopic 2
30falsesugar, knead, pastry, crustTopic 3
30falseclouds, sunshine, storm, thunderTopic 4
30falsegalaxy, orbit, astronaut, probeTopic 5
30falsedividend, yields, inflation, investorsTopic 6
Documents by topic (PCA of the embeddings)Which rows group together, and how well separated are the groups?
View data
TopicPC 1PC 2
10.1187−0.0662
20.39270.4384
3−0.1624−0.6197
20.38030.4151
3−0.1175−0.5983
40.04640.0144
3−0.1648−0.6774
50.2908−0.1158
50.2699−0.1279
50.3176−0.1148
3−0.0912−0.5303
50.3111−0.1016
3−0.1856−0.4290
40.0812−0.0279
40.09640.0739
4−0.00860.0631
40.0365−0.0178
20.31130.4577
10.1106−0.0189
20.27620.2717
50.2425−0.0962
10.0856−0.0455
6−0.65430.4051
10.0975−0.0959
20.27990.3338
6−0.41400.2525
20.43480.4667
6−0.61390.3520
3−0.1181−0.5903
10.1215−0.0505
3−0.2477−0.5563
10.19530.0272
6−0.63930.3363
3−0.2152−0.5086
10.1631−0.0519
6−0.65190.2587
10.1322−0.0342
10.1706−0.0002
3−0.2270−0.5063
20.42010.4611
20.37570.3536
6−0.71980.3892
20.39430.4176
20.40090.3969
10.1749−0.0475
6−0.70500.3183
20.40040.4232
20.26530.4029
50.2783−0.1200
40.05510.0302
20.34490.4184
50.2786−0.1648
3−0.1177−0.6109
50.2751−0.0586
6−0.72210.3715
50.2187−0.0864
6−0.61320.2818
10.1290−0.0260
3−0.1572−0.6779
4−0.0082−0.0758

First 60 of 180 rows.

Top terms per topic (class-based TF-IDF)What is each topic about?
View data
TermTopicc-TF-IDF
stadiumTopic 10.2161
midfieldTopic 10.2026
coachTopic 10.1998
strikerTopic 10.1912
seasonTopic 10.1792
matchTopic 10.1773
leagueTopic 10.1697
goalTopic 10.1613
pruningTopic 20.2114
seedsTopic 20.2091
mulchTopic 20.1902
compostTopic 20.1850
hedgeTopic 20.1847
greenhouseTopic 20.1790
tomatoesTopic 20.1645
wateringTopic 20.1611
sugarTopic 30.2143
kneadTopic 30.1934
pastryTopic 30.1934
crustTopic 30.1910
ovenTopic 30.1782
recipeTopic 30.1782
loafTopic 30.1605
butterTopic 30.1563
cloudsTopic 40.2225
sunshineTopic 40.1921
stormTopic 40.1918
thunderTopic 40.1888
rainTopic 40.1770
windTopic 40.1743
temperatureTopic 40.1708
showersTopic 40.1608
galaxyTopic 50.2021
orbitTopic 50.2021
astronautTopic 50.2018
probeTopic 50.1921
planetTopic 50.1845
rocketTopic 50.1710
missionTopic 50.1685
launchTopic 50.1629
dividendTopic 60.2174
yieldsTopic 60.1921
inflationTopic 60.1895
investorsTopic 60.1870
sharesTopic 60.1813
ratesTopic 60.1792
stocksTopic 60.1785
earningsTopic 60.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

TopicDocumentsShare of documentsCoherence (UMass)Top terms (c-TF-IDF)
13016.7%−0.7547stadium, midfield, coach, striker, season, match, league, goal
23016.7%−0.6609pruning, seeds, mulch, compost, hedge, greenhouse, tomatoes, watering
33016.7%−0.6620sugar, knead, pastry, crust, oven, recipe, loaf, butter
43016.7%−0.7320clouds, sunshine, storm, thunder, rain, wind, temperature, showers
53016.7%−0.6908galaxy, orbit, astronaut, probe, planet, rocket, mission, launch
63016.7%−0.6336dividend, 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"))
))
Python

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

TopicDocumentsShare of documentsCoherence (UMass)Top terms (c-TF-IDF)
13016.7%−0.7547stadium, midfield, coach, striker, season, match, league, goal
23016.7%−0.6609pruning, seeds, mulch, compost, hedge, greenhouse, tomatoes, watering
33016.7%−0.6620sugar, knead, pastry, crust, oven, recipe, loaf, butter
43016.7%−0.7320clouds, sunshine, storm, thunder, rain, wind, temperature, showers
53016.7%−0.6908galaxy, orbit, astronaut, probe, planet, rocket, mission, launch
63016.7%−0.6336dividend, 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.

06

Check your understanding

Checkpoint

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

07

Do it on your own data

In the app

Choose Topics in text, then BERTopic. Start with TF-IDF + SVD; download the pretrained model if topics mix paraphrases.

Python
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)
R
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)
08

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