Twitter (X) Topic Modeling in Python: BERTopic vs LDA on Real Tweets

- BERTopic first on tweets. On 970 real tweets with a hidden ground truth, BERTopic reached NMI 0.88 and 88% purity; NMF 0.63 / 70%; LDA 0.34 / 45%.
- Tweets are short. Median 16 content words per cleaned tweet, 26.2% under 10. LDA's per-document word statistics have little to work with at that length.
- NMF is the fast baseline. TF-IDF plus
NMF(n_components=k)fit in under a tenth of a second here and recovered 6 of 10 accounts. Use it to sanity-check BERTopic. - Clean before you model. Drop reposts, strip URLs and
@handles, deduplicate: of 1,424 raw posts, 379 were reposts and 56 duplicates or near-empty. - Data in one loop.
/twitter/tweet/advanced_searchreturnstweets[],has_next_page,next_cursor; 2,000 tweets is about 100 requests and $0.30 at $0.15 per 1,000. - Labels come from you. Models give top terms (
nba, cup, prime, watch), not names. Read a handful of tweets per topic, then name it.
This page is about finding themes in a set of tweets: which subjects a corpus talks about and how many tweets belong to each. It is not about mood or polarity, which is what Twitter sentiment analysis covers, and not about who talks to whom, which is the job of Twitter network analysis. Topic modeling sits upstream of both: it tells you what the conversation is about before you score how people feel about it.
Plenty of tutorials run LDA on tweets and print some word lists. Word lists always look plausible, so they prove little. We wanted a test with an answer key, so we collected recent posts from 10 public organization accounts whose subjects barely overlap (space, gaming, basketball, global health, AI hardware, developer tools, weather warnings, central banking, coffee, European space), threw away the account name, and asked LDA, NMF and BERTopic to sort the tweets. A good model should give back something close to the 10 accounts. The numbers below are from that run, with the code to reproduce it.
If you only need the recipe: fetch with /twitter/tweet/advanced_search, clean, embed with all-MiniLM-L6-v2, fit BERTopic, read the topic table. The rest of the page explains why that order, what can go wrong, and how many tweets you need.
NMI 0.88 for BERTopic, 0.63 for NMF, 0.34 for LDA on 970 tweets from 10 organization accounts (collected in 2026). Median tweet: 16 content words.
Why topic modeling on tweets is harder than on articles
Classic topic models were built for documents with hundreds of words. Latent Dirichlet Allocation treats each document as a mix of topics and each topic as a distribution over words, and it learns both from which words show up together inside the same document. A news article gives it hundreds of co-occurring pairs. A tweet gives it a handful.
Our sample shows how little is left. A tweet in the study had a median of 26 words before cleaning. After removing links, @handles and English stop words, the median was 16 content words, the 90th percentile 32, and 26.2% of tweets had fewer than 10. With min_df=3 the LDA vocabulary was 1,544 terms, and 5 tweets had no surviving term at all.
Three other traits of X data make it worse. Posts reuse campaign hashtags and calls to action (watch, live, learn, join) across unrelated subjects, so the frequent words are the least informative ones. Reposts and copy-paste duplicates inflate whatever topic they belong to. And a single account mixes subjects across a week, so even a perfect model will not give one clean cluster per author.
Researchers have long reported the same pattern. Egger and Yu compared LDA, NMF, Top2Vec and BERTopic on 31,800 travel tweets in Frontiers in Sociology (2022) and concluded that their study "supports the potency of BERTopic and NMF, followed by Top2Vec and LDA, in analyzing Twitter data". Our much smaller test ranks the three models we ran in the same order.
The study: three models, one hidden answer key
We pulled up to 160 recent posts from each of 10 organization accounts with /twitter/user/last_tweets (80 requests, 1,424 posts). After dropping 379 reposts, 19 non-English posts and 56 duplicates or near-empty posts, 970 tweets remained, between 67 and 122 per account.
Each model saw only the cleaned text. LDA (scikit-learn, word counts, k=10, 50 iterations) and NMF (TF-IDF, k=10) were told there were 10 topics. BERTopic (default all-MiniLM-L6-v2 embeddings, UMAP to 5 dimensions, HDBSCAN with min_cluster_size=15) picked its own count. All random seeds were fixed at 42.
We scored each model three ways. NMI (normalized mutual information) measures how much a model's topic assignment tells you about the hidden account, from 0 (nothing) to 1 (a perfect relabeling). Purity is the share of tweets that sit in a topic whose dominant account is their own. NPMI coherence scores how often a topic's top 10 terms appear together in the same tweets, which is the usual label-free quality check.
BERTopic found 9 topics and left 0.1% of tweets (one tweet) in the outlier topic -1. Its one "mistake" is defensible: NASA and ESA ended up in a single topic about space missions, Earth and orbit. NMF split the NBA and the Federal Reserve into two topics each and folded WHO health posts and NWS rainfall warnings into one mixed topic.

