Skip to content

CDiscover · discover.bertopic

BERTopic (embeddings, clustering, c-TF-IDF)

Which themes do these texts fall into, judged by meaning rather than shared word counts?

BERTopic's pipeline over a text column: each document becomes an embedding, UMAP reduces it, HDBSCAN groups dense regions into topics (documents that fit no group become outliers), and class-based TF-IDF names each topic by the words that set it apart. The default embedding is TF-IDF + SVD, which needs no download; a pretrained sentence embedder (all-MiniLM-L6-v2) runs on this computer once you agree to download it. Python and R run the same embeddings and topic words; UMAP and HDBSCAN are each engine's library, so topic counts and sizes agree within stated bands.

Experimental Python and R agree within simulation error Seeded Also called BERTopic, neural topic model, embedding topic model…

A real result

Example “Lsa umap default”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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.7509
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.0793−0.0817
20.42990.0038
3−0.5125−0.3752
20.29410.0014
3−0.4865−0.4041
40.04930.0320
3−0.5398−0.4044
50.1817−0.1864
50.1587−0.1788
50.2161−0.2119
3−0.4217−0.3552
50.2100−0.1909
3−0.4191−0.2223
40.06000.0044
40.12310.0590
40.04800.0998
40.03110.0289
20.39210.0594
10.0987−0.0539
20.2248−0.0240
50.1538−0.1463
10.0603−0.0657
6−0.17990.5306
10.0413−0.1118
20.32170.0234
6−0.13810.4193
20.44320.0024
6−0.21720.5982
3−0.4555−0.3653
10.0824−0.0908
3−0.4829−0.2608
10.1653−0.0721
6−0.19550.5014
3−0.3647−0.2013
10.1279−0.1026
6−0.24160.4430
10.1088−0.0743
10.1305−0.0714
3−0.4406−0.2339
20.46610.0134
20.3812−0.0250
6−0.24210.6203
20.4220−0.0093
20.4048−0.0224
10.1191−0.0958
6−0.28350.5912
20.4479−0.0192
20.31830.0639
50.1687−0.1899
40.07390.0556
20.40860.0259
50.1347−0.1999
3−0.4808−0.3971
50.1857−0.1528
6−0.24020.5969
50.1381−0.1260
6−0.24010.5059
10.1007−0.0552
3−0.5286−0.4119
4−0.0477−0.0048

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
penaltyTopic 10.1575
fansTopic 10.1497
pruningTopic 20.2114
seedsTopic 20.2091
mulchTopic 20.1902
compostTopic 20.1850
hedgeTopic 20.1847
greenhouseTopic 20.1790
tomatoesTopic 20.1645
wateringTopic 20.1611
rosesTopic 20.1484
weedsTopic 20.1484
sugarTopic 30.2143
kneadTopic 30.1934
pastryTopic 30.1934
crustTopic 30.1910
ovenTopic 30.1782
recipeTopic 30.1782
loafTopic 30.1605
butterTopic 30.1563
yeastTopic 30.1445
doughTopic 30.1384
cloudsTopic 40.2225
sunshineTopic 40.1921
stormTopic 40.1918
thunderTopic 40.1888
rainTopic 40.1770
windTopic 40.1743
temperatureTopic 40.1708
showersTopic 40.1608
frostTopic 40.1593
snowTopic 40.1580
galaxyTopic 50.2021
orbitTopic 50.2021
astronautTopic 50.2018
probeTopic 50.1921
planetTopic 50.1845
rocketTopic 50.1710
missionTopic 50.1685
launchTopic 50.1629
telescopeTopic 50.1629
cometTopic 50.1548
dividendTopic 60.2174
yieldsTopic 60.1921
inflationTopic 60.1895
investorsTopic 60.1870
sharesTopic 60.1813
ratesTopic 60.1792
stocksTopic 60.1785
earningsTopic 60.1757
portfolioTopic 60.1757
bondTopic 60.1624

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 — UMAP depends on the seed; rerun with another seed to see which topics are stable.

Topics

TopicDocumentsShare of documentsCoherence (UMass)Top terms (c-TF-IDF)
13016.7%−0.8144stadium, midfield, coach, striker, season, match, league, goal, penalty, fans
23016.7%−0.7727pruning, seeds, mulch, compost, hedge, greenhouse, tomatoes, watering, roses, weeds
33016.7%−0.7610sugar, knead, pastry, crust, oven, recipe, loaf, butter, yeast, dough
43016.7%−0.8051clouds, sunshine, storm, thunder, rain, wind, temperature, showers, frost, snow
53016.7%−0.7239galaxy, orbit, astronaut, probe, planet, rocket, mission, launch, telescope, comet
63016.7%−0.6284dividend, yields, inflation, investors, shares, rates, stocks, earnings, portfolio, bond
  • 3 rows have no text, or no words left after stop words and frequency limits, and are left out.
Python

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

