BERTopic: Neural topic modeling with a class-based TF-IDF procedure
Paper · 2022 · Maarten Grootendorst
Summary
A collection of documents can contain recurring subjects that nobody has labeled. The task of topic modeling is to discover those subjects and give readers a way to tell them apart. Older approaches such as Latent Dirichlet Allocation (LDA) and non-negative matrix factorization (NMF) start with word counts and describe documents as mixtures of topics. Counts preserve what words occur, while losing how those words are used together. BERTopic approaches the task by separating the evidence for grouping documents from the evidence for describing the resulting groups.
The authors use Sentence-BERT to turn documents into numerical representations that can be compared by meaning. UMAP reduces the number of dimensions in those representations, and HDBSCAN looks for groups of nearby documents, with the option to leave isolated documents unassigned. Earlier clustering approaches, including Top2Vec, look for words near the center of each group. That choice can give a misleading description when the group has an irregular shape. BERTopic builds its description from the text of the group's members.
Its main contribution is a class-based version of TF-IDF, a way to weight terms by their importance. Here a class is a cluster of documents. The method pools the text in each cluster, then gives weight to terms that occur frequently there and are less common across the collection of clusters. The same weighting scheme lets the authors describe how a topic's vocabulary varies over time. They discover topics using the whole collection, then count terms within each time slice while retaining the global weights. The documents only need to be embedded and clustered for the initial fit. The authors also describe how the same procedure could compare vocabulary by author or journal.
BERTopic recorded the highest topic coherence on Trump's tweets and competitive coherence on the two more heavily preprocessed news collections. The contextualized topic approach called CTM consistently scored higher on topic diversity, a separate measure of how much the word lists overlap. BERTopic's scores were stable across the tested Sentence-BERT encoders, although Doc2Vec was weaker on the tweets. In the temporal experiments, BERTopic led on both reported measures for the tweets and on coherence for the United Nations debates. Optional smoothing made little apparent difference to those measures. The architecture makes it possible to change the encoder or the vocabulary used to describe a topic, while leaving open two important questions for interpretation. A document is assigned to a single cluster during fitting, and a cluster's leading terms can repeat much the same idea.
Deep dive: BERTopic: Neural topic modeling with a class-based TF-IDF procedure
BERTopic groups documents by meaning and uses class-based TF-IDF to describe what each group discusses and how its vocabulary changes over time. · about 33 minutes to read
The problem and its context
What a discovered topic has to explain
A useful analysis of an unfamiliar collection has to give readers a sense of what the documents discuss. Making that analysis unsupervised means that the documents arrive without a set of answers telling the system which subject to assign to each one. The subjects are latent, meaning they have to be inferred from patterns in the text. A topic representation makes one of those inferred subjects inspectable. In the approaches discussed in the paper, the representation is generally a selection or weighting of words that can serve as a description.
LDA and NMF establish a point of comparison for this task. As the authors describe them, they represent each document as a bag of words and allow a document to have a mixture of topics. A bag of words records the terms encountered in a document and how frequently they appear. It discards the sequence in which they occur. A topic mixture can express the idea that a document ranges across subjects. The input used to infer that mixture, however, preserves little about the context in which a word takes on a particular meaning.
The distinction matters because shared vocabulary and shared subject matter can come apart. Texts about the same subject can express it in different language. A word that appears in several documents can also play a different role in each one. A count representation gives an analysis access to occurrences, while leaving those contextual distinctions implicit. The paper treats better input representations as a way to give the discovery procedure access to more of the information a reader would use when judging whether two documents are about related things.
The growth of embedding methods offered a way to represent that information. An embedding is a vector, or ordered set of numerical coordinates, used to place a piece of text in a space in which comparisons can be made. A desirable property for this task is that texts with similar meanings receive nearby representations. The paper points to BERT and related work such as RoBERTa as sources of contextual vector representations. The relevance of this work is that the vector can reflect a word or sentence in its surrounding text.
There was already more than one way to bring embeddings into topic discovery. The paper describes work that gave conventional approaches access to word embeddings, including Improving Topic Models with Latent Feature Word Representations. Other approaches put learned representations closer to the center of the procedure. The authors cite Topic Modeling in Embedding Spaces and discuss the contextualized approach evaluated as CTM. They take from the CTM study the possibility that improvements in pretrained text representations can carry over to topic discovery.
The geometry of a group and the words that describe it
Clustering makes the relationship between embeddings and topics direct. If texts about a subject tend to occupy the same region of the space, a group of nearby documents can stand for a topic. The discovery procedure produces those groups, and a separate operation gives each group words a reader can inspect. The question then becomes what should count as evidence that an individual word represents a collection of documents.
One approach described by the authors is to use a centroid, a central point computed from the positions of the members of a group. Sia and colleagues cluster the embeddings and use the proximity of word vectors to that point to propose topic terms. They also use within-cluster frequency to reorder the suggested words. As BERTopic's authors observe, the initial selection still limits that second operation. Frequency can promote a candidate only if the candidate was close enough to the centroid to be considered in the first place.
Top2Vec likewise finds words close to a cluster center. Its use of Doc2Vec gives that operation a specific basis. The word and document vectors share a space, so distances between their positions can be used to look for a description. The groups themselves are found by density. A group forms where points are sufficiently concentrated, and that concentration can follow a shape with a center that gives a poor account of where the points actually lie.
The authors' objection concerns the transition from a group to a description. A central point gives a simple account of position. Its value as a guide to word selection depends on how well position near that point represents the documents throughout the cluster. A group can extend along an irregular region, so a word near its center might capture a narrow part of the subject and a word shared by many members might sit elsewhere. Changing the clustering algorithm and changing the way words are selected address different parts of this problem.
BERTopic keeps clustering as a way of discovering candidate topics and makes group membership the basis of description. The evidence for a word comes from the text of the documents assigned to the group and from the word's prevalence across the collection. This design makes the dependence on geometry specific. Geometry influences which documents are included. Their observed vocabulary determines which terms are available to characterize them. A description can therefore be revised through choices about which terms to count, while the group that supplies those counts stays fixed.
A related distinction arises when the collection spans time. The paper describes Dynamic Topic Models as an extension of LDA that gives topics a temporal dimension. BERTopic approaches that need by asking which subjects recur across a collection and how the language used for those subjects changes. Those questions can share the same topic assignments. The paper's method treats timing as relevant to how a topic is expressed, while defining the topic from documents across the corpus.
The method, step by step
From a collection to groups of related documents
It helps to picture a set of documents that discuss cars in different ways. Some texts might emphasize the kind of vehicle and others the technology it uses. For BERTopic, the first question is whether enough of those documents are near one another when represented by meaning. A group of such documents can supply the evidence for a topic. Only after forming the group does the method ask which terms will help a reader recognize its subject.
How BERTopic finds and describes topics
The steps in order.
The first stage assigns a dense vector to every document. The authors use the Sentence-BERT framework, which produces representations of sentences and paragraphs from pretrained encoders. Dense means that the representation consists of numerical coordinates jointly describing the text. Documents with related meanings are expected to have representations that are close enough to be grouped. That is the working assumption behind the method, so the quality of the representations matters even though the scores used to select topic words come from a later stage.
The encoder enters the procedure already pretrained. The authors recommend an encoder that has undergone fine-tuning for semantic similarity, the task of estimating how closely texts match in meaning. The fitting operation described in the paper uses document vectors from that encoder to discover groups in the corpus. It has no stage in which feedback about the topic words trains the encoder. The clustering receives whatever distinctions the chosen vectors make available.
A vector can retain distinctions useful for comparing texts and still be difficult to cluster in its original space. The concern is that distance can become less discriminating as the number of dimensions grows. If the distances from a point to both its closest and farthest neighbors become similar, being near a particular point carries less information about a local group. The authors therefore reduce the dimensionality before asking a clustering procedure to recover the structure.
UMAP supplies that projection. It maps each vector to a representation with fewer coordinates, with the aim of retaining meaningful features of the arrangement. The authors mention principal component analysis and t-SNE as familiar alternatives and motivate their use of UMAP by its ability to preserve local and broader structure in a lower-dimensional representation. They also note that it accommodates embeddings with different dimensions, which matters when changing encoders. This projection is part of the clustering input. It can influence which documents the next stage treats as neighbors.
HDBSCAN operates on the projected document vectors. It extends DBSCAN, a density-based method, by organizing clustering possibilities hierarchically. The hierarchy allows the procedure to identify groups whose points have different levels of concentration. A useful consequence for this application is that the clusters can follow the observed concentrations of points. They need no common shape centered on a prototype.
The procedure can also mark a document as an outlier when its position offers insufficient support for assignment to a group. In the authors' account, letting unrelated documents remain unassigned can keep their vocabulary from obscuring the description of a coherent group. Outlier handling is thus relevant to both stages. It determines how much of the collection gets covered by the topics and which text provides the counts for each topic. HDBSCAN has a soft-clustering component, but the description constructed by BERTopic starts from the documents assigned to each group. The paper considers the soft outputs separately as a possible aid to interpretation.
The output at this point is a set of document clusters. BERTopic treats each cluster as a topic and still has to make that topic readable. An analyst could inspect the original documents to see what they share, but an automatic vocabulary description provides a much smaller object to examine. The authors build that description by returning to the text, with the cluster assignments specifying which documents may contribute to each profile.
Turning a cluster into a term profile
Ordinary TF-IDF balances two kinds of evidence. An occurrence in a particular document gives a term a reason to matter there. The distribution of that term across the corpus gives an indication of how much it can distinguish that document. For instance, one word can be common in a document but of little help in distinguishing it if the same word occurs throughout the collection. The conventional formula written in the paper is:
W[t,d] = tf[t,d] × log(N / df[t])
Here W[t,d] is the weight of term t in document d. The notation in brackets identifies what a value refers to. The quantity tf[t,d] is the frequency of t within d, N is the number of documents in the corpus, and df[t] counts the documents in which t occurs. The slash denotes division, log is the logarithm, and × multiplies the within-document frequency by the logarithmic factor. The equals sign defines the weight. The expression inside log gives the term a larger factor when it appears in fewer documents.
For topic description, the corresponding question concerns the distinctiveness of a term in a whole cluster. BERTopic treats that cluster as a class and concatenates all its documents into a single text for counting purposes. Terms can then be tallied against the full text assigned to that cluster. From the point of view of this calculation, an individual document contributes its terms through membership in the class. The frequency used to describe the class is calculated over the pooled text.
The authors also change how the global part of the score is calculated. Applying ordinary TF-IDF to the pooled documents would use the number of clusters containing a word as the denominator of the logarithmic factor. Their procedure uses the term's frequency across the classes. A term's repetitions matter to this global factor as well as to the local one. The average amount of text in a class provides the reference quantity.
W[t,c] = tf[t,c] × log(1 + A / tf[t])
Here W[t,c] is the class-based TF-IDF weight for term t in class c, and tf[t,c] is its frequency in that class's pooled document text. A is the average number of words per class, and tf[t] is the frequency of the term across all classes. The slash divides A by tf[t]. The plus sign adds 1 inside the logarithm to keep the logarithmic factor positive for observed terms. The multiplication sign applies that factor to the term's class frequency, and the equals sign gives the resulting score.
For a given term, the logarithmic factor comes from the collection as a whole. It is shared when scoring that term for different classes in the same fit. The local frequency supplies the variation among classes. For a given class, both factors matter in deciding which terms rise to the top. A often used term can still contribute even when it also occurs elsewhere, though its large global frequency reduces the weight attached to its local frequency. A globally uncommon term has a stronger multiplier, but its description of a class still depends on whether it actually occurs in that class.
This calculation yields a vector of term weights for each cluster. A high-scoring word is evidence about the cluster's vocabulary under this particular weighting rule. Its score does not require any numerical position for the word in the space used to group the documents. A reader or downstream procedure can use the highest-weighted entries as a compact description. The full vector also gives the authors a way to compare topics when they want to reduce how many are shown.
That reduction begins with the least common topic, which is merged with the topic whose class-based representation is most similar to it. The operation is repeated until the requested number of topics is reached. The reduction therefore acts on topic representations after clusters have been found. A requested topic count is a goal for reducing the available topics, instead of a parameter forcing the initial density-based clustering to produce that exact count. The paper describes the merge rule in terms of similarity between representations. Its account does not turn the reduction into a separate procedure for learning document vectors.
The cluster-level counting step permits different preprocessing choices from those used when embedding documents. The authors give the example of keeping common function words in the text sent to the encoder, then removing stopwords, or very common words of little descriptive value, during term selection. They also describe expanding the representation to longer n-grams, sequences of neighboring words counted as terms. A topic might then expose a recurring phrase as well as individual words. These choices change the vocabulary available to the description while preserving the document memberships on which the counts are based. The benchmark preparation of the datasets is a separate matter from this flexibility in the method.
What it means for an existing topic to change
The paper's car example makes the temporal setup concrete. Texts from 1990 and 2020 could both belong to a broad topic about vehicles. The later documents might give a company such as Tesla or self-driving technology more prominence in the description. The question for this part of the method is what vocabulary is characteristic of the documents from a particular time that were assigned to the same topic in the global fit.
The authors start by fitting BERTopic to the entire corpus, without treating the timestamps as input to topic discovery. Each time slice then draws its topic memberships from that fit. For a particular topic and time, the method pools the relevant documents, measures their term frequencies, and weights them using the inverse-frequency factors already calculated for the corpus. In the paper, that local calculation is written as:
W[t,c,i] = tf[t,c,i] × log(1 + A / tf[t])
Here W[t,c,i] is the local weight of term t for class c at timestep i. The quantity tf[t,c,i] is the term's frequency in the documents assigned to c that fall within i. The average number of words per global class is A, and tf[t] is still the global term frequency across classes. The slash forms the ratio of those global quantities, the plus sign adds 1, and log gives the fixed term factor. The multiplication sign combines it with the local frequency, and the equals sign defines the time-specific weight.
Keeping that global factor fixed means that the local descriptions respond to changes in the vocabulary of the selected documents under a common weighting scheme. Recomputing the global factor independently at each timestep would make the background prevalence of a word move along with its local prevalence. The paper's choice also saves work. The local operation requires grouping already assigned documents by time and counting their terms. It can use the same document embeddings and clusters for every slice.
The temporal method offers finer views of a topic under a stable identity. Each view asks which words describe the part of the topic observed in that slice. The authors point out that metadata other than time can serve the same purpose. Documents by a given author or from a given journal can be selected from a topic, then their term frequencies can be weighted by the shared global factors. The interpretation in each case concerns vocabulary within the document groups already discovered.
How optional smoothing uses the preceding timestep
In the basic dynamic calculation, the current slice's profile depends on the documents in that slice and the global weights. The previous slice's local profile plays no direct role. The authors consider a second version for settings where one expects topics to evolve gradually. In this version a topic's current term weights are influenced by its weights at the preceding timestep.
The paper first divides each relevant topic vector by its L1 norm. This norm is the sum of the absolute values of its entries. Dividing by it gives the vectors a common total weight, so the size of the pooled text does not give one vector disproportionate influence in the average. The authors then average the normalized current and preceding vectors for the same topic. Since the entries describe the same vocabulary, this combines corresponding weights. A term prominent at the earlier timestep can therefore still influence the current description.
The average encodes an assumption about continuity. When vocabulary changes gradually, adjacent slices can reinforce related terms. If a subject is suddenly discussed in very different language, carrying forward earlier terms can obscure the timing of the change. Smoothing is optional because the expected behavior depends on what the collection represents and what the analyst wants to see. The experiments compare the smoothed and independent-slice versions using the same evaluation measures.
Experiments and results
Collections and preparation
The experiments cover static and dynamic topic discovery. In the static comparison, the task is to find and describe groups using the corpus as a whole. For the dynamic comparison, the task is also to describe those topics at successive timesteps. The authors ran and validated their experiments with OCTIS, an open-source Python package that also supplied preprocessed data. They made the BERTopic implementation and the experimental setup available in the BERTopic and BERTopic_evaluation repositories.
The static experiment includes 20 NewsGroups, BBC News, and a corpus of Trump's tweets. The version of 20 NewsGroups used in the study contains 16,309 documents organized into 20 source categories. The BBC News collection has 2225 documents published between 2004 and 2005. The paper obtained both collections through OCTIS. Those corpora were preprocessed by removing punctuation and stopwords, applying lemmatization, which brings inflected words to a shared base form, and dropping documents with fewer than 5 words.
The authors collected the tweets to include recent short texts and a lighter preprocessing regime. The collection contains 44,253 tweets from 2009 to 2021, with retweets excluded. The paper also reports lowercasing tokens in its account of dataset preparation. The collections differ in what is being compared as well as how it was cleaned. The tweets come from one author, are short, and cover a different period and form of publication from the news data. Consequently, a difference in performance between them can reflect several properties of the material and its preparation.
The tweets also appear in the dynamic comparison, where the dates of the posts supply the temporal structure. The other dynamic corpus consists of transcripts of United Nations general debates between 2006 and 2015. In the dataset description, the authors report grouping the Trump corpus into 10 timesteps and the UN corpus into 9 timesteps. The caption describing the dynamic evaluation says that both datasets contributed scores for 9 timesteps. These are distinct statements about preparation and reporting. The paper does not identify which Trump bin accounts for the discrepancy.
Baselines and what was kept fixed
Using OCTIS’s default settings, both LDA and NMF were executed. They provide points of comparison that use the conventional word-count approach. The static comparison also includes CTM, which uses contextual document embeddings, and Top2Vec, which uses clusters and selects descriptive words through their proximity to a centroid. The combination puts BERTopic beside methods with different ways of representing text and beside one with a closely related way of finding groups.
For both CTM and the main BERTopic configuration, the document encoder was all-mpnet-base-v2, referred to as MPNET in the experiments. It is a Sentence-BERT encoder based on MPNet. Top2Vec was tested with its Doc2Vec representation and with the same MPNET encoder. The UMAP and HDBSCAN parameters were held fixed between BERTopic and Top2Vec. These choices make it easier to compare the two clustering approaches without also changing the settings of their projection and clustering algorithms.
The authors ran another comparison within BERTopic, replacing the embedding component. The configurations use Doc2Vec, the Universal Sentence Encoder, referred to as USE, and the Sentence-BERT encoders MPNET and MiniLM. MiniLM is the smaller all-MiniLM-L6-v2 encoder. These configurations all form topic descriptions with the same kind of class-based term weighting. Any changes to the documents brought together by the embeddings can affect the counts that enter that weighting.
The dynamic comparison uses LDA Sequence as the baseline. This is the authors' name for the original dynamic topic approach in the experiment. BERTopic appears both with independently calculated local topic descriptions and with the optional averaging of adjacent descriptions. The comparison between the two BERTopic variants tests the effect of the smoothing operation. Their comparison against LDA Sequence evaluates complete approaches to producing temporal topics.
Reading the scores
The paper measures topic coherence using normalized pointwise mutual information, abbreviated NPMI. The intuition is that terms chosen to describe the same subject should have an association in text. NPMI uses co-occurrence evidence to assess such association in relation to how frequently the terms occur by themselves. Its scale runs from -1 to 1, with 1 indicating perfect association. The authors cite earlier work on automatic topic coherence evaluation for the observation that a measure of this kind can approximate human judgments.
Topic diversity asks how much distinct vocabulary appears across the topic descriptions. The measure used here comes from Topic Modeling in Embedding Spaces and is based on the share of words that are unique across the topic lists. It ranges from 0 to 1. Scores toward 1 indicate greater variety, while lower scores indicate more repetition. The metric concerns the overlap of the words selected for the descriptions. Topics can use different terms while covering closely related subjects, or share terms that are important to each of them.
The metrics can reward different outputs. A set of words that frequently appear together can earn a strong coherence score for a topic, while several topics that use those same words can be penalized for low diversity. The reverse is also possible. A collection of word lists can avoid repetition while containing combinations whose association is weak. A comparison across both measures gives some indication of whether a system finds recognizable groups of words and whether its descriptions offer a varied view of the corpus.
The static comparison evaluates topic counts from 10 to 50, in steps of 10. Each setting is averaged across 3 runs. The static table caption describes each aggregate coherence or diversity score as an average across 15 runs. The caption for the encoder comparison describes the same topic-count range, step and repetition. These averages summarize performance across the tested settings. They are less informative about how a system behaves at a specific topic count or whether an ordering holds at every count.
In the dynamic procedure, the scores being averaged are NPMI values computed separately for each timestep with 50 topics. In the dynamic table caption, both coherence and diversity are calculated for 9 evaluated timesteps per dataset, with 3 runs per step. Each reported dynamic score represents an average of 27 values. These values come from a temporal evaluation protocol, while the static aggregate combines settings for different requested numbers of topics.
Observations averaged per BERTopic coherence score on Trump's tweets
The dynamic evaluation averages over timesteps, while the static evaluation averages over topic-count settings.
The numbers
| System or setting | observations per reported score |
|---|---|
| BERTopic, static topic-count settings | 15 |
| BERTopic, dynamic timestep settings (this paper) | 27 |
The chart shows the number of observations going into the reported averages, with the larger count identifying the design that averages over more values. The units being averaged differ between the two settings. The paper reports its quality comparisons in terms of which approaches led or remained competitive. Its reported findings give the direction of those comparisons, while the counts and ranges above describe how the measures were obtained.
How the static comparisons turned out
BERTopic had its clearest coherence advantage on the Trump corpus, where it received the highest topic coherence score. It remained competitive on coherence for 20 NewsGroups and BBC News. The distinction is important because the main result is a pattern across datasets, with a clear lead reported for the tweets and competitive results for the two news collections. The authors highlight that the tweets received lighter preprocessing. The results across those collections leave open how much of the pattern comes from representation, corpus characteristics, or preprocessing.
CTM led BERTopic on topic diversity across the static datasets. BERTopic was competitive on diversity, but the strongest pattern in its favor was coherence. This is consistent with the authors' account of the earlier CTM study, which also found high diversity using a different measure. Within this paper, the comparison makes clear that the most favorable judgment of BERTopic depends on the aim of the analysis. The distinction between associated terms within topics and distinct vocabulary across topics matters when reading the rankings.
The encoder results show stability across the two tested Sentence-BERT configurations. MiniLM and MPNET gave broadly stable coherence and diversity in BERTopic, which led the authors to suggest that MiniLM might be preferable when accelerator capacity is limited. The comparison also includes USE and Doc2Vec. The authors describe their performance as generally similar, with a marked exception for Doc2Vec on the tweets. The weak Doc2Vec showing on that collection also appears in the Top2Vec results. The paper interprets this pattern as evidence that Doc2Vec struggles to represent that particular dataset.
Top2Vec with Doc2Vec nevertheless had competitive coherence in the static comparison. Substituting MPNET for Doc2Vec inside Top2Vec reduced coherence and diversity across the datasets. The authors connect this to the joint vector space that Doc2Vec provides for words and documents. Top2Vec's way of describing a group makes use of that relationship. BERTopic can use a different encoder for the documents while still obtaining word weights from the original text. The same encoder change can therefore have different consequences in the two pipelines.
Dynamic scores and elapsed time
For the Trump corpus, the authors report that BERTopic surpassed LDA Sequence on both topic coherence and topic diversity. On the UN debates, BERTopic had the leading coherence result, and the diversity result did not give it the same lead. The comparison supports the use of the global-fit, local-count procedure for obtaining coherent temporal word lists across two different collections. Averaging adjacent profiles had little apparent effect on the reported coherence or diversity for either dataset.
An additional experiment measures wall time, the elapsed time a user would wait for a run to finish. Its input sizes come from the Trump collection, starting at 1000 documents and increasing to 43,000 documents in steps of 2000. The times are plotted in seconds. The authors used a machine with 2 Intel Xeon CPU cores at 2.00GHz and a Tesla P100-PCIE-16GB GPU. The accelerator was available for the embedding stage, making that hardware part of the conditions under which the timing observations apply.
CTM with MPNET took much longer than the other configurations. The authors present another view of the timing comparison with CTM omitted so that readers can distinguish the approaches whose times are closer together. In that view, LDA and NMF run faster than the neural approaches. BERTopic and Top2Vec have similar elapsed times when using the same encoder. MiniLM is also close to Doc2Vec in speed in this environment, which is why the paper identifies the MiniLM configuration as a plausible balance between elapsed time and topic quality.
The sizes describe the observed input range of the timing experiment. The reported comparison gives a speed ordering instead of a point estimate for each approach at a selected size. Its practical significance comes in part from comparing pipelines on the same machine and corpus. The GPU condition also matters when relating this ranking to the quality experiments. A smaller contextual encoder can look attractive when it maintains competitive scores and runs quickly with that hardware, while the cost of the same embedding step on a CPU-only machine remains uncertain.
What the ablations show
Changing the embeddings while keeping the description procedure
The paper does not report a full component-removal ablation. Its closest controlled analyses change the embeddings used by BERTopic, compare it with Top2Vec under shared clustering settings, toggle temporal smoothing, and measure elapsed time over different input sizes. Together they address questions about how sensitive the method is to its components. Each comparison has a particular scope determined by what was held fixed and what was measured.
The encoder exchange within BERTopic is the most direct test of its modular design. The same procedure for generating a topic's words is applied after clustering, whichever tested encoder provides the document vectors. If the measured coherence and diversity depended on a particular encoder, exchanging it could noticeably destabilize those results. The behavior of MiniLM and MPNET suggests that BERTopic can give similar results with either of the tested Sentence-BERT options. This is the observation behind the paper's suggestion that the smaller option can be attractive.
The Doc2Vec result gives that conclusion a boundary. Changing the document encoder can change which documents are neighbors, which clusters are found, and which terms are counted together. A later stage that weighs terms independently of vector geometry cannot recover a grouping that was missed earlier. On the tweets, the weaker Doc2Vec performance is consistent with the authors' explanation that those representations were less suitable for this corpus. The result tests the outputs of the complete configuration. It leaves the quality of the document vectors and individual cluster assignments unmeasured on their own.
Stability under an encoder exchange also has a narrower meaning than agreement between the resulting topics. The measures summarize association and overlap in selected term lists. They can be similar for different partitions of a corpus. A comparison of document memberships or of matched topics would be needed to establish how much the contents of the topics changed. The reported scores show that both tested Sentence-BERT configurations can deliver competitively scoring descriptions without establishing that their outputs are interchangeable for every analysis.
What the comparison with Top2Vec isolates
The Top2Vec comparison places a related clustering method beside BERTopic and fixes the settings of UMAP and HDBSCAN between them. With MPNET used in both, the comparison also holds the named document encoder in common. This makes the difference in how the systems construct topic words particularly relevant. BERTopic can rank words straight from the grouped documents, while Top2Vec's procedure relies on comparing words with the central positions of document groups.
The weak results for Top2Vec's MPNET variant across the datasets support the authors' explanation that the shared geometry of word and document vectors is important to its original design. BERTopic's representation procedure gives it a way to use document vectors on their own for grouping. The pattern is therefore evidence for the flexibility that motivated the new weighting scheme. How well it can make use of a particular set of document vectors remains an empirical question, as the Doc2Vec results illustrate.
A more narrowly isolated test of class-based weighting would start with the same document membership for every group and compare how alternative descriptions of those exact groups are judged. Such an experiment would directly address whether the count-based descriptions are better for irregular clusters than descriptions based on their centers. The reported comparison spans complete methods and establishes how their configurations perform under the benchmark. It does not measure cluster shape or attach the observed ranking to specific regions of the document space.
Smoothing and the cost of the pipeline
Turning smoothing on and off is a direct intervention on the temporal representation. The operation adds the previous normalized description to the calculation of the current one through an average. The topics have already been defined globally, so the comparison concerns how words are weighted once documents have been grouped and sliced. In the reported averages, the intervention made little apparent difference to either evaluation metric on either temporal corpus.
Coherence and diversity are computed for the topic lists in a slice and then averaged. Their values can remain similar even if a topic's leading vocabulary changes from one slice to the next. The finding therefore places a limit on the observed effect in the benchmark measures. A test of whether the transitions themselves look more believable would need to examine the relationship between descriptions across time, including whether sharp changes in vocabulary give an accurate picture of the underlying documents.
The wall-time experiment addresses a different aspect of the pipeline. It changes the amount of Trump text selected for a run and compares complete configurations under common hardware conditions. The similar times for BERTopic and Top2Vec with the same encoder are consistent with the importance of the embedding choice. The timing curves do not apportion elapsed time among embedding, projection, clustering, and word weighting. They show how those costs combine for the tested configurations, including cases such as CTM with MPNET where the complete pipeline takes considerably longer.
Taken together, the controlled comparisons give the clearest evidence for adaptability at the encoder stage and for the limited effect of smoothing on the chosen scores. They give indirect evidence for the authors' decision to decouple grouping from word selection. The contribution of each individual step, including the particular projection and density clustering choices, remains open to more targeted comparisons.
Limitations
Limits identified by the authors
BERTopic builds topics from clusters in which an assigned document contributes to a single topic. A document can in reality discuss several subjects that a reader would want the analysis to recognize. The authors suggest that a collection could be split into smaller units such as paragraphs or sentences before grouping. That changes the unit presented to the method, and the resulting assignments describe those segments. Combining such evidence into a reliable account of the original document remains a separate task.
The authors also suggest using HDBSCAN's soft membership information as a proxy for a distribution over topics in a document. This can convey more about how a document relates to multiple groups than its main assignment conveys. The proxy comes from the clustering procedure and its representation of membership. The fitting process that produces BERTopic's word profiles still works with the assignment of documents to clusters, so soft membership does not make the training procedure learn documents as mixtures of topics.
The description has a second weakness. Context only enters indirectly through the selection of documents to count. The scoring procedure gives terms weights based on pooled occurrences. Closely related words can rise together in the ranking and give the reader several variations of the same information. The authors suggest maximal marginal relevance, a kind of reordering that can take redundancy among candidates into account, as a possible treatment for the leading terms. They leave that suggestion untested.
The authors also qualify what automated evaluation can support. Coherence and diversity are proxies for judgments that can vary by reader and purpose. They cite research that questions whether NPMI's correspondence with human judgments carries over from conventional approaches to neural ones. A larger coherence value therefore gives a stronger result under one definition of word association. It tells less about whether a person trying to make sense of a particular corpus will find the groups and their descriptions useful. The paper discusses runtime in part because practical use depends on qualities that topic-list scores do not capture.
Finally, the authors expect embedding time to increase substantially without a GPU. They point to Doc2Vec as an available alternative in that setting, while recognizing that it was less stable in the quality comparison. The ranking from the timing experiment is consequently most informative for similar hardware and inputs. It leaves the performance of the complete workflow under other resource constraints to be established.
Limits of what the experimental design can establish
An outlier label leaves a document outside the topics used for description. That can help keep a group's word profile focused. It also means coherence and diversity describe the topics that were represented, while a separate question remains about coverage of the corpus. The evaluation presented here does not give an outlier rate for each configuration or track what kinds of material were left unassigned. In an application concerned with unusual or infrequent themes, understanding those documents could be as important as obtaining compact descriptions of the larger clusters.
The static corpora also provide limited leverage for attributing differences to preprocessing. The tweet collection varies from the news collections in several ways at once, including the length and source of the documents. Its better relative score for BERTopic establishes that the method performed well in that benchmark condition. A comparison of differently preprocessed versions of the same corpus would be needed to separate the effect of text cleaning from the effects of the domain and document form.
The averages summarize performance across runs and settings. A reader can use them to understand the reported ordering and overall competitiveness. They leave questions about the variation between runs, the size of a change at a given topic count, and whether an advantage persists throughout the specified range. The presence of source categories in 20 NewsGroups also should not be confused with the evaluation target. The reported metrics judge the topic word lists. Agreement with known categories or correctness of an individual document's assignment would require other evidence.
The temporal construction gives a shared identity to each topic across slices. This is useful when the object of interest is a continuing subject described using different words. It also sets a boundary on the kinds of change described. The fit uses all documents together, including those from later timesteps, to establish the topics. The experiment supports retrospective interpretation of the collection. It does not test whether earlier documents alone would have been enough to discover a topic that emerged later, or whether the method would identify when a topic split into separate subjects.
Likewise, a stable description under smoothing can reflect the averaging rule itself. To learn whether the rule improves an account of real changes, one would need a measure of temporal behavior or judgments grounded in the underlying documents. The paper's reported dynamic scores concern within-slice coherence and diversity. Its discussion of other metadata describes how the same computations could be reused, without an experiment on author- or journal-specific profiles.
The separation of components gives BERTopic room to benefit from better representations. The experiments demonstrate that changing the encoder is feasible and that several tested configurations yielded competitive results. They offer no general guarantee about what a stronger encoder on a separate similarity task will do for topic discovery. The groups must still correspond to distinctions in the collection that matter for the analysis, and the weighted vocabulary must communicate those distinctions to the reader.
What came after
Different answers to the problem of topic representation
Later papers that cite BERTopic pursue several of the same questions through different kinds of input and output. Some explore new mechanisms for discovering or describing topics. Others address what a useful evaluation should measure. The citations establish a connection to BERTopic, while the stated contributions of those papers identify the directions of the later work. In particular, a connection through a shared design question leaves the exact reuse of class-based term weighting open.
TopicGPT presents a prompt-based framework for topic modeling. It takes the problem of producing recognizable subjects from a collection in the direction of prompting. BERTopic gives that problem a particular division of labor. Embeddings provide evidence for group membership, and corpus counts support the descriptions. The contribution named by TopicGPT puts prompts at the center of the framework and opens a different way of specifying how a topic should be presented and understood.
Topic Modeling: Contextual Token Embeddings Are All You Need makes contextual representations of tokens central to topic modeling. A token is a unit of text represented by an encoder. The choice of unit changes where contextual evidence is available. BERTopic uses the contextual document representation to decide which texts belong together, then scores terms from their occurrences. Work centered on contextual token embeddings addresses the possibility of using context at a finer level within the text.
GINopic develops a topic modeling approach based on a graph isomorphism network. Its stated contribution places a graph-based learning mechanism at the center of the topic procedure. BERTopic's design instead begins with a vector for each document and passes through a density-based partition before selecting topic words. The citation places these ideas in the same discussion of how learned representations can supply structure for discovering themes.
Enhancing Short-Text Topic Modeling with Context Expansion and Prefix-Tuned VAEs addresses short text through context expansion and a prefix-tuned variational autoencoder, a form of representation-learning architecture. Its connection to the BERTopic study is especially clear at the level of the problem. Short documents provide limited observed words per item. BERTopic's tweet benchmark examines a procedure that groups those items and pools their wording afterwards. The later work's named method investigates expanding the context available to short-text topic discovery itself.
RoBERT2VecTM presents a topic extraction approach for Islamic studies. It connects the broader methodological discussion to a particular domain where the usefulness of a topic depends on the vocabulary and distinctions found in that material. BERTopic's experiments establish behavior on news, tweets, and debate transcripts. A domain-specific topic extraction paper asks what kind of discoverable structure is useful for its own collection.
Time and the reader's judgment
Beyond Coherence targets temporal consistency and interpretability in dynamic topic modeling. Its stated goals correspond to questions raised by BERTopic's adjacent-slice averaging. A description can contain strongly associated words at a given time, while the sequence of descriptions remains difficult to interpret as the development of a subject. The later paper makes the quality of that sequence and its readability explicit objectives.
When Numbers Tell Half the Story studies alignment between automated topic metrics and human judgment. BERTopic's discussion already recognizes that a coherence or diversity score can indicate one property of the word lists without settling how readers will assess them. The later work makes the relationship between the measured quantities and human assessments its central question. That relationship matters when topic descriptions will guide a substantive reading of documents, since association, vocabulary variety, and the usefulness of a group can lead to different judgments.
Towards Modern Topic Models surveys taxonomies and changes in how topic analysis is approached, including a turn towards methods centered on large language models. BERTopic is concerned with a distinction that helps put such changes in perspective. The way an approach finds related material can be specified separately from how it communicates the resulting subjects. Across the later work, questions about representation, time, and evaluation continue to depend on both choices. A topic can be easy to describe, stable within a collection, or useful for a reader's purpose, and establishing each property calls for evidence suited to it.
Fields, topics and concepts
Shelves 6The field of science this work belongs to (OpenAlex fields).Computer Science · 19,503 worksArtificial Intelligence · 18,805 worksArts and Humanities · 17,959 worksLanguage and Linguistics · 17,789 worksSocial Sciences · 2,009 worksGeneral Social Sciences · 256 works
Concepts 2Key ideas and methods explained on our concept pages.Topic modeling · 47 worksTF-IDF · 26 works
Cite
Cite as Maarten Grootendorst. 2022. BERTopic: Neural topic modeling with a class-based TF-IDF procedure. arXiv:2203.05794.
@misc{grootendorst2022bertopic,
title = {{BERTopic: Neural topic modeling with a class-based TF-IDF procedure}},
author = {Maarten Grootendorst},
year = {2022},
doi = {10.48550/arxiv.2203.05794},
eprint = {2203.05794},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2203.05794}
}References
- Charu C Aggarwal, Alexander Hinneburg, and Daniel A Keim. 2001. On the surprising behavior of distance metrics in high dimensional space. In International conference on database theory, pages 420–434. Springer. OpenAlex ↗ · Scholar ↗
- Mebarka Allaoui, Mohammed Lamine Kherfi, and Abdelhakim Cheriet. 2020. Considerably improving clustering algorithms using umap dimensionality reduction technique: A comparative study. In International Conference on Image and Signal Processing, pages 317–325. Springer. OpenAlex ↗ · Scholar ↗
- Dimo Angelov. 2020. Top2vec: Distributed representations of topics. arXiv preprint arXiv:2008.09470. our card
- Alexander Baturo, Niheer Dasandi, and Slava J Mikhaylov. 2017. Understanding state preferences with text as data: Introducing the un general debate corpus. Research & Politics, 4(2):2053168017712821. OpenAlex ↗ · Scholar ↗
- Kevin Beyer, Jonathan Goldstein, Raghu Ramakrishnan, and Uri Shaft. 1999. When is “nearest neighbor” meaningful? In International conference on database theory, pages 217–235. Springer. OpenAlex ↗ · Scholar ↗
- Federico Bianchi, Silvia Terragni, and Dirk Hovy. 2020a. Pre-training is a hot topic: Contextualized document embeddings improve topic coherence. arXiv preprint arXiv:2004.03974. our card
- Federico Bianchi, Silvia Terragni, Dirk Hovy, Debora Nozza, and Elisabetta Fersini. 2020b. Cross-lingual contextualized topic models with zero-shot learning. arXiv preprint arXiv:2004.07737. our card
- David M Blei and John D Lafferty. 2006. Dynamic topic models. In Proceedings of the 23rd international conference on Machine learning, pages 113–120. OpenAlex ↗ · Scholar ↗
- David M Blei, Andrew Y Ng, and Michael I Jordan. 2003. Latent dirichlet allocation. the Journal of machine Learning research, 3:993–1022. OpenAlex ↗ · Scholar ↗
- Gerlof Bouma. 2009. Normalized (pointwise) mutual information in collocation extraction. Proceedings of GSCL, 30:31–40. OpenAlex ↗ · Scholar ↗
- Ziqiang Cao, Sujian Li, Yang Liu, Wenjie Li, and Heng Ji. 2015. A novel neural topic model and its supervised extension. In Proceedings of the AAAI Conference on Artificial Intelligence, pages 2210–2216. OpenAlex ↗ · Scholar ↗
- Jaime Carbonell and Jade Goldstein. 1998. The use of mmr, diversity-based reranking for reordering documents and producing summaries. In Proceedings of the 21st annual international ACM SIGIR conference on Research and development in information retrieval, pages 335–336. OpenAlex ↗ · Scholar ↗
- Daniel Cer, Yinfei Yang, Sheng-yi Kong, Nan Hua, Nicole Limtiaco, Rhomni St John, Noah Constant, Mario Guajardo-Cespedes, Steve Yuan, Chris Tar, et al. 2018. Universal sentence encoder. arXiv preprint arXiv:1803.11175. OpenAlex ↗ · Scholar ↗
- Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. Bert: Pre-training of deep bidirectional transformers for language understanding. arXiv preprint arXiv:1810.04805. our card
- Adji B Dieng, Francisco JR Ruiz, and David M Blei. 2020. Topic modeling in embedding spaces. Transactions of the Association for Computational Linguistics, 8:439–453. our card
- Cédric Févotte and Jérôme Idier. 2011. Algorithms for nonnegative matrix factorization with the $\beta$-divergence. Neural computation, 23(9):2421–2456. OpenAlex ↗ · Scholar ↗
- Derek Greene and Pádraig Cunningham. 2006. Practical solutions to the problem of diagonal dominance in kernel document clustering. In Proc. 23rd International Conference on Machine learning (ICML'06), pages 377–384. ACM Press. OpenAlex ↗ · Scholar ↗
- Alexander Hoyle, Pranav Goel, Andrew Hian-Cheong, Denis Peskov, Jordan Boyd-Graber, and Philip Resnik. 2021. Is automated topic model evaluation broken? the incoherence of coherence. Advances in Neural Information Processing Systems, 34. OpenAlex ↗ · Scholar ↗
- Thorsten Joachims. 1996. A probabilistic analysis of the rocchio algorithm with tfidf for text categorization. Technical report, Carnegie-mellon univ pittsburgh pa dept of computer science. OpenAlex ↗ · Scholar ↗
- Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu Soricut. 2019. Albert: A lite bert for self-supervised learning of language representations. arXiv preprint arXiv:1909.11942. our card
- Ken Lang. 1995. Newsweeder: Learning to filter netnews. In Machine Learning Proceedings 1995, pages 331–339. Elsevier. OpenAlex ↗ · Scholar ↗
- Hugo Larochelle and Stanislas Lauly. 2012. A neural autoregressive topic model. Advances in Neural Information Processing Systems, 25. OpenAlex ↗ · Scholar ↗
- Jey Han Lau, David Newman, and Timothy Baldwin. 2014. Machine reading tea leaves: Automatically evaluating topic coherence and topic model quality. In Proceedings of the 14th Conference of the European Chapter of the Association for Computational Linguistics, pages 530–539. our card
- Quoc Le and Tomas Mikolov. 2014. Distributed representations of sentences and documents. In International conference on machine learning, pages 1188–1196. PMLR. our card
- Jinhyuk Lee, Wonjin Yoon, Sungdong Kim, Donghyeon Kim, Sunkyu Kim, Chan Ho So, and Jaewoo Kang. 2020. Biobert: a pre-trained biomedical language representation model for biomedical text mining. Bioinformatics, 36(4):1234–1240. our card
- Yang Liu, Zhiyuan Liu, Tat-Seng Chua, and Maosong Sun. 2015. Topical word embeddings. In Twenty-ninth AAAI conference on artificial intelligence. OpenAlex ↗ · Scholar ↗
- Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining approach. arXiv preprint arXiv:1907.11692. our card
- L. McInnes, J. Healy, and J. Melville. 2018. UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction (http://arxiv.org/abs/1802.03426). ArXiv e-prints. our card
- Leland McInnes and John Healy. 2017. Accelerated hierarchical density based clustering. In Data Mining Workshops (ICDMW), 2017 IEEE International Conference on, pages 33–42. IEEE. OpenAlex ↗ · Scholar ↗
- Leland McInnes, John Healy, and Steve Astels. 2017. hdbscan: Hierarchical density based clustering. The Journal of Open Source Software, 2(11):205. our card
- Leland McInnes, John Healy, Nathaniel Saul, and Lukas Grossberger. 2018. Umap: Uniform manifold approximation and projection. The Journal of Open Source Software, 3(29):861. OpenAlex ↗ · Scholar ↗
- Dat Quoc Nguyen, Richard Billingsley, Lan Du, and Mark Johnson. 2015. Improving topic models with latent feature word representations. Transactions of the Association for Computational Linguistics, 3:299–313. our card
- Divya Pandove, Shivan Goel, and Rinkl Rani. 2018. Systematic review of clustering high-dimensional and large datasets. ACM Transactions on Knowledge Discovery from Data (TKDD), 12(2):1–68. OpenAlex ↗ · Scholar ↗
- Jipeng Qiang, Ping Chen, Tong Wang, and Xindong Wu. 2017. Topic modeling over short texts by incorporating word embeddings. In Pacific-Asia Conference on Knowledge Discovery and Data Mining, pages 363–374. Springer. OpenAlex ↗ · Scholar ↗
- Nils Reimers and Iryna Gurevych. 2019. Sentence-bert: Sentence embeddings using siamese bert-networks (https://arxiv.org/abs/1908.10084). In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing. Association for Computational Linguistics. our card
- Nils Reimers and Iryna Gurevych. 2020. Making monolingual sentence embeddings multilingual using knowledge distillation. arXiv preprint arXiv:2004.09813. our card
- Min Shi, Jianxun Liu, Dong Zhou, Mingdong Tang, and Buqing Cao. 2017. We-lda: a word embeddings augmented lda model for web services clustering. In 2017 ieee international conference on web services (icws), pages 9–16. IEEE. OpenAlex ↗ · Scholar ↗
- Suzanna Sia, Ayush Dalmia, and Sabrina J Mielke. 2020. Tired of topic models? clusters of pretrained word embeddings make for fast and good topics too! arXiv preprint arXiv:2004.14914. OpenAlex ↗ · Scholar ↗
- Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, and Tie-Yan Liu. 2020. Mpnet: Masked and permuted pre-training for language understanding. arXiv preprint arXiv:2004.09297. our card
- Michael Steinbach, Levent Ertöz, and Vipin Kumar. 2004. The challenges of clustering high dimensional data. In New directions in statistical physics, pages 273–309. Springer. OpenAlex ↗ · Scholar ↗
- Silvia Terragni, Elisabetta Fersini, Bruno Giovanni Galuzzi, Pietro Tropeano, and Antonio Candelieri. 2021. Octis: Comparing and optimizing topic models is simple! In Proceedings of the 16th Conference of the European Chapter of the Association for Computational Linguistics: System Demonstrations, pages 263–270. OpenAlex ↗ · Scholar ↗
- Nandan Thakur, Nils Reimers, Johannes Daxenberger, and Iryna Gurevych. 2020. Augmented sbert: Data augmentation method for improving bi-encoders for pairwise sentence scoring tasks. arXiv preprint arXiv:2010.08240. our card
- Laure Thompson and David Mimno. 2020. Topic modeling with contextualized word representation clusters. arXiv preprint arXiv:2010.12626. OpenAlex ↗ · Scholar ↗
- He Zhao, Dinh Phung, Viet Huynh, Yuan Jin, Lan Du, and Wray Buntine. 2021. Topic modelling meets deep neural networks: A survey. arXiv preprint arXiv:2103.00498. OpenAlex ↗ · Scholar ↗
This page in Markdown https://md.research.elamur.ai/free/en/papers/grootendorst-2022-bertopic-neural-topic-modeling-class/