Issue with _extract_words_per_topic
Hi @MaartenGr,
I'm trying to get the top 30 words for each topic (even though the model is trained to represent only the top 10) so that I can make a word cloud for each topic to give a little more context to some of the most frequent words (hope that makes sense). I tried using ._extract_words_per_topic(words) and got the error 'BERTopic' object has no attribute 'c_tf_idf'.
I then changed line 1664 in _bertopic.py from c_tf_idf = self.c_tf_idf to c_tf_idf = self._c_tf_idf, which solved the initial error, but then I get the error 'function' object has no attribute 'indptr' (line 1906 of _bertopic.py). I'm not an expert programmer so I'm hesitant to change too much. Am I following the right approach to get more top words than initially specified in the model, or is there another way I'm missing?
Kind regards, Francesca
I tried using ._extract_words_per_topic(words) and got the error 'BERTopic' object has no attribute 'c_tf_idf'.
That error only happens if you did not fit the model before executing ._extract_words_per_topic(words) since the attribute c_tf_idf is generated when fitting the model.
I then changed line 1664 in _bertopic.py from c_tf_idf = self.c_tf_idf to c_tf_idf = self._c_tf_idf, which solved the initial error, but then I get the error 'function' object has no attribute 'indptr' (line 1906 of _bertopic.py).
The line that you changed was already correct. What you did was setting that variable to an internal function which is not the behavior that we are looking for.
Am I following the right approach to get more top words than initially specified in the model, or is there another way I'm missing?
Yes, you can approach it as follows. First, let's train our model without making any changes to the parameters and therefore only selecting the top 10 words per topic:
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)
We can check the number of words per topic with topic_model.get_topic(0) and we can indeed see that it only has 10 words. To change this value, you need to change the top_n_words attribute in BERTopic and then update the topic representations:
# Indicate that we want the top 30 words per topic
topic_model.top_n_words = 30
# Update our topic representation
# Note that if you used a custom CountVectorizer when training the model, you will
# also need to pass it to this function
topic_model.update_topics(docs, topics)
Now, when we run topic_model.get_topic(0), we can see the top 30 words instead. Do note that I am using BERTopic v0.10.0 here and it might be different for older versions. Also, the top n words is currently capped at 30 to make it easier to work with MMR but this might be changed in the future.
Oh I see! Thank you, this works perfectly.