BERTopic icon indicating copy to clipboard operation
BERTopic copied to clipboard

Different number of topics after training on the same dataset.

Open Nadiaghobadi opened this issue 4 years ago • 32 comments

Hi,

I noticed that if I train bertopic on a same dataset multiple times, the number of topics might range between 2-3 to 10-11. Sometimes we have a noise cluster and sometimes we don't. Do you recommend any approach to handle the randomness?

Thank you!

Nadiaghobadi avatar Feb 28 '22 19:02 Nadiaghobadi

Due to the stochastic nature of UMAP, results may differ between runs. You can set a random_state in UMAP but it might affect performance. You can find a bit more about that in the FAQ here.

MaartenGr avatar Mar 01 '22 08:03 MaartenGr

Thank you for the quick response @MaartenGr !

Nadiaghobadi avatar Mar 01 '22 16:03 Nadiaghobadi

Hi Maarten, sorry, but on the same issue. We just noticed that despite setting random_state to achieve reproducibility, we get different outcomes for the same data and same parameters set. Do any specifications in other model components affect the reproducibility? Here is our implementation:

# preprocess and clean data
my_stopwords = frozenset(list(["rt","RT", "&", "amp", "&amp", "http","https", "http://", "https://", "fav", "FAV"]))
vectorizer_model = CountVectorizer(ngram_range=(1, 2), stop_words = my_stopwords, min_df=20)

# do the BERT topic modelling
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)

min_clusters = round(len(alltweets) * 0.0017)
hdbscan_model = HDBSCAN(min_cluster_size= min_clusters, metric='euclidean', cluster_selection_method='eom', prediction_data=True, min_samples=5)

sentence_model = SentenceTransformer("all-mpnet-base-v2")
embeddings = sentence_model.encode(alltweets)

#run the model
topic_model = BERTopic(nr_topics = 'auto', umap_model=umap_model, hdbscan_model=hdbscan_model, embedding_model = sentence_model,vectorizer_model=vectorizer_model, low_memory=True, calculate_probabilities=True)

topics, probs = topic_model.fit_transform(alltweets, embeddings)

Run 1: 45 topics Run 2: 19 topics Run 3: 66 topics

Many thanks!

ViktoriaSpaiser avatar Mar 04 '22 08:03 ViktoriaSpaiser

@ViktoriaSpaiser I just tried your code out using the 20NewsGroup dataset and I cannot reproduce the issue you are having:

from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
from bertopic import BERTopic
from umap import UMAP
from hdbscan import HDBSCAN
from sklearn.feature_extraction.text import CountVectorizer

alltweets = fetch_20newsgroups(subset='all',  remove=('headers', 'footers', 'quotes'))['data']

# preprocess and clean data
my_stopwords = frozenset(list(["rt","RT", "&", "amp", "&amp", "http","https", "http://", "https://", "fav", "FAV"]))
vectorizer_model = CountVectorizer(ngram_range=(1, 2), stop_words = my_stopwords, min_df=20)

# do the BERT topic modelling
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)

min_clusters = round(len(alltweets) * 0.0017)
hdbscan_model = HDBSCAN(min_cluster_size= min_clusters, metric='euclidean', cluster_selection_method='eom', prediction_data=True, min_samples=5)

sentence_model = SentenceTransformer("all-mpnet-base-v2")
embeddings = sentence_model.encode(alltweets)

#run the model
topic_model = BERTopic(nr_topics = 'auto', umap_model=umap_model, hdbscan_model=hdbscan_model, embedding_model = sentence_model,vectorizer_model=vectorizer_model, low_memory=True, calculate_probabilities=True)

topics, probs = topic_model.fit_transform(alltweets, embeddings)

When I run the code above several times, I consistently get the exact same output. Do you perform any preprocessing steps in which there might be some randomness?

MaartenGr avatar Mar 07 '22 07:03 MaartenGr

Many thanks for your response Maarten, this is really strange, I wonder whether it's to do with the setup of my Python environment. And no, we don't do any preprocessing except for what is shown in "preprocess and clean data" step. We'll try to understand what is going on and report back for everyone.

