Sub topic 3
Describing clusters with c-TF-IDF
This chapter assumes you know Python, have installed bertopic with pip, and understand TF-IDF and sentence embeddings.
What c-TF-IDF does
BERTopic groups documents by meaning, but a cluster of numbers needs a name. Class-based TF-IDF (c-TF-IDF) describes each cluster with words. It treats all documents in one cluster as a single class, then scores each word by how often it appears in that class relative to the others. Words common to every cluster score low, so the top words of a topic are the ones that set it apart.
Running the BERTopic pipeline end to end
BERTopic runs four stages: embed each document, reduce the embeddings with UMAP, cluster them with HDBSCAN, and describe each cluster with c-TF-IDF.
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(
subset="all", remove=("headers", "footers", "quotes")
)["data"]
topic_model = BERTopic(language="english", min_topic_size=15)
topics, probs = topic_model.fit_transform(docs)
print(topic_model.get_topic_info().head(10))
print(topic_model.get_topic(0)) # (word, c-TF-IDF score) pairsUnderstanding and reducing outliers
HDBSCAN cannot place some documents in any cluster. BERTopic files them under topic -1. Large outlier groups hide real structure, so reassign them to their closest topic:
new_topics = topic_model.reduce_outliers(docs, topics)
topic_model.update_topics(docs, topics=new_topics)> Hmm, see the note below before you apply this.
Refining topics: reduction, merging, and better labels
Many small topics can be merged into fewer broad ones with reduce_topics. Topic words can also be re-estimated with a different representation model, which update_topics does after any change to the topic assignments.
Choosing between LDA and BERTopic
Choose LDA when you need a probabilistic model of word counts and each document should mix several topics. Choose BERTopic when your documents are short, you have a pretrained embedding model for the language, and you want clusters that each document belongs to in one topic.
Tracking topics over time
If documents carry timestamps, topics_over_time shows how each topic's frequency changes across time bins:
timestamps = [...] # one date or time value per document
topics_over_time = topic_model.topics_over_time(docs, timestamps, nr_bins=20)Exercise:
Exercise
What does c-TF-IDF compare when it scores a word for a cluster?
Show answer
It compares how often the word appears in that cluster with how often it appears across all the other clusters.