MaartenGr / MaartenGr/BERTopic
Topic deletion fails if topics have custom lables
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7.8k
- Forks
- 920
- Avg merge
- 22h 24m
- Merged PRs (30d)
- 5
Description
### Have you searched existing issues? 🔎
- [x] 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
```python
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in bertopic/_bertopic.py at the delete_topics method around line 2275, then compare how other code handles custom_labels_ as a list or dictionary. Reproduce the failure with the provided BERTopic example and verify that deleting a topic after set_topic_labels succeeds for list-based labels.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- machine-learning
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Active
- Clarity
- Clearly specified
- Newbie friendliness
- 84/100