Skip to content

Topic deletion fails if topics have custom lables#2529

Description

@aymanmh

Have you searched existing issues? 馃攷

  • I have searched and found no existing issues

Describe the bug

If the model has custom labels set, topic deletion fails with error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[10], line 1
----> 1 topic_model.delete_topics([2])

File ~/miniconda3/envs/tgram/lib/python3.13/site-packages/bertopic/_bertopic.py:2275, in BERTopic.delete_topics(self, topics_to_delete)
   2271 # Update custom labels if they exist
   2272 if hasattr(self, "custom_labels_") and self.custom_labels_ is not None:
   2273     new_labels = {
   2274         (final_mapping[old_topic] if old_topic != -1 else -1): label
-> 2275         for old_topic, label in self.custom_labels_.items()
   2276         if old_topic not in topics_to_delete
   2277     }
   2278     self.custom_labels_ = new_labels
   2280 # Update topic representations

AttributeError: 'list' object has no attribute 'items'

The delete topics function expects custom_labels_ to be a dictionary, but its a list, I can see in other places in the code it does check for the object type (list or dict) and handles it accordingly, but not here.

Reproduction

from bertopic import BERTopic

from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(subset='all',  remove=('headers', 'footers', 'quotes'))['data']

topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)

topic_model.delete_topics([2]) # works fine

#set custom labels
topic_labels = topic_model.generate_topic_labels(nr_words=3, topic_prefix=True,word_length=8,separator=" - ")
topic_model.set_topic_labels(topic_labels)

topic_model.delete_topics([2]) # deletion fails with the error shown above

BERTopic Version

0.17.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions