BERTopic icon indicating copy to clipboard operation
BERTopic copied to clipboard

Bertopic using Online Learning and partial_fit

Open noskimusprime opened this issue 3 years ago • 12 comments

I am using .partial_fit() to train my bertopic model in a loop function. However, after running the training function I set up, the model does not return any visualizations when running model.visualize_barchart(). Also when I try model.fit_transform() after training the model, it yields: AttributeError: 'NoneType' object has no attribute 'fit_transform'. I would be really glad if you could provide help.

All the best and thank you in advance!

checkpoint, model = load_checkpoint() 

model = BERTopic(verbose=True, umap_model=umap_model, hdbscan_model=cluster_model, vectorizer_model=vectorizer_model)
for i, x in enumerate(df_splits):` 
    
    if checkpoint is not None:  
        if checkpoint >= i:  
            print(f'Skipping iteration {i}/{len(df_splits)}') 
            continue
        else:
            print(f'Running iteration {i}/{len(df_splits)}')
    else:
        print(f'Running iteration {i}/{len(df_splits)}') # das haben wir hier ein weiteres Mal, denn es gilt ja sowohl für höhere Iterationen als auch wenn wir bei null anfangen

    model.partial_fit(x) #Fit BERTopic on a subset of the data and perform online learning with batch-like data
    save_checkpoint(model, i)  # Funktion ist weiter unten definiert
    checkpoint = i # Aktuelle Iteration wird als neuer Checkpoint abgespeichert

print('done')

return model`

noskimusprime avatar Mar 02 '23 15:03 noskimusprime

Most likely, something is happening within save_checkpoint that changes the model. Could you also share that code?

MaartenGr avatar Mar 03 '23 04:03 MaartenGr

Hi Maarten,

thank you so much for your reply. I use the code shown underneath for the checkpoints. image

Also, I realized that the part of the code, which opens the function is missing above, however, there I only split the corpus into 10 percent shares of itself using np.array_split.

noskimusprime avatar Mar 03 '23 09:03 noskimusprime

Based on your code, I would think that there is something going on with your load_checkpoint function that returns None for model since the error is AttributeError: 'NoneType' object has no attribute 'fit_transform'. Based on this, it would seem that you are not assigning BERTopic to the model parameter.

MaartenGr avatar Mar 05 '23 06:03 MaartenGr

Hi Maarten, thank you for your feedback. I also tried to run the model with a small share of the dataset however to avoid OnlineLearning and not use the checkpoint approach. However, also here, the model.visualize functions are not working. The following code still yields nothing, although I installed plotly and tried to write it with fig = model.visualize_barchart(); fig.show().

model = BERTopic(verbose=True, language="multilingual", calculate_probabilities=True) model.fit(preprocessed_texts) topics, probabilities= model.fit_transform(preprocessed_texts) fig=model.visualize_barchart() fig.show()

noskimusprime avatar Mar 07 '23 10:03 noskimusprime

Based on your code, it suffices to only run model.fit and there is no need to then also run model.fit_transform as you are essentially doing the same twice.

With respect to the visualization, you might have to make sure plotly works in a jupyter environment. You can find more about that here.

MaartenGr avatar Mar 09 '23 12:03 MaartenGr

Dear Maarten, thank you for your feedback. However, how do I user BERT then to first train the model and then make predictions based on the trained model? I thought this is what first partial_fit() and then model.fit_transform does?

noskimusprime avatar Mar 09 '23 15:03 noskimusprime

You might notice the word fit being in both .partial_fit and in .fit_transform. This means that the model is fitted, and thereby trained, in both functions. If you want to only predict unseen documents, without re-training, you would need to use the .transform function.

MaartenGr avatar Mar 10 '23 06:03 MaartenGr

Hi MaartenGr , I had a similiar issue. Let me explain:

1 - I run a process to partial_fit ( a brand new model ) with 300 documents ( for example ) 2- save the model to a file 3 - load a model ( it worked ) 4 - get more 200 documents ( for example the number is important ) 5- partial_fit then (. using also a trick to keep tracking of older topics mentioned at documentation about dynamicaly modeling) 6 - when a try to get hieararchical_topics , it not works.

The point here is: In the first iteraction , I had 300 documents, but they are not available anymore at this running. only have 200 other documents for the second iteraction. BUT, looking inside the code. look what I have found:

876 # Calculate basic bag-of-words to be iteratively merged later --> 877 documents = **pd.DataFrame({"Document": docs, 878 "ID": range(len(docs)), 879 "Topic": self.topics_})** 880 documents_per_topic = documents.groupby(['Topic'], as_index=False).agg({'Document': ' '.join}) 881 documents_per_topic = documents_per_topic.loc[documents_per_topic.Topic != -1, :]

so the error is : ValueError: All arrays must be of the same length

but why docs fitted must be all docs fitted EVER? in an incremental approach?

Maybe I'm missing something, maybe not. More info about the code.

loading topic_model = BERTopic.load(prop['training']['import_model_file']) final_topics = topic_model.topics_

fitting `for docx in doc_chunks: print("chunk fit start") topic_model.partial_fit(docx) print("chunk fit end") print("QTD TOPICOS DO CHUNK ", len(topic_model.get_topics())) final_topics.extend(topic_model.topics_)

topic_model.topics_ = final_topics` using the warning at : https://maartengr.github.io/BERTopic/getting_started/online/online.html

print("_topics : ", len(topic_model.topics_), " get_topics(): ", len(topic_model.get_topics())) _topics : 146 get_topics(): 70

and the size of all documents in the chuncks are 90 .

What do you think?

guilharj avatar Mar 15 '23 15:03 guilharj

@guilharj

but why docs fitted must be all docs fitted EVER? in an incremental approach?

The reason for needing all documents in hierarchical topic modeling is two-fold. First, although there is a .partial_fit method for training BERTopic, hierarchical topic modeling is not an online-learning approach, only .partial_fit is. Second, the reason why hierarchical topic modeling is not online since we make calculate the c-TF-IDF representations based on the documents themselves at different levels of hierarchy. So if we do not have all documents, then it is not possible to perform some hierarchical analyses unless we want to merge c-TF-IDF values, which tends to be rather instable and ignores any weighting with respect to the sizes of the topics. Moreover, this would also prevent the usage of many/most bertopic.representation_model to be used.

MaartenGr avatar Mar 16 '23 10:03 MaartenGr

I got it! What do you think about making a different approach? Maybe if we use only representative docs per topic do calculate de c-TF-IDF. So I can reduce the number of docs a have to store to create this view. If you think that it's possible to online modeling hierarchical, I could try something like it.

The reason that I asked for it, is that I wanna suggest a topic relation to the user so they can understand the meaning of something. and eventually look only to a hi level "topic".

And also bc I have several documents , and new documents every day, so online approach appears to be bettter.

Tell me what do you think about the idea of using representative docs only.

guilharj avatar Mar 16 '23 11:03 guilharj

Using representative documents per topic is typically not sufficient to calculate the c-TF-IDF as you will not have sufficient data to properly calculate the IDF values. Instead, you could use the Bag-of-Words to mimic the documents so that they do not need to be passed. More specifically, topic_model.vectorizer_model.X_ contains the counts for each word across each topic. So if you were to transform those raw counts to text, you could pass that to .hierarchical_topics.

MaartenGr avatar Mar 19 '23 05:03 MaartenGr

Due to inactivity, I'll be closing this issue. Let me know if you want me to re-open the issue!

MaartenGr avatar May 23 '23 09:05 MaartenGr