Sub topic 13
Describing clusters with c-TF-IDF
This chapter assumes you know plain TF-IDF, how CountVectorizer builds a document-term matrix, and that BERTopic has already grouped documents into clusters with embeddings, UMAP and HDBSCAN. Here you will see how BERTopic turns each cluster into a short list of words.
The problem c-TF-IDF solves
After HDBSCAN runs, each document has a topic number. A number is not a topic description. You need words that make the cluster readable, such as game, team, season, players.
The clustering step used embeddings, so it never produced a word distribution. BERTopic builds the word lists in a separate step. It treats each cluster as one big document and asks which words are characteristic of that document compared with the other clusters. That score is class-based TF-IDF, or c-TF-IDF.
From TF-IDF to c-TF-IDF
Ordinary TF-IDF scores a word within one document, relative to all documents. c-TF-IDF changes the unit. A "class" is a topic, and all documents in the topic are joined into one text.
The BERTopic paper defines the weight of term t in class c as:
W(t, c) = tf(t, c) * log(1 + A / f(t))tf(t, c)is how often term t occurs in class c.f(t)is how often term t occurs across all classes.Ais the average number of words per class.
The 1 + inside the logarithm keeps the weight positive, even for words that appear in every class. A word that is frequent in one class and rare elsewhere gets a high weight. A word spread evenly across all classes gets a lower multiplier, but not zero.
Computing it by hand
The code below reproduces the formula with scikit-learn and NumPy on a toy corpus. It follows the paper's formula directly.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the team won the match after a late goal",
"the coach praised the team and the players",
"the season ends and the league champion wins the title",
"parliament passed the law after a long vote",
"the minister defended the government policy",
"voters judged the party and the election result",
]
labels = [0, 0, 0, 1, 1, 1]
classes = sorted(set(labels))
class_docs = [
" ".join(d for d, l in zip(docs, labels) if l == c) for c in classes
]
vectorizer = CountVectorizer(stop_words="english")
tf = vectorizer.fit_transform(class_docs).toarray().astype(float) # classes x terms
terms = vectorizer.get_feature_names_out()
f_t = tf.sum(axis=0) # total count of each term across classes
A = tf.sum(axis=1).mean() # average number of words per class
idf = np.log(1 + A / f_t)
ctfidf = tf * idf
for c in classes:
top = np.argsort(ctfidf[c])[::-1][:4]
print(c, [(terms[i], round(float(ctfidf[c][i]), 2)) for i in top])Each row of tf describes a whole topic, not a single document. The stop_words argument removes words like "the" before counting. The output lists the four highest-weighted terms for each class. Many tied scores are expected on a corpus this small.
What BERTopic does differently from the formula
The formula above is the idea. The ClassTfidfTransformer class in the library adds a few practical details:
- It normalises each topic's term counts so that large topics do not dominate small ones.
- It can use a BM25-style weighting (
bm25_weighting=True). - It can reduce the weight of very frequent words (
reduce_frequent_words=True).
Check the signature in your installed version, because options and defaults have changed across releases.
Where the vectoriser fits
BERTopic counts words with a CountVectorizer, and this is the main place to shape the output. The embeddings were computed on the raw text, so you can clean the vocabulary afterwards without changing the clusters. This differs from LDA, where preprocessing changes the model itself.
| Vectoriser setting | Effect on topic words |
|---|---|
| `stop_words="english"` | Removes function words from the topic descriptions |
| `ngram_range=(1, 2)` | Allows phrases such as `machine learning` |
| `min_df=5` | Drops terms that occur in fewer than 5 documents, which removes typos and rare names |
| `max_features` | Caps the vocabulary size and memory use |
Pass the vectoriser and, optionally, a customised transformer when you create the model:
from bertopic import BERTopic
from bertopic.vectorizers import ClassTfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
vectorizer_model = CountVectorizer(stop_words="english", ngram_range=(1, 2), min_df=5)
ctfidf_model = ClassTfidfTransformer(reduce_frequent_words=True)
topic_model = BERTopic(
vectorizer_model=vectorizer_model,
ctfidf_model=ctfidf_model,
)You can also change these on a fitted model without re-clustering. update_topics recomputes the word lists from the existing topic assignments:
# Assumes topic_model, docs, and topics come from topic_model.fit_transform(docs)
new_vectorizer = CountVectorizer(stop_words="english", ngram_range=(1, 3), min_df=10)
topic_model.update_topics(docs, topics=topics, vectorizer_model=new_vectorizer)
print(topic_model.get_topic(0))Common errors and gotchas
- Stop words in topic descriptions. If words like "the" or "said" appear in your topics, the default vectoriser is not removing them. Add
stop_wordsto yourCountVectorizer. - Removing stop words before embedding. Do not strip stop words from the text you embed. Sentence-embedding models were trained on natural sentences, and removing words can hurt cluster quality. Remove them only in the vectoriser.
- Treating weights as probabilities. c-TF-IDF scores are relative importance scores. They do not sum to one and are not comparable across models.
- Topic words are not the cluster's definition. Clusters come from embeddings, so the top words can look odd or mixed even when the underlying documents are coherent. Read example documents with
get_representative_docs. - Topic -1 gets words too. The outlier group is also treated as a class, so its description is a mix of unrelated terms. Do not read it as a theme.
- Large vocabularies. With many topics, the topic-by-term matrix can get large. Use
min_dformax_featuresto limit it.
Why this design works
Separating clustering from description gives you two independent controls. If clusters look wrong, adjust UMAP or HDBSCAN. If the clusters look right but the words are noisy, adjust the vectoriser or the weighting. The same topic assignments also feed the representation models covered later, which can rewrite the c-TF-IDF word lists into more readable labels.
Exercise
A corpus has two topics, and the average number of words per class is A = 100. The word "goal" occurs 6 times in topic A and never in topic B. The word "said" occurs 30 times in topic A and 30 times in topic B. Using W = tf * ln(1 + A / f), compute the weight of each word in topic A. Which word ranks higher, and what does that tell you?
Show answer
"goal": f = 6, so W = 6 ln(1 + 100/6) = 6 ln(17.67) ≈ 6 2.872 ≈ 17.2. "said": f = 60, so W = 30 ln(1 + 100/60) = 30 ln(2.667) ≈ 30 0.981 ≈ 29.4. "said" ranks higher even though it is spread evenly across topics. The logarithm reduces the weight of common words but does not remove it, and a high raw count can still win. This is why you remove stop words in the vectoriser, or enable reducefrequentwords.
Exercise
You fitted BERTopic and the clusters look sensible, but the topic descriptions contain many single words such as "learning" and "model" where you wanted phrases. Which component do you change, and do you need to re-run the clustering?
Show answer
Change the vectoriser, for example CountVectorizer(ngramrange=(1, 2)) or a wider range, and apply it with topicmodel.updatetopics(docs, topics=topics, vectorizermodel=new_vectorizer). You do not need to re-run embedding, UMAP or HDBSCAN, because the topic assignments stay the same and only the c-TF-IDF word lists are recomputed.