ViktoriaSpaiser avatar Mar 07 '22 09:03 ViktoriaSpaiser

Hello, just a quick update. We are still not sure what happened. It seems we got different outcomes when doing it on different machines and we are still not sure why this happened. But, we are now able to reproduce the most recent result consistently. Many thanks again for your help Maarten.

ViktoriaSpaiser avatar Mar 21 '22 11:03 ViktoriaSpaiser

Thanks for the update! Good to hear that the results can now be reproduced consistently. If you ever run into any other issues, please let me know and I'll be glad to help out.

MaartenGr avatar Mar 22 '22 07:03 MaartenGr

@ViktoriaSpaiser I am experimenting with the variability of the results and am curious to learn if you found the root cause of variability which you observed.

dimitry12 avatar Jul 27 '22 18:07 dimitry12

Hi @dimitry12 No, unfortunately we never found the root cause of variability. Given this occurred only once when we run the the analysis on two different machines, it may have something to do with slightly different configurations of the environment. We did not encounter this problem again. Do you have an idea what the root cause is, did you encounter the problem?

ViktoriaSpaiser avatar Jul 28 '22 22:07 ViktoriaSpaiser

can you tell me how you came up with the formula for min_clusters ?

SaraAmd avatar Feb 01 '23 00:02 SaraAmd

@SaraAmd If you are trying to tune min_clusters you might try my TopicTuner. In my experience there is no calculation you can do to get the "right" number of min_clusters. As you probably know BERTopic takes min_clusters and uses that value for HDBSCAN min_cluster_size. In turn HDBSCAN, if not passed a different value for min_samples, will set min_samples to the same value. The relationship between a given reduction, min_sample_size and min_clusters is not linear so it can be difficult or impossible to predict the precise relationship between the two without running many tests. Testing multiple parameters through BERTopic involves quite a bit of overhead and in many cases will make a thorough parameter search impractical. TopicTuner is meant to make the process of determining the best min_sample_size and min_cluster_size as efficient and painless as possible. More on HDBSCAN tuning (which is what min_clusters is doing) here.

drob-xx avatar Feb 01 '23 02:02 drob-xx

I tried running it on Mac (M1 chip), but it gave a different result(topics) while running it multiple times. After transferring the same code to Windows (Intel chip), I get consistent results.

ashutoshraj avatar Apr 02 '23 04:04 ashutoshraj

Hi Maarten, sorry, but on the same issue. We just noticed that despite setting random_state to achieve reproducibility, we get different outcomes for the same data and same parameters set. Do any specifications in other model components affect the reproducibility? Here is our implementation:

# preprocess and clean data
my_stopwords = frozenset(list(["rt","RT", "&", "amp", "&amp", "http","https", "http://", "https://", "fav", "FAV"]))
vectorizer_model = CountVectorizer(ngram_range=(1, 2), stop_words = my_stopwords, min_df=20)

# do the BERT topic modelling
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)

min_clusters = round(len(alltweets) * 0.0017)
hdbscan_model = HDBSCAN(min_cluster_size= min_clusters, metric='euclidean', cluster_selection_method='eom', prediction_data=True, min_samples=5)

sentence_model = SentenceTransformer("all-mpnet-base-v2")
embeddings = sentence_model.encode(alltweets)

#run the model
topic_model = BERTopic(nr_topics = 'auto', umap_model=umap_model, hdbscan_model=hdbscan_model, embedding_model = sentence_model,vectorizer_model=vectorizer_model, low_memory=True, calculate_probabilities=True)

topics, probs = topic_model.fit_transform(alltweets, embeddings)

Run 1: 45 topics Run 2: 19 topics Run 3: 66 topics

Many thanks!

hey, I am working on the BERTopic model but am unsure how to initialize each of the parameters of the BERTopic. How do I decide the values of parameters of umap_model, vectorizer, hdbscan, and embedding_model I am working on a dataset of user reviews of size around 18k.