Topics
6
Outliers
0.0%
Mean coherence (UMass)
−0.7509
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 — UMAP depends on the seed; rerun with another seed to see which topics are stable.

Topics

TopicDocumentsShare of documentsCoherence (UMass)Top terms (c-TF-IDF)
13016.7%−0.8144stadium, midfield, coach, striker, season, match, league, goal, penalty, fans
23016.7%−0.7727pruning, seeds, mulch, compost, hedge, greenhouse, tomatoes, watering, roses, weeds
33016.7%−0.7610sugar, knead, pastry, crust, oven, recipe, loaf, butter, yeast, dough
43016.7%−0.8051clouds, sunshine, storm, thunder, rain, wind, temperature, showers, frost, snow
53016.7%−0.7239galaxy, orbit, astronaut, probe, planet, rocket, mission, launch, telescope, comet
63016.7%−0.6284dividend, yields, inflation, investors, shares, rates, stocks, earnings, portfolio, bond
  • 3 rows have no text, or no words left after stop words and frequency limits, and are left out.

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

Worked examples in the app

  • Lsa umap defaultml_topics · text: text
  • Lsa pca deterministicml_topics · text: text
  • Lsa direct assign outliersml_topics · text: text
  • Small corpus pcaml_corpus · text: text
  • Umap two dims large topicsml_topics · text: text
  • Ollama vectors directml_topics_vec · text: text

In the guides

Where it sits in the decision guides

  • Topic modeling (LDA, NMF, BERTopic) · DS & ML Decision Guide · Discover — find structure without labels
  • Discover: cluster quality (silhouette, ARI); coherence (topics); stability and interpretability · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Textcategorical · 1 column
The text column; each row is one document.

Choices you make

model

Document embeddingsdefault lsa

How each document becomes a vector. TF-IDF + SVD needs no download; MiniLM understands meaning better.

  • TF-IDF + SVD (no download)(default) — Word weights compressed by a truncated SVD (latent semantic analysis); runs anywhere, matches shared words and their co-occurrence.
  • all-MiniLM-L6-v2 (pretrained, ~90 MB) — A small sentence-transformer that places texts with similar meaning close together. Runs locally after a one-time download you approve.
  • Local Ollama model — Vectors from an embedding model in Ollama on this computer, added by the app before the run; text never leaves the machine.
Ollama embedding modeldefault nomic-embed-text

An embedding model installed in Ollama on this computer (ollama pull nomic-embed-text).

SVD componentsdefault 50

Size of the TF-IDF + SVD embedding (capped at the number of documents and words minus one).

Dimension reductiondefault umap

