保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Large Language Models

Advanced Topic Modeling with LLMs

A deep dive into topic modeling by leveraging representation models and generative AI with BERTopic Alex Davis July 21, 202511 min read

Introduction

This article is a continuation of topic modeling open-source intelligence (OSINT) from the OpenAlex API. In a previous article, I give an introduction into topic modeling, the data used, and a traditional NLP approach using Latent Dirichlet Allocation (LDA). See the previous article here: Topic Modeling Open-Source Research with the OpenAlex APIAn overview of topic modeling global research through the OpenAlex API and visualizing resultsAlex Davis · 9 min read This article uses a more advanced approach of topic modeling by leveraging representation models, generative AI, and other advanced techniques. We leverage BERTopic to bring several models together into one pipeline, visualize our topics, and explore variations of topic models. Learn this step by step with the interactive AI Engineer roadmap. Image by Author The data used comes from the OpenAlex API (https://openalex.org/). This is a dataset/catalogue of open-source research from around the world. The data is freely accessible under a No Rights Reserved license (CC0 license). ···

The BERTopic Pipeline

Using a traditional approach to topic modeling can be difficult, needing to build your own pipeline to clean your data, tokenize, lemmatize, create features, etc. Traditional models like LDA or LSA are also computationally expensive and often yield poor results. BERTopic leverages the transformer architecture through embedding models, and incorporates other components like dimensionality reduction and topic representation models, to create high-performing topic models. BERTopic also provides variations of models to fit a variety of data and use cases, visualizations to explore results, and more. Image by Author The biggest advantage of BERTopic is its modularity. Seen above, the pipeline is comprised of several different models:

  1. Embedding model
  2. Dimensionality Reduction model
  3. Clustering model
  4. Tokenizer
  5. Weighting Scheme
  6. Representation model (optional)

Therefore, we can experiment with different models in each component, each with its own parameters. For example, we can try different embedding models, switch the dimensionality reduction from PCA to UMAP, or try fine-tuning the parameters on our clustering model. This is a huge advantage that allows us to fit a topic model to our data and use case. ··· First, we need to import to necessary modules. Most of these are to build the components of our BERTopic model. python

#import packages for data management
import pickle

#import packages for topic modeling
from bertopic import BERTopic
from bertopic.representation import KeyBERTInspired
from bertopic.vectorizers import ClassTfidfTransformer
from sentence_transformers import SentenceTransformer
from umap.umap_ import UMAP
from hdbscan import HDBSCAN
from sklearn.feature_extraction.text import CountVectorizer

#import packages for data manipulation and visualization
import pandas as pd
import matplotlib.pyplot as plt
from scipy.cluster import hierarchy as sch

Embedding Model

The main component of the BERTopic model is the embedding model. First, we initialize the model using the sentence transformer. You can then specify the embedding model you would like to use. In this case, I am using a relatively small model (~30 million parameters). While we can probably get better results using larger embedding models, I decided to use a smaller model to emphasize speed in this pipeline. You can find and compare embedding models based on their size, performance, intended use, etc. by using the MTEB leaderboard from Hugging Face (https://huggingface.co/spaces/mteb/leaderboard ). python

#initalize embedding model
embedding_model = SentenceTransformer('thenlper/gte-small')

#calculate embeddings
embeddings = embedding_model.encode(data['all_text'].tolist(), show_progress_bar=True)

Once we run our model, we can use the .shape function to see the size of the vectors produced. Below, we can see that each embedding contains 384 values which make up the meaning of each document. python

#invesigate shape and size of vectors
embeddings.shape

#output: (6102, 384)

Dimensionality Reduction Model

The next component of the BERTopic model is the dimensionality reduction model. As high-dimensional data can be troublesome to model, we can use a dimensionality reduction model to represent the embeddings in a lower dimensional representation without losing too much information. Image by Author There are several different types of dimensionality reduction models, with Principal Component Analysis (PCA) being the most popular. In this case, we will use a Uniform Manifold Approximation and Projection (UMAP) model. The UMAP model is a non-linear model and is likely to better handle the complex relationships in our data better than PCA. python

#initialize dimensionality reduction model and reduce embeddings
umap_model = UMAP(n_neighbors=5, min_dist=0.0, metric='cosine', random_state=42)
reduced_embeddings = umap_model.fit_transform(embeddings)

It is important to note that dimensionality reduction is not a solve-all for high-dimensional data. Dimensionality reduction presents a tradeoff between speed and accuracy as information is lost. These models need to be well-thought out and experimented with to avoid losing too much information while maintaining speed and scalability.

Clustering Model

The third step is to use the reduced embeddings and create clusters. While clustering is not usually necessary for topic modeling, we can leverage density-based clustering models to isolate outliers and eliminate noise in our data. Below, we initialize the Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN) model and create our clusters. python

#initialize clustering model and cluster
hdbscan_model = HDBSCAN(min_cluster_size=30, metric='euclidean', cluster_selection_method='eom').fit(reduced_embeddings)
clusters = hdbscan_model.labels_

A density-based approach gives us a few advantages. Documents are not forced into clusters that they shouldn’t be assigned to, therefore isolating outliers and reducing noise in our data. Also, as opposed to centroid-based models, we do not specify the number of clusters, and clusters are more likely to be well-defined. See my guide to clustering algorithms: A Guide to Clustering AlgorithmsAn overview of clustering and the different families of clustering algorithms.Alex Davis · 5 min read See the code below to visualize the results of the clustering model. python

#create dataframe of reduced embeddings and clusters
df = pd.DataFrame(reduced_embeddings, columns = ['x', 'y'])
df['Cluster'] = [str(c) for c in clusters]

#split between clusters and outliers
to_plot = df.loc[df.Cluster != '-1', :]
outliers = df.loc[df.Cluster == '-1', :]

#plot clusters
plt.scatter(outliers.x, outliers.y, alpha = 0.05, s = 2, c = 'grey')
plt.scatter(to_plot.x, to_plot.y, alpha = 0.6, s = 2, c = to_plot.Cluster.astype(int), cmap = 'tab20b')
plt.axis('off')

Image by Author We can see well-defined clusters that do not overlap. We can also see some smaller clusters group together to make up higher-level topics. Lastly, we can see several documents are greyed out and identified as outliers. ···

Creating a BERTopic Pipeline

We now have the necessary components to build our BERTopic pipeline (embedding model, dimensionality reduction model, clustering model). We can use the models we have initialized and fit them to our data using the BERTopic function. python

#use models above to BERTopic pipeline
topic_model = BERTopic(
  embedding_model=embedding_model,          # Step 1 - Extract embeddings
  umap_model=umap_model,                    # Step 2 - Reduce dimensionality
  hdbscan_model=hdbscan_model,              # Step 3 - Cluster reduced embeddings
  verbose = True).fit(data['all_text'].tolist(), embeddings)

Since I know I ingested papers about human-machine interfaces (augmented reality, virtual reality), let’s see which topic align to the term “augmented reality”. python

#topics most similar to 'augmented reality'
topic_model.find_topics("augmented reality")

#output: ([18, 3, 16, 24, 12], [0.9532771, 0.9498462, 0.94966936, 0.9451431, 0.9417263])

From the output above, we can see that topics 18, 3, 16, 24, and 12 highly align to the term “augmented reality”. All these topic should (hopefully) contribute to the broader theme of augmented reality, but each cover a different aspect. To confirm this, let’s investigate the topic representations. A topic representation is a list of terms that aims to properly represent the underlying theme of the topic. For example, the terms “cake”, “candles”, “family”, and “presents” may collectively represent the topic of birthdays or birthday parties. We can use the get_topic() function to investigate the representation of topic 18. python

#investigate topic 18
topic_model.get_topic(18)

Image by Author In the above representation, we see some useful terms like “reality”, “virtual”, “augmented”, etc. However, this is not useful as a whole, as we see several stop words like “and” and “the”. This is because BERTopic uses Bag of Words as the default way to represent topics. This representation may also match other representations about augmented reality. Next, we will improve our BERTopic pipeline to create more meaningful topic representations that are give us more insight into these themes. ···

Improving Topic Representations

We can improve the topic representations by adding a weighting scheme, which will highlight the most important terms and better differentiate our topics. This does not replace the Bag of Words model, but improves upon it. Below we add a TF-IDF model to better determine the importance of each term. We use the update_topics() function to update our pipeline. python

#initialize tokenizer model
vectorizer_model = CountVectorizer(stop_words="english")

#initialize ctfidf model to weight terms
ctfidf_model = ClassTfidfTransformer()

#add tokenizer and ctfidf to pipeline
topic_model.update_topics(data['all_text'].tolist(), vectorizer_model=vectorizer_model, ctfidf_model=ctfidf_model)

python

#investigate how topic representations have changed
topic_model.get_topic(18)

Image by Author With TF-IDF, these topic representations are much more useful. We can see that the meaningless stop words are gone, other terms appear that help describe the topic, and terms are reordered by their importance. But we do not have to stop here. Thanks to countless new developments in the world of AI and NLP, there are methods we can leverage to fine-tune these representations. To fine-tune, we can take one of two approaches:

  1. A representation model
  2. A generative model

Fine-Tuning with a Representation Model

First, let’s add the KeyBERTInspired model as our representation model. This leverages BERT to compare the semantic similarity of the TF-IDF representations with the documents themselves to better determine the relevance of each term, rather than the importance. See all representation model options here:https://maartengr.github.io/BERTopic/getting_started/representation/representation.html#keybertinspired python

#initilzae representation model and add to pipeline
representation_model = KeyBERTInspired()
topic_model.update_topics(data['all_text'].tolist(), vectorizer_model=vectorizer_model, ctfidf_model=ctfidf_model, representation_model=representation_model)

Image by Author Here, we see a fairly major change in the terms, with some additional terms and acronyms. Comparing this to the TF-IDF representation, we again get a better understanding of what this topic is about. Also notice that the scores changed from the TF-IDF weights, which did not have any meaning without context, to scores between 0–1. These new scores represent the semantic similarity scores.

Topic Model Visualizations

Before we move to generative models for fine-tuning, let’s explore some of the visualizations that BERTopic offers. Visualizing topic models is crucial in understanding your data and how the model is working. First, we can visualize our topics in a 2-dimensional space, allowing us to see the size of topics and what other topics are similar. Below, we can see we have many topics, with clusters of topics making up larger themes. We can also see a topic that is large and isolated, indicating that there is a lot of similar research regarding crispr. Image by Author Let’s zoom into these clusters of topics to see how they break down higher-level themes. Below, we zoom into topics regarding augmented and virtual reality and see how some topics cover different domains and applications. Image by Author Image by Author We can also quickly visualize the most important or most relevant terms in each topic. Again, this is dependent on your approach to the topic representations. Image by Author We can also use a heatmap to explore the similarity between topics. Image by Author These are just a few of the visualizations that BERTopic offers. See the full list here:https://maartengr.github.io/BERTopic/getting_started/visualization/visualization.html

Leveraging Generative Models

For our last step of fine-tuning our topic representations, we can leverage generative AI to produce representations that are coherent descriptions of the topic. BERTopic offers an easy way to leverage OpenAI’s GPT models to interact with the topic model. We first establish a prompt that shows the model the data and the current representation of the topics. We then ask it to generate a short label for each topic. We then initialize the client and model, and update our pipeline. python

import openai
from bertopic.representation import OpenAI

#promt for GPT to create topic labels
prompt = """
I have a topic that contains the following documents:
[DOCUMENTS]

The topic is described by the following key words: [KEYWORDS]

Based on the information above, extract a short topic label in the following format:
topic: <short topic label>
"""

#import GPT
client = openai.OpenAI(api_key='API KEY')

#add GPT as representation model
representation_model = OpenAI(client, model = 'gpt-3.5-turbo', exponential_backoff=True, chat=True, prompt=prompt)
topic_model.update_topics(data['all_text'].tolist(), representation_model=representation_model)

Now, let’s go back to the augmented reality topic. python

#investigate how topic representations have changed
topic_model.get_topic(18)

#output: [('Comparative analysis of virtual and augmented reality for immersive analytics',1)]

The topic representation now reads “Comparative analysis of virtual and augmented reality for immersive analytics”. The topic is now much more clear, as we can see the objectives, technologies, and domain included in these documents. Below is the full list of our new topic representations. Image by Author It does not take much code to see how powerful generative AI is in supporting our topic model and its representations. It is of course extremely important to dig deeper and validate these outputs as you build your model and to do plenty of experimentation with different models, parameters, and approaches.

Leveraging Topic Models Variations

Lastly, BERTopic provides several variations of topic models to provide solutions for different data and use cases. These include time-series, hierarchical, supervised, semi-supervised, and many more. See the full list and documentation here:https://maartengr.github.io/BERTopic/getting_started/topicsovertime/topicsovertime.html Let’s quickly explore one of these possibilities with hierarchical topic modeling. Below, we create a linkage function using scipy, which establishes distances between our topics. We can easily fit it to our data and visualize the hierarchy of topics. python

#create linkages between topics
linkage_function = lambda x: sch.linkage(x, 'single', optimal_ordering=True)
hierarchical_topics = topic_model.hierarchical_topics(data['all_text'], linkage_function=linkage_function)

#visualize topic model hierarchy
topic_model.visualize_hierarchy(hierarchical_topics=hierarchical_topics)

Image by Author In the visualization above, we can see how topics put themselves together to create broader and broader topics. For example, we see topics 25 and 30 come together to form “Smart Cities and Sustainable Development”. This model provides an awesome capability of being able to zoom in and out and deciding how broad or narrow we would like our topics to be. ···

Conclusion

In this article, we got to see the power of BERTopic for topic modeling. BERTopics use of transformers and embedding models dramatically improves results from traditional approaches. The BERTopic pipeline also offers both power and modularity, leveraging several models and allowing you to plug-in other models to fit your data. All of these models can be fine-tuned and put together to create a powerful topic model. You can also integrate representation and generative models to improve topic representations and improve interpretability. BERTopic also offers several visualizations to truly explore your data and validate your model. Lastly, BERTopic offers several variations of topic modeling, like time-series or hierarchical topic modeling, to better fit your use case. ··· I hope you have enjoyed my article! Please feel free to comment, ask questions, or request other topics. Connect with me on LinkedIn:https://www.linkedin.com/in/alexdavis2020/

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Alex Davis

See all from Alex Davis Deep DivesLlm ApplicationsMachine LearningNatural Lanugage ProcessingTopic Modeling Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

How to Analyze and Optimize Your LLMs in 3 Steps

Large Language Models Learn to enhance your LLMs with my 3 step process, inspecting, improving and iterating on your LLMs Eivind Kjosbakken September 11, 20258 min read

Statistics Bootcamp 8: A Tale of Two Means

Statistics Learn the math and methods behind the libraries you use daily as a data scientist Adrienne Kline January 4, 202312 min read

Building a Scalable and Accurate Audio Interview Transcription Pipeline with Google Gemini

Large Language Models From prototype to production: real-world insights into building smarter transcription pipelines with LLMs. Ugo Pradère April 29, 202518 min read

10 Must-Know Linux Commands

Artificial Intelligence An introductory tutorial for Linux operating system Soner Yıldırım December 21, 20205 min read

Build better time-series models: introducing ByteHub

Machine Learning Learn how to use a feature store to streamline your data science workflow Toby Coleman April 27, 20213 min read

Fine-tuning pretrained NLP models with Huggingface's Trainer

Artificial Intelligence A simple way to fine-tune pretrained NLP models without native Pytorch or Tensorflow Vincent Tan March 25, 20215 min read

PyTest for Machine Learning - a simple example-based tutorial

Artificial Intelligence We show how to use PyTest for writing effective test functions for a simple machine learning module. Tirthajyoti Sarkar April 24, 20219 min read

Retain Customers with Time to Event Modeling Driven Intervention

Machine Learning Hands-on Tutorials Pinpointing customer churn at the right time using XGBoost By Charles Frenzel, Baichuan... Charles Frenzel June 3, 202114 min read

The Forceful and Insistent Application of Gender Stereotypes by Google Translate

Machine Learning How does one of the most common language translation tools used across the world perpetuate bias? Sourojit Ghosh(G) December 6, 20215 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close