Topic models¶
A topic model finds the themes of a collection of documents without labels. It returns groups of words that occur together, and a person reads each group and decides what it is about. This notebook runs two topic models on the same tweets. LDA works on word counts. BERTopic works on document embeddings. The tweets have topic labels from human annotators, so the notebook can check what each model finds.
Sections: Prepare the documents, LDA with Gensim, Read the topics, BERTopic, Compare the two results.
Packages beyond the standard library: gensim, bertopic, nltk, pandas, pyarrow.
Install them with uv add gensim bertopic nltk pandas pyarrow (or pip install).
bertopic needs PyTorch, which is a large package.
Colab has all of them except gensim and bertopic, and the next cell installs these two there.
The BERTopic section downloads an embedding model of about 90 MB when it first runs. No section needs a GPU.
# Colab does not have gensim and bertopic, so this cell installs them there.
# pip may print a note about restarting the kernel. A restart is not needed.
# The cell does nothing if the two packages are already installed.
import importlib.util
if importlib.util.find_spec("gensim") is None:
%pip install -q gensim
if importlib.util.find_spec("bertopic") is None:
%pip install -q bertopic
# This notebook uses TweetTopic, a public research dataset of 6,090 English tweets
# with topic labels. This cell downloads the file (0.9 MB) from Hugging Face into
# data/ next to this notebook, unless the file is already there. The long string
# in the address is a fixed revision of the dataset, so every run gets the same file.
import pathlib
import urllib.request
data_url = (
"https://huggingface.co/datasets/cardiffnlp/tweet_topic_multi/resolve/"
"dc65379cfc7721f579c97656a1ebdbb80aedad08/"
"tweet_topic_multi/train_all-00000-of-00001.parquet"
)
data_path = pathlib.Path("data") / "train_all-00000-of-00001.parquet"
data_path.parent.mkdir(exist_ok=True)
if not data_path.exists():
urllib.request.urlretrieve(data_url, data_path)
print(data_path, data_path.stat().st_size, "bytes")
# The stopword list of NLTK is a separate data package (less than 1 MB).
# This call does nothing if the package is already on the machine.
import nltk
nltk.download("stopwords", quiet=True)
Prepare the documents¶
The file that the first cell downloaded is TweetTopic (Antypas et al., 2022), a research dataset of 6,090 English tweets from 2019 to 2021. Annotators gave each tweet one or more labels from a list of 19 topics. The topic models do not see these labels. The notebook uses them only afterwards, to check the topics.
import pandas as pd
df = pd.read_parquet(data_path).reset_index(drop=True)
print(df.shape)
df.explode("label_name")["label_name"].value_counts()
The labels are very uneven.
news_&_social_concern, sports, and music have more than 1,000 tweets each, and the smallest labels have about 100.
The authors of the dataset replaced the links and the account names in the text with three placeholders: {{URL}} for a link, {{USERNAME}} for a mention of an account that is not verified, and {@Name@} for a mention of a verified account, with the display name between the markers.
The file writes the apostrophe as the curly character ’.
clean_text removes the first two placeholders, keeps the display name as plain text, and replaces the curly apostrophe.
tokenize then splits a tweet into lowercase tokens and drops links, punctuation, and stopwords.
Both functions come from the Word Counts notebook, which explains each step.
import re
from nltk.corpus import stopwords
from nltk.tokenize import TweetTokenizer
stop_words = set(stopwords.words("english"))
tokenizer = TweetTokenizer(preserve_case=False, reduce_len=True, strip_handles=True)
def normalize(tokens, remove_stopwords=True):
kept = []
for token in tokens:
if token.startswith("http"):
continue
if not any(ch.isalnum() for ch in token):
continue
if remove_stopwords and token in stop_words:
continue
kept.append(token)
return kept
def clean_text(text):
text = text.replace("{{URL}}", " ").replace("{{USERNAME}}", " ")
text = re.sub(r"\{@(.*?)@\}", r"\1", text)
return text.replace("’", "'")
def tokenize(text, remove_stopwords=True):
return normalize(tokenizer.tokenize(clean_text(text)), remove_stopwords)
The two models need the documents in two forms.
docsis the list of cleaned texts. BERTopic reads whole sentences, so it gets this list.doc_tokensis the list of token lists. LDA works on word counts, so it gets this list. Tokens of one or two characters, such asuand2, are dropped, because they say little about a topic.
A document here is one tweet.
docs = [clean_text(text) for text in df["text"]]
doc_tokens = [[token for token in tokenize(text) if len(token) > 2] for text in df["text"]]
lengths = pd.Series([len(tokens) for tokens in doc_tokens])
print(len(docs), "documents")
print("Median number of tokens in a document:", lengths.median())
example = "{@Daily Planet@} says the game starts at 8, don’t be late {{USERNAME}} #gameday {{URL}}"
print(clean_text(example))
print([token for token in tokenize(example) if len(token) > 2])
The last two lines show a hand-written post in the format of the file, first cleaned and then as tokens.
A tweet is a very short document: half of the tweets have 15 tokens or fewer. This number matters for LDA.
LDA with Gensim¶
LDA (Latent Dirichlet Allocation) is a model of how the documents were written. It assumes two things:
- Each topic is a mixture of words. A sports topic gives a high probability to
gameandteam. - Each document is a mixture of topics. One document can be 70% sports and 30% news.
The model sees only the word counts of the documents. From these counts it estimates the words of each topic and the topics of each document. It ignores the order of the words, so it is a bag-of-words method.
Gensim needs two objects.
The Dictionary gives a number to each different word.
The corpus holds each document as a list of pairs of a word number and a count.
from gensim.corpora import Dictionary
dictionary = Dictionary(doc_tokens)
print(len(dictionary), "different words")
dictionary.filter_extremes(no_below=5, no_above=0.5)
print(len(dictionary), "words after the filter")
corpus = [dictionary.doc2bow(tokens) for tokens in doc_tokens]
print(sum(1 for bow in corpus if not bow), "documents have no word left")
example_bow = dictionary.doc2bow(["game", "team", "game", "win"])
print(example_bow, [dictionary[word_id] for word_id, count in example_bow])
filter_extremes removes the words that appear in fewer than 5 documents and the words that appear in more than half of the documents.
A word that appears in two tweets cannot describe a topic.
Most of the vocabulary is this rare, so the filter removes most of it.
Now train the model. You must choose the number of topics before the training. The file has 19 labels, so this notebook asks for 20 topics. With your own data you do not know this number. The usual way is to try several values and to read the topics of each.
passes=10 lets the model go through all documents 10 times.
random_state fixes the random start, so a rerun on the same machine with the same versions gives the same topics.
Another seed, another version of Gensim, or another kind of processor can give other topics.
The cell takes about 5 seconds on a recent laptop.
from gensim.models import LdaModel
num_topics = 20
lda = LdaModel(corpus, id2word=dictionary, num_topics=num_topics, passes=10, random_state=42)
Read the topics¶
A topic is a list of words with probabilities.
show_topic returns the words with the highest probability.
The cell below rounds the numbers.
[(word, round(float(probability), 3)) for word, probability in lda.show_topic(0, topn=10)]
The topics have numbers and no names. The next cell puts the top 10 words of every topic into one table.
pd.set_option("display.max_colwidth", None)
lda_words = pd.Series({
topic: ", ".join(word for word, probability in lda.show_topic(topic, topn=10))
for topic in range(num_topics)
})
lda_words.to_frame("top words")
Read every row and try to give the topic a name.
A few topics are easy to name.
One has words about new music and streaming services, and one or two have words about games and teams.
Many topics are hard to name.
Their words do not belong to one theme, and general words such as new, love, and day are in several topics.
The model also gives each document a mixture of topics. The post below is hand-written.
post = "What a game last night, the team played great and got the win"
bow = dictionary.doc2bow([token for token in tokenize(post) if len(token) > 2])
shares = sorted(lda.get_document_topics(bow), key=lambda pair: pair[1], reverse=True)
[(topic, round(float(share), 2)) for topic, share in shares]
Each pair is a topic number and its share of the document. Topics with a very small share are left out.
For a simple summary, give each tweet its main topic, which is the topic with the largest share.
def main_topic(bow):
topics = lda.get_document_topics(bow, minimum_probability=0)
return max(topics, key=lambda pair: pair[1])
main_topics = [main_topic(bow) for bow in corpus]
df["lda_topic"] = [topic for topic, share in main_topics]
df["lda_share"] = [share for topic, share in main_topics]
print("Mean share of the main topic:", round(df["lda_share"].mean(), 2))
df["lda_topic"].value_counts().sort_index()
On average, the main topic has only about 40% of a tweet. For many tweets, the model is not sure which topic they belong to.
The top words are one way to read a topic.
The other way is to read the documents.
The next cell prints the five tweets with the largest share of one topic.
Change topic and read a few topics in this way.
topic = 0
print(lda_words[topic])
print()
for row in df[df["lda_topic"] == topic].sort_values("lda_share", ascending=False).head(5).itertuples():
print(round(row.lda_share, 2), clean_text(row.text))
print()
This dataset has labels from human annotators, so there is a third check, which most collections do not allow. For each topic, the function below finds the label that is most common among its tweets, and the share of the tweets of the topic that have this label. A tweet with two labels counts for both.
def topics_against_labels(topic_column):
exploded = df.explode("label_name").reset_index(drop=True)
table = pd.crosstab(exploded[topic_column], exploded["label_name"])
size = df[topic_column].value_counts().sort_index()
return pd.DataFrame({
"tweets": size,
"most common label": table.idxmax(axis=1),
"share with that label": (table.max(axis=1) / size).round(2),
})
topics_against_labels("lda_topic").join(lda_words.rename("top words"))
A topic that matches one label has a share near 1. Only a few LDA topics have a share above 0.6. For most topics, the most common label is one of the three large labels, and fewer than half of the tweets of the topic have it.
The reason is the length of the documents. LDA learns from the words that occur together in a document. A news article has hundreds of words, and a tweet has about 15 tokens after the stopwords are removed, so each tweet gives the model very little. LDA works better on longer documents. For short posts, a common fix is to join the posts of one author or one thread into one document.
BERTopic¶
BERTopic starts from the meaning of whole documents, not from word counts. It works in six steps.
- Embed each document: a language model turns the text into a vector. Documents with similar meanings get similar vectors.
- Reduce the dimensions of the vectors with UMAP, because clustering works poorly on vectors with hundreds of dimensions.
- Cluster the reduced vectors with HDBSCAN. Each cluster is a topic. Documents that fit no cluster are outliers.
- Tokenize the documents of each topic.
- Weight the tokens with a variant of TF-IDF that treats all documents of a topic as one long document.
- Represent each topic by its top tokens.
Each document gets one topic, not a mixture.
The first step is the slow one, so this notebook runs it in its own cell.
all-MiniLM-L6-v2 is a small embedding model with the Apache 2.0 license.
The first run downloads it (about 90 MB).
It turns each tweet into a vector of 384 numbers.
On an Apple M4 laptop, the embedding takes less than 10 seconds. On a Colab CPU runtime, the first run takes about 3 minutes, which includes the download of the model.
import time
from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
start = time.perf_counter()
embeddings = embedding_model.encode(docs, show_progress_bar=True)
print("Embedding took", round(time.perf_counter() - start), "seconds")
embeddings.shape
The next cell sets up the other steps and fits the model.
umap_modelis the UMAP step with the default settings of BERTopic, plusrandom_state=42. UMAP has a random part, and without a fixed seed every run gives other topics.vectorizer_modelis the tokenizer of step 4.stop_words="english"keeps words such astheandandout of the topic words. The embedding step still reads the full text.min_topic_size=30is the smallest number of tweets that can form a topic. The default is 10, which gives many small topics on this data.
You do not choose the number of topics. It follows from the clusters that HDBSCAN finds.
On an Apple M4 laptop, the fit takes about 15 seconds. Expect about a minute on a free Colab runtime.
from bertopic import BERTopic
from sklearn.feature_extraction.text import CountVectorizer
from umap import UMAP
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric="cosine", random_state=42)
vectorizer_model = CountVectorizer(stop_words="english")
topic_model = BERTopic(
embedding_model=embedding_model,
umap_model=umap_model,
vectorizer_model=vectorizer_model,
min_topic_size=30,
)
start = time.perf_counter()
topics, probabilities = topic_model.fit_transform(docs, embeddings)
print("Fitting took", round(time.perf_counter() - start), "seconds")
df["bertopic_topic"] = topics
print(df["bertopic_topic"].nunique() - 1, "topics")
print((df["bertopic_topic"] == -1).sum(), "of", len(df), "tweets are outliers")
The seed makes a rerun on the same machine with the same versions give the same topics. The result can still differ between machines and between versions of the packages, because the embeddings and UMAP depend on the processor and on the numerical libraries. Your numbers can differ a little from the numbers in the text below.
get_topic_info returns one row for each topic, with the number of tweets and a name that BERTopic builds from the top words.
Topic -1 is not a topic.
It holds the outliers.
topic_info = topic_model.get_topic_info()
topic_info[["Topic", "Count", "Name"]].head(10)
[(word, round(float(weight), 3)) for word, weight in topic_model.get_topic(1)]
get_topic returns the top words of one topic with their weights, which the cell above rounds.
The next cell builds the same table as for LDA: the size of each topic, its most common label, the share of its tweets with that label, and its top words.
bertopic_words = pd.Series({
topic: ", ".join(word for word, weight in topic_model.get_topic(topic))
for topic in topic_info["Topic"]
})
topics_against_labels("bertopic_topic").join(bertopic_words.rename("top words"))
Read the rows as before.
Most topics are easy to name: a football league, a basketball league, a fighting sport, the pandemic, climate change, U.S. politics, video game streams, a holiday.
The topics are narrower than the 19 labels.
The label sports is split into several topics, one for each sport or league.
Most topics have a share above 0.8 for their most common label.
Three things need attention.
- Topic -1 is large. About one tweet in three fits no cluster. BERTopic gives these tweets no topic.
- Topic 0 is much larger than the other topics. It holds most of the music tweets together with tweets on other subjects, so its share is lower than the share of the narrow topics.
- Many top words are names of people, teams, and events. The tweets were collected from trending topics, so a topic is often one event of one week.
Read the documents of a topic too.
get_representative_docs returns a few tweets that are typical for a topic.
for doc in topic_model.get_representative_docs(1):
print(doc)
print()
Compare the two results¶
The labels allow one summary number for each model. Take the most common label of each topic. Then count the tweets that have the most common label of their topic among their own labels. The outliers of BERTopic are left out of its count.
def label_match(topic_column):
best_label = topics_against_labels(topic_column)["most common label"]
assigned = df[df[topic_column] != -1]
matches = [best_label[topic] in labels for topic, labels in zip(assigned[topic_column], assigned["label_name"])]
return {
"topics": assigned[topic_column].nunique(),
"tweets with a topic": len(assigned),
"percent of all tweets": round(100 * len(assigned) / len(df), 1),
"percent with the label of their topic": round(100 * sum(matches) / len(assigned), 1),
}
pd.DataFrame([label_match("lda_topic"), label_match("bertopic_topic")], index=["LDA", "BERTopic"])
largest = df.explode("label_name")["label_name"].value_counts()
print("Most common label:", largest.index[0], "with", round(100 * largest.iloc[0] / len(df), 1), "percent of the tweets")
The last line is a baseline: a model that puts every tweet into one topic would reach this percentage.
LDA is above the baseline, but not by much. BERTopic matches the labels for most of the tweets that it assigns. It assigns only about two thirds of the tweets.
The comparison is not fully fair. BERTopic may drop the tweets that are hard to place, and LDA must place every tweet. The two models also have different numbers of topics.
Summary of the two results:
- LDA needs only word counts and runs in seconds. It gives each document a mixture of topics. It works poorly on very short documents, and you must choose the number of topics.
- BERTopic uses a language model, so it needs a download and more time. It handles short documents well. It gives each document one topic, it leaves some documents out, and the number of topics depends on its settings.
- With both models, the topics change when you change a setting or the seed. Run a model more than once before you report its topics.
- A topic has no name and no meaning until a person reads its words and its documents. The labels of this dataset made a check possible. With your own data, reading is the check.