Retour aux articles
IAHugging Face Blog

Introducing BERTopic Integration with the Hugging Face Hub

Back to Articles Introducing BERTopic Integration with the Hugging Face Hub Published May 31, 2023 Update on GitHub Upvote 10 +4 Maarten Grootendorst MaartenGr Follow guest Daniel van Strien davanstrien...

Le flux RSS ne fournissait qu'un extrait. FlowMarket a récupéré le contenu public disponible depuis la page originale, sans contourner les contenus réservés.

Introducing BERTopic Integration with the Hugging Face Hub

Introducing BERTopic Integration with the Hugging Face Hub

  • +4
Maarten Grootendorst
Daniel van Strien
Open in Colab

We are thrilled to announce a significant update to the BERTopic Python library, expanding its capabilities and further streamlining the workflow for topic modelling enthusiasts and practitioners. BERTopic now supports pushing and pulling trained topic models directly to and from the Hugging Face Hub. This new integration opens up exciting possibilities for leveraging the power of BERTopic in production use cases with ease.

What is Topic Modelling?

Topic modelling is a method that can help uncover hidden themes or "topics" within a group of documents. By analyzing the words in the documents, we can find patterns and connections that reveal these underlying topics. For example, a document about machine learning is more likely to use words like "gradient" and "embedding" compared to a document about baking bread.

Each document usually covers multiple topics in different proportions. By examining the word statistics, we can identify clusters of related words that represent these topics. This allows us to analyze a set of documents and determine the topics they discuss, as well as the balance of topics within each document. More recently, new approaches to topic modelling have moved beyond using words to using more rich representations such as those offered through Transformer based models.

What is BERTopic?

BERTopic is a state-of-the-art Python library that simplifies the topic modelling process using various embedding techniques and c-TF-IDF to create dense clusters allowing for easily interpretable topics whilst keeping important words in the topic descriptions.

An overview of the BERTopic library

Whilst BERTopic is easy to get started with, it supports a range of advanced approaches to topic modelling including guided , supervised , semi-supervised and manual topic modelling. More recently BERTopic has added support for multi-modal topic models. BERTopic also have a rich set of tools for producing visualizations.

BERTopic provides a powerful tool for users to uncover significant topics within text collections, thereby gaining valuable insights. With BERTopic, users can analyze customer reviews, explore research papers, or categorize news articles with ease, making it an essential tool for anyone looking to extract meaningful information from their text data.

BERTopic Model Management with the Hugging Face Hub

With the latest integration, BERTopic users can seamlessly push and pull their trained topic models to and from the Hugging Face Hub. This integration marks a significant milestone in simplifying the deployment and management of BERTopic models across different environments.

The process of training and pushing a BERTopic model to the Hub can be done in a few lines

from bertopic import BERTopic

topic_model = BERTopic("english")
topics, probs = topic_model.fit_transform(docs)
topic_model.push_to_hf_hub('davanstrien/transformers_issues_topics')

You can then load this model in two lines and use it to predict against new data.

from bertopic import BERTopic
topic_model = BERTopic.load("davanstrien/transformers_issues_topics")

By leveraging the power of the Hugging Face Hub, BERTopic users can effortlessly share, version, and collaborate on their topic models. The Hub acts as a central repository, allowing users to store and organize their models, making it easier to deploy models in production, share them with colleagues, or even showcase them to the broader NLP community.

You can use the libraries filter on the hub to find BERTopic models.

BERTopic hub filter

Once you have found a BERTopic model you are interested in you can use the Hub inference widget to try out the model and see if it might be a good fit for your use case.

Once you have a trained topic model, you can push it to the Hugging Face Hub in one line. Pushing your model to the Hub will automatically create an initial model card for your model, including an overview of the topics created. Below you can see an example of the topics resulting from a model trained on ArXiv data .

Due to the improved saving procedure, training on large datasets generates small model sizes. In the example below, a BERTopic model was trained on 100,000 documents, resulting in a ~50MB model keeping all of the original’s model functionality. For inference, the model can be further reduced to only ~3MB!

Image de l'article

The benefits of this integration are particularly notable for production use cases. Users can now effortlessly deploy BERTopic models into their existing applications or systems, ensuring seamless integration within their data pipelines. This streamlined workflow enables faster iteration and efficient model updates and ensures consistency across different environments.

safetensors: Ensuring Secure Model Management

In addition to the Hugging Face Hub integration, BERTopic now supports serialization using the safetensors library . Safetensors is a new simple format for storing tensors safely (instead of pickle), which is still fast (zero-copy). We’re excited to see more and more libraries leveraging safetensors for safe serialization. You can read more about a recent audit of the library in this blog post .