KethavathSaiYashwanth avatar Jun 21 '23 08:06 KethavathSaiYashwanth

@KethavathSaiYashwanth I would advise going through some of the tutorials in the documentation or the ones you will find at the top of the README for more information.

MaartenGr avatar Jun 21 '23 09:06 MaartenGr

@KethavathSaiYashwanth I would advise going through some of the tutorials in the documentation or the ones you will find at the top of the README for more information.

Thanks for the reply. I will go through them once. But if I am not required to do any fine-tuning parameters and just using the default BERTopic model is fine, how do I reproduce my results? I tried the following code random_seed_1 = 42 umap_model = umap.UMAP(random_state=random_seed_1) model = BERTopic(umap_model=umap_model) But still, I was getting different results every time I run the model. I do pre-processing but that gives the same data every time before fitting into the model.

KethavathSaiYashwanth avatar Jun 21 '23 09:06 KethavathSaiYashwanth

@KethavathSaiYashwanth Could you share your full code? It is difficult to say what is happening without seeing everything. Also, it might be worthwhile to use the parameters as listed here for better performance.

MaartenGr avatar Jun 21 '23 09:06 MaartenGr

@KethavathSaiYashwanth Could you share your full code? It is difficult to say what is happening without seeing everything. Also, it might be worthwhile to use the parameters as listed here for better performance.

Sorry but I cannot share the whole code, I will share the part where the problem lies

from bertopic import BERTopic import umap random_seed_1 = 42 random_seed_2 = 100 umap_model = umap.UMAP(random_state=random_seed_1) model = BERTopic(umap_model=umap_model) docs_i_train = negative_rows_i_train['Installer Verbatim Lemmatized'].tolist() topics, probs = model.fit_transform(docs_i_train) negative_rows_i_train['topic_Installer'] = topics negative_rows_i_train['probability_Installer'] = probs negative_rows_i_train model.get_topic_freq() model.get_topic_info()

The negative_rows_i_train is a pandas data frame with 14993 rows consisting of user reviews. through the model.get_topic_info(), it generated topics from -1 to 199. Next time I run it, the negative_rows_i_train was the same but the model gave a different number of topics and different names of topics.

KethavathSaiYashwanth avatar Jun 21 '23 10:06 KethavathSaiYashwanth

@KethavathSaiYashwanth Based on what you shared, this should be reproducible assuming you run it in the exact same environment with the same BERTopic version. Which version of BERTopic are you using? Also, could you try the following and see whether the results stay the same:

from bertopic import BERTopic
from umap import UMAP
from sklearn.datasets import fetch_20newsgroups

docs = fetch_20newsgroups(subset='all',  remove=('headers', 'footers', 'quotes'))['data']
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)
topic_model = BERTopic(umap_model=umap_model)
topics, probs = model.fit_transform(docs)

MaartenGr avatar Jun 21 '23 10:06 MaartenGr

@KethavathSaiYashwanth Based on what you shared, this should be reproducible assuming you run it in the exact same environment with the same BERTopic version. Which version of BERTopic are you using? Also, could you try the following and see whether the results stay the same:

from bertopic import BERTopic
from umap import UMAP
from sklearn.datasets import fetch_20newsgroups

docs = fetch_20newsgroups(subset='all',  remove=('headers', 'footers', 'quotes'))['data']
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)
topic_model = BERTopic(umap_model=umap_model)
topics, probs = model.fit_transform(docs)

Thank you. My bertopic model is reproducing results now and the version I have is 0.15.0. I will explore more about the parameters and try to improve my model.

KethavathSaiYashwanth avatar Jun 21 '23 11:06 KethavathSaiYashwanth

@MaartenGr Can you help me with another query? It is regarding guided topic modeling. I have a set of around 15 labels and I want to assign each text of my data(10k+ texts) to one of those labels. How should I use the BERTopic model?

KethavathSaiYashwanth avatar Jun 21 '23 15:06 KethavathSaiYashwanth