What the topics looked like
The topic labels below are the real top terms each model produced, not names we chose. BERTopic's c-TF-IDF picks words that are frequent inside one cluster and rare in the others, so its lists read like labels you could hand to a stakeholder after a quick look at sample tweets.
LDA's lists show what happens when co-occurrence evidence runs thin. Several topics mixed vocabularies that never belong together: one paired copilot, github, app, pumpkin, githubuniverse (GitHub posts and Starbucks posts in one bucket), another health, friday, care, coffee, playstation, a third health, asteroid, mission, dimorphos, climate. Only one LDA topic (nba, cup, et, prime) drew more than 60% of its tweets from a single account.
There is one twist worth knowing. NMF's topics had the highest NPMI coherence (0.28 against BERTopic's 0.17 and LDA's 0.02), even though they matched the answer key worse than BERTopic's. Coherence rewards terms that co-occur, and a topic built around one campaign phrase repeated many times scores well on it. BERTopic's Starbucks topic (cold, drink, fall, hot, summer) had negative NPMI because those words rarely sit in the same tweet, yet 85% of the topic was Starbucks. Coherence is a useful smoke test; it is not a substitute for reading the tweets.

Step 1: collect tweets with pagination
Any topic model is only as good as the sample it sees, so decide the scope first. For a theme study around a keyword, product or event, use /twitter/tweet/advanced_search with X search operators: lang:en to keep one language (multilingual models exist, but one language is easier to read), -filter:retweets to drop reposts at the source, and since_time:<unix> / until_time:<unix> to fix the window. For a study of what specific accounts post about, use /twitter/user/last_tweets with userName, which is what we did, because we needed a known label per tweet.
Both endpoints return 20 tweets per page with has_next_page and next_cursor. The search endpoint returns a top-level tweets[]; last_tweets nests them in data.tweets[]. Each tweet carries text, createdAt, lang, likeCount, retweetCount and an author object, so you can weight or filter before modeling without a second call. No X account is needed for reads.
Cost is linear in tweets returned: 15 credits per tweet, which is $0.15 per 1,000 tweets, with a minimum of 15 credits per request. A 2,000-tweet corpus is about 100 requests and $0.30. The same 2,000 post reads on the official X API pay-per-usage rate card ($0.005 per post read on docs.x.com) come to $10, about 33 times more. Our study read 1,424 posts for $0.21.
Rate limits matter for larger pulls. Before the first payment an account is limited to 0.2 requests per second (one call every 5 seconds); paid accounts get 20, Scale 50, Business 500. If a call returns HTTP 429 or 503, wait and retry the same cursor rather than skipping it. If you plan to keep the tweets for later analysis, the Twitter data with pandas guide shows how to flatten the JSON into a DataFrame and save it to Parquet.
Step 2: clean the text (this changes the result more than the model)
Drop reposts. A repost is someone else's text. In our raw pull 379 of 1,424 posts (27%) were reposts; left in, they duplicate topics from accounts you never chose. Use -filter:retweets in the query or skip any tweet with a retweeted_tweet object.
Strip links and handles. https://t.co/... tokens and @handles are unique strings that topic models either ignore or, worse, turn into a topic. Hashtags are different: keep the word and drop the #, because #AntimicrobialResistance is a real topic signal.
Deduplicate. Accounts post the same announcement twice; bots and giveaways post it thousands of times. Lowercased exact-match dedup removed 56 posts in our run. For keyword searches, also consider near-duplicate removal (for example MinHash), because a single copy-paste campaign can become your largest topic.
Keep the stop-word list for the vectorizer, not the embedder. For LDA and NMF remove English stop words before counting. For BERTopic pass the raw cleaned sentence to the embedding model (sentence models read grammar) and give the stop-word list only to the CountVectorizer that builds the topic keywords. BERTopic's own default keyword step uses CountVectorizer, so that is where stop-word removal belongs.
Filter by language. The lang field on each tweet is X's own language guess. We kept en only, which removed 19 posts.
Step 3: BERTopic, the default for short text
BERTopic (MIT license, by Maarten Grootendorst; latest stable release 0.17.4 on PyPI, Python 3.10 or newer) runs four swappable stages: a sentence-transformer turns each tweet into a vector, UMAP reduces the vectors to a few dimensions, HDBSCAN clusters them, and a class-based TF-IDF picks the words that describe each cluster. With language="english" the default embedding model is all-MiniLM-L6-v2, a 384-dimension model under the Apache-2.0 license that truncates input above 256 word pieces, far longer than any tweet.
Because the clustering runs on meaning rather than shared words, two tweets about the same thing can land together even with zero words in common (flash flooding expected and heavy rain tonight). That is the property LDA lacks on short texts.
On a laptop CPU, encoding our 970 tweets took 0.7 seconds and the UMAP plus HDBSCAN plus c-TF-IDF fit took 4.0 seconds, after a one-time download of the embedding model. Embedding time grows roughly linearly with tweet count, so by extrapolation 100,000 tweets would take a minute or two on the same machine; compute embeddings once and save them with numpy.save so you can refit with different settings for free.
Two defaults are worth knowing: min_topic_size=10 and top_n_words=10. Raise the minimum topic size (we used an HDBSCAN min_cluster_size of 15) when you have thousands of tweets, or you will get hundreds of tiny topics. Lower it for small samples. Topic -1 holds outliers; on keyword searches it is often a sizable share, while our curated sample left only one tweet there.
import os
import re
import time
import requests
from bertopic import BERTopic
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import CountVectorizer
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
def search_tweets(query, max_tweets=2000):
"""Page through /twitter/tweet/advanced_search (20 tweets per page)."""
tweets, cursor = [], ""
while len(tweets) < max_tweets:
r = requests.get(
f"{BASE}/twitter/tweet/advanced_search",
headers=HEADERS,
params={"query": query, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
if r.status_code in (429, 503):
time.sleep(60) # back off, then retry the same cursor
continue
r.raise_for_status()
body = r.json()
tweets.extend(body.get("tweets", []))
if not body.get("has_next_page"):
break
cursor = body["next_cursor"]
time.sleep(1) # fixed pacing
return tweets[:max_tweets]
def clean(text):
text = re.sub(r"https?://\S+", " ", text) # links carry no topic words
text = re.sub(r"@\w+", " ", text) # handles are not topics
text = text.replace("#", "").replace("&", "&")
return re.sub(r"\s+", " ", text).strip()
raw = search_tweets('"open source" lang:en -filter:retweets', max_tweets=2000)
seen, docs, kept = set(), [], []
for t in raw:
c = clean(t["text"])
if len(c) >= 15 and c.lower() not in seen: # drop near-empty and duplicate posts
seen.add(c.lower())
docs.append(c)
kept.append(t) # keep the tweet for createdAt later
embedder = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = embedder.encode(docs, show_progress_bar=True)
topic_model = BERTopic(
vectorizer_model=CountVectorizer(stop_words="english", min_df=2),
min_topic_size=15,
)
topics, _ = topic_model.fit_transform(docs, embeddings)
print(topic_model.get_topic_info().head(15)[["Topic", "Count", "Name"]])
Step 4: LDA and NMF as baselines
LDA and NMF are still worth running: they need no download, fit in about a second on a few thousand tweets, and a reviewer may ask for them. In scikit-learn, LatentDirichletAllocation defaults to n_components=10, learning_method='batch' and max_iter=10; we raised iterations to 50 because 10 left topics unstable on tweets. Feed LDA raw counts from CountVectorizer, and feed NMF TF-IDF weights from TfidfVectorizer.
Tune min_df and max_df. min_df=3 drops one-off typos and usernames that slipped through; max_df=0.5 drops words that appear in half the corpus. On tweets, also consider adding your search keyword to the stop list, since it appears in every document.
Pick k on purpose. LDA and NMF need the topic count up front. Fit k from 5 to 30, compare coherence and read the topics; there is no single right k for an open corpus. If you want to skip that loop, BERTopic's HDBSCAN chooses the count for you.
Short-text variants exist. Researchers built LDA variants for short text, such as the biterm topic model (which models word pairs across the whole corpus) and Dirichlet multinomial mixture models (one topic per document). They help, but in practice the embedding route has become the common choice for tweets.
from sklearn.decomposition import NMF, LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
# LDA wants raw counts; NMF works better on TF-IDF weights
cv = CountVectorizer(stop_words="english", min_df=3, max_df=0.5)
X = cv.fit_transform(docs)
lda = LatentDirichletAllocation(n_components=10, max_iter=50, random_state=42)
doc_topic = lda.fit_transform(X) # one row per tweet, sums to 1
tv = TfidfVectorizer(stop_words="english", min_df=3, max_df=0.5)
Xt = tv.fit_transform(docs)
nmf = NMF(n_components=10, init="nndsvd", random_state=42, max_iter=400)
W = nmf.fit_transform(Xt)
def show(components, vocab, n=8):
for i, comp in enumerate(components):
print(i, " ".join(vocab[j] for j in comp.argsort()[::-1][:n]))
show(lda.components_, cv.get_feature_names_out())
show(nmf.components_, tv.get_feature_names_out())
How many tweets you need, and how to name topics
Our 970 tweets were enough for 9 clean topics because the accounts were far apart. Real keyword samples are messier, so plan on more. A practical rule from running these models: aim for at least 30 to 50 tweets per topic you expect to find, which means 1,000 to 2,000 tweets for a 20 to 40 topic view of one keyword and 10,000 or more for a broad subject. Below a few hundred tweets, reading them by hand beats any model.
Name topics from evidence. BERTopic's get_topic_info() returns the keyword list and a Representative_Docs column (three tweets per topic by default in 0.17.4). Read those, then a random 10 more, and write the label yourself. Its representation_model option can also pass keywords and sample documents to a language model to draft a label, which you should still check.
Merge and clean after fitting. reduce_topics(docs, nr_topics=...) merges similar topics. reduce_outliers(docs, topics) reassigns topic -1 tweets to their nearest topic (the default strategy is c-tf-idf; embeddings, distributions and probabilities are alternatives), followed by update_topics so the keyword lists reflect the new members.
Track topics over time. topics_over_time(docs, timestamps) counts each topic per time bin. Parse createdAt (Thu Oct 16 12:34:56 +0000 2026) with the format %a %b %d %H:%M:%S %z %Y. Pairing this with a word cloud per topic or an emotion breakdown gives a readable report.
# Fewer, broader topics: merge after fitting
topic_model.reduce_topics(docs, nr_topics=12)
# Push outliers (topic -1) into their nearest topic, then refresh the labels
new_topics = topic_model.reduce_outliers(docs, topic_model.topics_, strategy="c-tf-idf")
topic_model.update_topics(docs, topics=new_topics)
# Topics over time: needs a timestamp per document
from datetime import datetime
stamps = [datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y") for t in kept]
over_time = topic_model.topics_over_time(docs, stamps, nr_bins=20)
How we collected this
Question. Can off-the-shelf topic models recover real topics from short tweets, and which does it better when there is an answer key?
Accounts. NASA, PlayStation, NBA, WHO, nvidia, github, NWS, federalreserve, Starbucks and ESA: public organization accounts in unrelated fields.
Window and sample. Up to 160 recent posts per account at collection time via /twitter/user/last_tweets, 80 requests, 1,424 posts, 970 after cleaning. Collected in 2026. API cost $0.21.
Method. scikit-learn 1.9.1 LDA and NMF (k=10, seed 42), BERTopic 0.17.4 with all-MiniLM-L6-v2, UMAP (n_neighbors=15, 5 components, seed 42) and HDBSCAN (min_cluster_size=15), on a laptop CPU. NMI and purity against the hidden account; NPMI computed on the same tweets from document co-occurrence of each topic's top 10 terms.
What the sample cannot show. Organization accounts post on-message, so this is an easier test than a raw keyword search full of replies, slang and spam; absolute scores on your data will be lower. An account is not a perfect topic label (NASA and ESA really do share a subject). One seed and one sample size; results move with min_cluster_size and k.
Privacy. Organization accounts only; aggregates only; no private individuals analyzed or quoted. The study folder holds the protocol, analysis script, results and a de-identified row file.
import os
import re
import time
import requests
from bertopic import BERTopic
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import CountVectorizer
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
def search_tweets(query, max_tweets=2000):
"""Page through /twitter/tweet/advanced_search (20 tweets per page)."""
tweets, cursor = [], ""
while len(tweets) < max_tweets:
r = requests.get(
f"{BASE}/twitter/tweet/advanced_search",
headers=HEADERS,
params={"query": query, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
if r.status_code in (429, 503):
time.sleep(60) # back off, then retry the same cursor
continue
r.raise_for_status()
body = r.json()
tweets.extend(body.get("tweets", []))
if not body.get("has_next_page"):
break
cursor = body["next_cursor"]
time.sleep(1) # fixed pacing
return tweets[:max_tweets]
def clean(text):
text = re.sub(r"https?://\S+", " ", text) # links carry no topic words
text = re.sub(r"@\w+", " ", text) # handles are not topics
text = text.replace("#", "").replace("&", "&")
return re.sub(r"\s+", " ", text).strip()
raw = search_tweets('"open source" lang:en -filter:retweets', max_tweets=2000)
seen, docs, kept = set(), [], []
for t in raw:
c = clean(t["text"])
if len(c) >= 15 and c.lower() not in seen: # drop near-empty and duplicate posts
seen.add(c.lower())
docs.append(c)
kept.append(t) # keep the tweet for createdAt later
embedder = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = embedder.encode(docs, show_progress_bar=True)
topic_model = BERTopic(
vectorizer_model=CountVectorizer(stop_words="english", min_df=2),
min_topic_size=15,
)
topics, _ = topic_model.fit_transform(docs, embeddings)
print(topic_model.get_topic_info().head(15)[["Topic", "Count", "Name"]])
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Is LDA good for tweets?
It works, but poorly compared with the alternatives. LDA learns topics from words that co-occur inside a document, and the median cleaned tweet in our sample had 16 content words. On our test LDA reached NMI 0.34 against the hidden account, versus 0.63 for NMF and 0.88 for BERTopic. If you must use LDA, consider pooling tweets (by author, hashtag or hour) into longer documents.
What is BERTopic and why is it used for Twitter data?
BERTopic is an open-source (MIT) Python library that embeds documents with a sentence-transformer, reduces dimensions with UMAP, clusters with HDBSCAN and describes each cluster with class-based TF-IDF keywords. It groups tweets by meaning rather than shared words, which suits short texts. Egger and Yu (2022) and our own test both rank it above LDA on tweets.
How many tweets do I need for topic modeling?
Enough for each topic to have a few dozen members. As a working rule, 1,000 to 2,000 tweets for a focused keyword and 10,000 or more for a broad subject. Our 970-tweet test produced 9 clean topics because the sources were very different; noisier samples need more.
Does BERTopic need a GPU?
No. With the default all-MiniLM-L6-v2 model, encoding 970 tweets took 0.7 seconds on a laptop CPU in our run, and the full fit under 5 seconds after the model download. A GPU helps only at hundreds of thousands of tweets or with larger embedding models.
What does topic -1 mean in BERTopic?
Topic -1 is the outlier group: tweets HDBSCAN did not place in any cluster. You can leave them out of the analysis or reassign them with reduce_outliers(docs, topics) and then call update_topics. In our curated sample only one tweet landed there; keyword searches typically leave far more.
How do I get tweets for topic modeling without the official X API?
Use /twitter/tweet/advanced_search on twitterapi.io with a query and paginate with next_cursor until has_next_page is false, or /twitter/user/last_tweets for specific accounts. It costs $0.15 per 1,000 tweets returned, versus $0.005 per post read on the official X API pay-per-usage rate card. No X account is needed for reads; new accounts get free starter credits (no card, one per person or network, expiring after 31 days).
Is twitter clustering the same as topic modeling?
Close. Clustering assigns each tweet to one group; topic modeling also describes each group with keywords, and LDA lets one tweet belong to several topics with weights. BERTopic is clustering plus a keyword step, which is why it reads like a topic model.
Should I remove stop words before BERTopic?
Not before embedding. Pass the cleaned sentence to the embedding model and give the stop-word list to the CountVectorizer used for topic keywords (vectorizer_model=CountVectorizer(stop_words="english")). Removing stop words before embedding strips context the sentence model uses.
Continue
- BERTopic API reference (defaults: all-MiniLM-L6-v2, min_topic_size, topic -1)
- BERTopic on PyPI (version, license, Python requirement)
- all-MiniLM-L6-v2 model card (Apache-2.0, 384 dimensions, 256 word-piece limit)
- scikit-learn LatentDirichletAllocation reference
- Egger and Yu (2022), A Topic Modeling Comparison Between LDA, NMF, Top2Vec, and BERTopic to Demystify Twitter Posts
- X API pricing (pay-per-usage rate card)
- X (Twitter) API overview and endpoints
- Twitter sentiment analysis in Python
- Twitter network analysis: who talks to whom
- Load Twitter data into pandas
- Twitter data for academic research
- Build a word cloud from tweets
- twitterapi.io pricing per 1,000 tweets
- 01Twitter (X) Fake News Detection: Datasets, Features and Code
- 02How to Make a Twitter (X) Word Cloud from Tweets in Python
- 03Twitter (X) Hate Speech Detection in Python: Models, Thresholds and a Real Reply Study
- 04Spark Streaming Twitter (X) Data in 2026: PySpark Structured Streaming Without TwitterUtils
- 05Twitter (X) API to Neo4j: model, import and query a real follower and mention graph
- 06How to Save a GIF from Twitter (X): Desktop, iPhone, Android and Bulk
- 07Codex MCP: How to Add Any MCP Server to OpenAI Codex (CLI, IDE and App)
- 08Twitter (X) Follower Tracking via API — A Developer Guide
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.