Sub topic 18
Tracking topics over time
This chapter covers how to see how topic prevalence and topic wording change across time periods. It assumes you can fit a BERTopic model and an LDA model, and that you know what topic -1 is and how c-TF-IDF scores words.
Why a topic model needs a time axis
A single fit gives you one list of topics for the whole corpus. That list can hide the pattern you care about. A news corpus might contain a "pandemic" topic that is nearly absent in 2019, dominates early 2020, and drifts toward vaccines and then travel rules. Two questions follow:
- Prevalence: how much of each period's text belongs to each topic?
- Representation: which words describe a topic in each period?
BERTopic answers both with one method. For LDA you compute prevalence yourself, and a dedicated dynamic model is needed for wording.
How BERTopic computes topics over time
topics_over_time does not refit the model. It reuses the topic assignment each document already has from fit_transform. It then does this:
- Split the documents into time bins.
- For each topic and bin, collect the documents in that topic and bin.
- Compute c-TF-IDF for that group, treating it as one long document.
- Return the top words and the document count (frequency) for each topic and bin.
Because the topics come from one fit, the set of topics is fixed. Topics do not split, merge, or appear later in the way a true dynamic model would allow. If a theme only exists in the last month and has too few documents to form a cluster, HDBSCAN will place those documents in topic -1 or in a neighbouring topic.
Running it
The function takes your documents, a parallel list of timestamps, and optionally nr_bins.
# Assumes topic_model was fitted with topic_model.fit_transform(docs)
# and timestamps is a list of the same length as docs.
# Entries may be datetime objects, or strings if datetime_format is given.
topics_over_time = topic_model.topics_over_time(
docs,
timestamps,
nr_bins=20,
global_tuning=True,
evolution_tuning=True,
)
print(topics_over_time.head())
fig = topic_model.visualize_topics_over_time(topics_over_time, top_n_topics=8)
fig.write_html("topics_over_time.html")The result is a pandas DataFrame with the columns Topic, Words, Frequency, and Timestamp. visualize_topics_over_time returns a Plotly figure, with one line per topic.
The parameters that matter
| Parameter | Effect | Typical choice |
|---|---|---|
| `nr_bins` | Splits the time range into this many equal-width bins. Without it, each distinct timestamp is its own bin. | 10 to 30 for a corpus of tens of thousands of documents |
| `datetime_format` | Parses string timestamps, for example `"%Y-%m-%d"`. | Set it only when you pass strings |
| `global_tuning` | Averages each bin's c-TF-IDF vector with the topic's overall vector. | `True` |
| `evolution_tuning` | Averages each bin's vector with the previous bin's vector. | `True` for smooth drift, `False` to see abrupt shifts |
| `topics` | Restricts the computation to a list of topic ids. | Use it when the corpus is large |
Choosing the bin size
A bin needs enough documents per topic to give stable words. With 50,000 documents, 30 topics, and 20 bins, the average group has about 80 documents. That is workable. With 2,000 documents and the same settings, the average group has about 3 documents, and the top words will mostly be noise.
Check the Frequency column before you read anything into the Words column:
print(topics_over_time["Frequency"].describe())
sparse = topics_over_time[topics_over_time["Frequency"] < 10]
print(f"{len(sparse)} of {len(topics_over_time)} topic-bin cells have under 10 documents")If many cells are sparse, reduce nr_bins, filter to the largest topics, or both.
Equal-width bins also hide uneven sampling. If most documents arrive in two months, those two months share bins with long quiet periods. Plot the document count per bin to see this. Consider pre-bucketing your timestamps to weeks or months yourself.
Excluding the outlier topic
Topic -1 contains the documents that HDBSCAN did not assign to any cluster. It is usually the largest line on the plot, and it does not describe a theme. Drop it before plotting prevalence:
tot = topics_over_time[topics_over_time["Topic"] != -1]
fig = topic_model.visualize_topics_over_time(tot, top_n_topics=8)To compare prevalence rather than raw counts, pass normalize_frequency=True to the visualiser. Raw counts rise and fall with the volume of text in each period, and that volume can mask the change in share.
Tracking prevalence with LDA
Standard LDA has no time dimension. The common approach is to fit it once on the whole corpus. Then average each document's topic mixture within each period. This tells you how prevalence changes, and the topic-word distributions stay fixed.
import pandas as pd
from gensim import corpora
from gensim.models import LdaModel
docs = [
["goal", "match", "player", "team", "season"],
["election", "vote", "party", "government", "policy"],
["team", "coach", "league", "season", "win"],
["minister", "government", "vote", "law", "policy"],
]
periods = ["2024-01", "2024-01", "2024-02", "2024-02"]
dictionary = corpora.Dictionary(docs)
corpus = [dictionary.doc2bow(doc) for doc in docs]
lda = LdaModel(
corpus=corpus, id2word=dictionary, num_topics=2, passes=10, random_state=42
)
rows = []
for period, bow in zip(periods, corpus):
for topic_id, prob in lda.get_document_topics(bow, minimum_probability=0.0):
rows.append({"period": period, "topic": topic_id, "prob": prob})
share = (
pd.DataFrame(rows)
.groupby(["period", "topic"])["prob"]
.mean()
.unstack("topic")
)
print(share)Each row of share sums to 1, and each column is one topic's average share of that period. The same pattern works with BERTopic's approximate_distribution if you want soft assignments, but the hard-assignment counts from topics_over_time are simpler to read.
Gensim also includes LdaSeqModel, an implementation of the dynamic topic model by Blei and Lafferty (2006). It lets topic-word distributions evolve across time slices. It is much slower than LdaModel and is practical only for small corpora and few slices.
Common errors
- Mismatched lengths.
docsandtimestampsmust be the same length and in the same order as when you fitted the model. Filtering one list but not the other shifts every timestamp onto the wrong document. - Reading words as a trend. A topic's words change between bins partly because the sample changes. Differences between bins with few documents are often not real drift.
- Expecting new topics to appear. The topics are fixed by the single fit. To find a theme that emerges late, fit on a later slice of the data or reduce
min_topic_size. - Unsorted or unparsed strings. String timestamps without
datetime_formatmay be binned as text. Convert them withpd.to_datetimefirst.
Exercise
A corpus of 3,000 support tickets is fitted with 25 topics and tracked over 30 monthly bins. The plot shows topic wording that changes almost every month. What is the likely cause, and what two changes would you try?
Show answer
The average topic-bin cell holds about 4 documents (3,000 / 25 / 30), so c-TF-IDF is computed on tiny samples and the top words are noisy. Reduce the number of bins (for example to quarterly bins), and restrict the analysis to the largest topics or lower the topic count with reduce_topics. Keeping global_tuning=True also helps by pulling each bin's words toward the topic's overall description.