BERTopic reduces embeddings before clustering because density clustering struggles in many dimensions.

  • UMAP (BERTopic's default)(default) — Keeps local neighborhoods; stochastic, so engines agree on topics within bands rather than exactly.
  • PCA (deterministic) — Linear and repeatable; both engines give the same coordinates. Topics can be coarser than with UMAP.
  • None — Cluster the embeddings directly; works for small embeddings such as a 5–10 component SVD.
Reduced dimensionsdefault 5

Dimensions kept for clustering. BERTopic uses 5.

UMAP neighborsdefault 15

Small values find many small topics; large values merge them into broad ones.

Smallest topicdefault 10

Fewest documents a topic needs. Larger values give fewer, broader topics and more outliers.

Assign outliers to the nearest topicdefault off

Moves each outlier into the topic whose average embedding is most similar. Off keeps them visible as unclear documents.

Advanced

UMAP minimum distancedefault 0

0 packs similar documents tightly, which helps density clustering (BERTopic's setting).

preprocess

Minimum documents per worddefault 2

Ignore words in fewer documents than this (for the TF-IDF + SVD embedding and the topic words).

Maximum share of documents per worddefault 0.95

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

Vocabulary sizedefault 2000

Largest vocabulary kept, by document frequency.

options

Top terms per topicdefault 10

Words listed for each topic, by class-based TF-IDF.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Enough documents

    Density clustering needs dozens of documents per topic; with fewer than a few hundred, expect broad topics and many outliers.

  • English text

    The stop list and MiniLM are English; other languages need another embedder.

  • Stochastic layout

    UMAP's layout depends on the seed; rerun with another seed to see which topics are stable.

What it reports

n_docs
The share of distinct words among the top words of all topics: 1 means no two topics share a top word, low values mean redundant topics.
n_left_out
The share of distinct words among the top words of all topics: 1 means no two topics share a top word, low values mean redundant topics.
n_terms
How many distinct words a text method kept after lower-casing, removing stop words and dropping words in too few or too many documents.
embedding
A fixed-length vector for a whole text from a model trained so that texts with similar meaning get nearby vectors.
embed_dims
A fixed-length vector for a whole text from a model trained so that texts with similar meaning get nearby vectors.
n_topics
Documents that HDBSCAN leaves in no dense group; BERTopic reports them as topic −1.
n_outliers
Documents that HDBSCAN leaves in no dense group; BERTopic reports them as topic −1.
outlier_share
Documents that HDBSCAN leaves in no dense group; BERTopic reports them as topic −1.
mean_coherence
How often a topic's top terms appear together in the same documents; closer to 0 is more coherent.
diversity
The share of distinct words among the top words of all topics: 1 means no two topics share a top word, low values mean redundant topics.

Per group, level or term: embed_kept, size[<topic>], share[<topic>], top_term[<topic>], coherence[<topic>], weight[<topic>:<term>]

Python and R

Python and R agree within simulation error (relative tolerance 1e-8). Python uses numpy, scipy, scikit-learn, umap-learn, codesplash; R uses codesplashr, uwot, dbscan, stringi.

Default traps between the two languages

  • The embeddings (TF-IDF + SVD, MiniLM in plain numpy / base R from the same float32 weights), the reduced coordinates for PCA, the topic numbering and the class-based TF-IDF are the same twins in both engines (codesplash.text ↔ codesplashr text_*.R); with reduce = pca or none the engines agree to rounding.
  • With reduce = umap both engines start from the same exact kNN graph and PCA layout, but umap-learn and uwot run their own stochastic optimizers, and scikit-learn's HDBSCAN and dbscan::hdbscan then see slightly different coordinates; topic counts, sizes, shares, outliers and coherence agree within the bands above on well-separated themes, and documents near a topic border can change topic. Even on identical coordinates (reduce = pca or none), scikit-learn's HDBSCAN and dbscan::hdbscan can merge two nearby groups differently, so the parity cases use well-separated themes.
  • The bertopic package is an oracle for the class-based TF-IDF only (tests/crosscheck/w3ds2b_bertopic.py); its own default embedder (all-MiniLM-L6-v2 through sentence-transformers) is replaced by the twins, and Hugging Face transformers checks the MiniLM twin to 1e-6 when installed.
Python

The exact script CodeSplash ran for example “Lsa umap default” · 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 d4e82e3e50dba0fd
# 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
import umap
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), 50)  # 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
K = min(5, E.shape[1])
k_nn = min(15, n - 1)
knn_idx, knn_dist = csembed.exact_knn(E, k_nn)  # Euclidean on unit rows ranks pairs as cosine does
with _warnings.catch_warnings():
    _warnings.simplefilter("ignore")
    Z = umap.UMAP(
        n_neighbors=k_nn, n_components=K, min_dist=0.0, metric="euclidean",
        n_epochs=500 if n <= 10000 else 200, init=bt.pca_init(E, K), random_state=42, n_jobs=1,
        precomputed_knn=(knn_idx, knn_dist, None),
    ).fit_transform(E)

# %% 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 = 10
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_umap_default/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 "umap" == "umap" else "pass",
     "detail": "UMAP depends on the seed; rerun with another seed to see which topics are stable." if "umap" == "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", "umap-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"},
    ],
})
R

The exact script CodeSplash ran for example “Lsa umap default” · 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 d4e82e3e50dba0fd
# 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)
suppressPackageStartupMessages(library(uwot))

# %% 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), 50)  # 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
K <- min(5, ncol(E))
k_nn <- min(15, n - 1L)
Z <- uwot::umap(
  E, n_neighbors = k_nn, n_components = K, min_dist = 0.0, metric = "euclidean",
  n_epochs = if (n <= 10000) 500 else 200, nn_method = cs_ml_exact_knn(E, k_nn), init = cs_bt_pca_init(E, K),
  n_threads = 1, n_sgd_threads = 0, seed = 42
)

# %% 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 <- 10
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_umap_default/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 <- TRUE
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", "uwot", "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"))
))

Sources

  • Grootendorst M (2022). BERTopic: neural topic modeling with a class-based TF-IDF procedure. arXiv:2203.05794.
  • McInnes L, Healy J, Melville J (2018). UMAP: uniform manifold approximation and projection for dimension reduction. arXiv:1802.03426.
  • Campello RJGB, Moulavi D, Sander J (2013). Density-based clustering based on hierarchical density estimates. PAKDD 2013, 160–172.
  • Reimers N, Gurevych I (2019). Sentence-BERT: sentence embeddings using Siamese BERT-networks. EMNLP-IJCNLP 2019, 3982–3992.
  • Wang W, Wei F, Dong L, Bao H, Yang N, Zhou M (2020). MiniLM: deep self-attention distillation for task-agnostic compression of pre-trained transformers. NeurIPS 33.
  • Deerwester S, Dumais ST, Furnas GW, Landauer TK, Harshman R (1990). Indexing by latent semantic analysis. JASIS 41(6):391–407.
  • Dieng AB, Ruiz FJR, Blei DM (2020). Topic modeling in embedding spaces. TACL 8:439–453.
  • Mimno D, Wallach H, Talley E, Leenders M, McCallum A (2011). Optimizing semantic coherence in topic models. EMNLP 2011.

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