An example of using BERTopic to explore RLHF datasets

To illustrate some of the power of BERTopic let's look at an example of how it can be used to monitor changes in topics in datasets used to train chat models.

The last year has seen several datasets for Reinforcement Learning with Human Feedback released. One of these datasets is the OpenAssistant Conversations dataset . This dataset was produced via a worldwide crowd-sourcing effort involving over 13,500 volunteers. Whilst this dataset already has some scores for toxicity, quality, humour etc., we may want to get a better understanding of what types of conversations are represented in this dataset.

BERTopic offers one way of getting a better understanding of the topics in this dataset. In this case, we train a model on the English assistant responses part of the datasets. Resulting in a topic model with 75 topics.

BERTopic gives us various ways of visualizing a dataset. We can see the top 8 topics and their associated words below. We can see that the second most frequent topic consists mainly of ‘response words’, which we often see frequently from chat models, i.e. responses which aim to be ‘polite’ and ‘helpful’. We can also see a large number of topics related to programming or computing topics as well as physics, recipes and pets.

Words associated with top 8 topics

databricks/databricks-dolly-15k is another dataset that can be used to train an RLHF model. The approach taken to creating this dataset was quite different from the OpenAssistant Conversations dataset since it was created by employees of Databricks instead of being crowd sourced via volunteers. Perhaps we can use our trained BERTopic model to compare the topics across these two datasets?

The new BERTopic Hub integrations mean we can load this trained model and apply it to new examples.

topic_model = BERTopic.load("davanstrien/chat_topics")

We can predict on a single example text:

example = "Stalemate is a drawn position. It doesn't matter who has captured more pieces or is in a winning position"
topic, prob = topic_model.transform(example)

We can get more information about the predicted topic

topic_model.get_topic_info(topic)

We can see here the topics predicted seem to make sense. We may want to extend this to compare the topics predicted for the whole dataset.

from datasets import load_dataset

dataset = load_dataset("databricks/databricks-dolly-15k")
dolly_docs = dataset['train']['response']
dolly_topics, dolly_probs = topic_model.transform(dolly_docs)

We can then compare the distribution of topics across both datasets. We can see here that there seems to be a broader distribution across topics in the dolly dataset according to our BERTopic model. This might be a result of the different approaches to creating both datasets (we likely want to retrain a BERTopic across both datasets to ensure we are not missing topics to confirm this).

Topic distribution comparison

Comparison of the distribution of topics between the two datasets

We can potentially use topic models in a production setting to monitor whether topics drift to far from an expected distribution. This can serve as a signal that there has been drift between your original training data and the types of conversations you are seeing in production. You may also decide to use a topic modelling as you are collecting training data to ensure you are getting examples for topics you may particularly care about.

Get Started with BERTopic and Hugging Face Hub

You can visit the official documentation for a quick start guide to get help using BERTopic.

You can find a starter Colab notebook here that shows how you can train a BERTopic model and push it to the Hub.

Some examples of BERTopic models already on the hub:

  • MaartenGr/BERTopic_ArXiv : a model trained on ~30000 ArXiv Computation and Language articles (cs.CL) after 1991.
  • MaartenGr/BERTopic_Wikipedia : a model trained on 1000000 English Wikipedia pages.
  • davanstrien/imdb_bertopic : a model trained on the unsupervised split of the IMDB dataset

You can find a full overview of BERTopic models on the hub using the libraries filter

We invite you to explore the possibilities of this new integration and share your trained models on the hub!

Models mentioned in this article 4

Datasets mentioned in this article 2

More Articles from our Blog

Welcome fastai to the Hugging Face Hub

mmBERT: ModernBERT goes Multilingual

  • +2

Community

Image de l'article

reading through your blog on BERTopic integration with the Hugging Face Hub! The breakdown of topic modeling and model management was especially insightful.

While researching, I found this resource on Hugging Face model integration with RunPod, covering AI model setup, image generation, and diffusion workflows: https://mobisoftinfotech.com/resources/blog/flux-on-runpod-using-comfyui .

Would love to hear your thoughts on optimizing topic modeling for large-scale AI applications!

  • 1 reply

The process should be similar, especially considering you can download the model and run it through any API that you want. There are many options to choose from though, ranging from GPU-acceleration (e.g., cuML) or CPU-focused applications (e.g., Model2Vec).

· Sign up or log in to comment

Models mentioned in this article 4

Datasets mentioned in this article 2

Besoin d'un workflow n8n ou d'aide pour l'installer ?

Après la veille, passez à l'action : trouvez un template n8n ou un créateur capable de l'adapter à vos outils.

Source

Hugging Face Blog - huggingface.co

Voir la publication originale