BERTopic icon indicating copy to clipboard operation
BERTopic copied to clipboard

get more than 3 representative docs from get_representative_docs()

Open studentdave opened this issue 4 years ago • 15 comments

is there a way to get N (more than 3) representative docs from get_representative_docs() ?

studentdave avatar Jun 02 '22 15:06 studentdave

The code explicitly saves only three documents:

                  representative_docs[topic] = list(np.random.choice(result, 3, replace=False).astype(int))

        # Convert indices to documents
        self.representative_docs = {topic: [documents.iloc[doc_id].Document for doc_id in doc_ids]
                                    for topic, doc_ids in
                                    representative_docs.items()}

What is your use case?

drob-xx avatar Jun 02 '22 16:06 drob-xx

ah. thx you. i'm first curious about how the "representative" doc are selected. and I would like to get more of them. i want like 20 of them. it helps with human review

studentdave avatar Jun 02 '22 16:06 studentdave

The representative documents are based on HDBSCAN's exemplar points. Essentially, those are points that best represent a density-based cluster. You can find a bit more about that here. I chose to only save three documents as it can quickly result in saving too much text in the model whenever you have millions of documents. Adding yet another parameter for increasing that value would make it a bit more difficult to use with the number of parameter to not only know about but also tweak.

Fortunately, the code of BERTopic is rather straightforward and you could adapt it to your use cases as such:

import numpy as np
import pandas as pd
import hdbscan
from bertopic import BERTopic

class BERTopicNew(BERTopic):
    def _save_representative_docs(self, documents: pd.DataFrame):
        """ Save the most representative docs (3) per topic
        The most representative docs are extracted by taking
        the exemplars from the HDBSCAN-generated clusters.
        Full instructions can be found here:
            https://hdbscan.readthedocs.io/en/latest/soft_clustering_explanation.html
        Arguments:
            documents: Dataframe with documents and their corresponding IDs
        """
        # Prepare the condensed tree and luf clusters beneath a given cluster
        condensed_tree = self.hdbscan_model.condensed_tree_
        raw_tree = condensed_tree._raw_tree
        clusters = sorted(condensed_tree._select_clusters())
        cluster_tree = raw_tree[raw_tree['child_size'] > 1]

        #  Find the points with maximum lambda value in each leaf
        representative_docs = {}
        for topic in documents['Topic'].unique():
            if topic != -1:
                leaves = hdbscan.plots._recurse_leaf_dfs(cluster_tree, clusters[topic])

                result = np.array([])
                for leaf in leaves:
                    max_lambda = raw_tree['lambda_val'][raw_tree['parent'] == leaf].max()
                    points = raw_tree['child'][(raw_tree['parent'] == leaf) & (raw_tree['lambda_val'] == max_lambda)]
                    result = np.hstack((result, points))
                
                # CHANGED THE VALUE OF 3 REPRESENTATIVE DOCS TO 20 HERE:
                representative_docs[topic] = list(np.random.choice(result, 20, replace=False).astype(int))

        # Convert indices to documents
        self.representative_docs = {topic: [documents.iloc[doc_id].Document for doc_id in doc_ids]
                                    for topic, doc_ids in
                                    representative_docs.items()}

Then, you can use that new class as follows instead of the original BERTopic:

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

Do note that each topic should have at least 20 documents for this to work.

MaartenGr avatar Jun 02 '22 19:06 MaartenGr

extremely helpful. much appreciated #teachingtofish

studentdave avatar Jun 03 '22 09:06 studentdave

The representative documents are based on HDBSCAN's exemplar points. Essentially, those are points that best represent a density-based cluster. You can find a bit more about that here. I chose to only save three documents as it can quickly result in saving too much text in the model whenever you have millions of documents. Adding yet another parameter for increasing that value would make it a bit more difficult to use with the number of parameter to not only know about but also tweak.

Fortunately, the code of BERTopic is rather straightforward and you could adapt it to your use cases as such:

import numpy as np
import pandas as pd
import hdbscan
from bertopic import BERTopic

class BERTopicNew(BERTopic):
    def _save_representative_docs(self, documents: pd.DataFrame):
        """ Save the most representative docs (3) per topic
        The most representative docs are extracted by taking
        the exemplars from the HDBSCAN-generated clusters.
        Full instructions can be found here:
            https://hdbscan.readthedocs.io/en/latest/soft_clustering_explanation.html
        Arguments:
            documents: Dataframe with documents and their corresponding IDs
        """
        # Prepare the condensed tree and luf clusters beneath a given cluster
        condensed_tree = self.hdbscan_model.condensed_tree_
        raw_tree = condensed_tree._raw_tree
        clusters = sorted(condensed_tree._select_clusters())
        cluster_tree = raw_tree[raw_tree['child_size'] > 1]

        #  Find the points with maximum lambda value in each leaf
        representative_docs = {}
        for topic in documents['Topic'].unique():
            if topic != -1:
                leaves = hdbscan.plots._recurse_leaf_dfs(cluster_tree, clusters[topic])

                result = np.array([])
                for leaf in leaves:
                    max_lambda = raw_tree['lambda_val'][raw_tree['parent'] == leaf].max()
                    points = raw_tree['child'][(raw_tree['parent'] == leaf) & (raw_tree['lambda_val'] == max_lambda)]
                    result = np.hstack((result, points))
                
                # CHANGED THE VALUE OF 3 REPRESENTATIVE DOCS TO 20 HERE:
                representative_docs[topic] = list(np.random.choice(result, 20, replace=False).astype(int))

        # Convert indices to documents
        self.representative_docs = {topic: [documents.iloc[doc_id].Document for doc_id in doc_ids]
                                    for topic, doc_ids in
                                    representative_docs.items()}

Then, you can use that new class as follows instead of the original BERTopic:

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

Do note that each topic should have at least 20 documents for this to work.

Something wrong with this code. The topic IDs are not matching with documents. Almost all documents are picked from topic 1 from my case.

fsysean avatar Jun 13 '22 06:06 fsysean

@fsysean Could you share your full code for running this? This seems to be working for me and a reproducible example would help greatly in understanding where things might go wrong.

MaartenGr avatar Jun 13 '22 08:06 MaartenGr

@fsysean Could you share your full code for running this? This seems to be working for me and a reproducible example would help greatly in understanding where things might go wrong.

import numpy as np
import pandas as pd
import hdbscan
from bertopic import BERTopic

class BERTopicNew(BERTopic):
    def _save_representative_docs(self, documents: pd.DataFrame):
        """ Save the most representative docs (3) per topic
        The most representative docs are extracted by taking
        the exemplars from the HDBSCAN-generated clusters.
        Full instructions can be found here:
            https://hdbscan.readthedocs.io/en/latest/soft_clustering_explanation.html
        Arguments:
            documents: Dataframe with documents and their corresponding IDs
        """
        # Prepare the condensed tree and luf clusters beneath a given cluster
        condensed_tree = self.hdbscan_model.condensed_tree_
        raw_tree = condensed_tree._raw_tree
        clusters = sorted(condensed_tree._select_clusters())
        cluster_tree = raw_tree[raw_tree['child_size'] > 1]

        #  Find the points with maximum lambda value in each leaf
        representative_docs = {}
        for topic in documents['Topic'].unique():
            if topic != -1:
                leaves = hdbscan.plots._recurse_leaf_dfs(cluster_tree, clusters[topic])

                result = np.array([])
                for leaf in leaves:
                    max_lambda = raw_tree['lambda_val'][raw_tree['parent'] == leaf].max()
                    points = raw_tree['child'][(raw_tree['parent'] == leaf) & (raw_tree['lambda_val'] == max_lambda)]
                    result = np.hstack((result, points))
                
                # CHANGED THE VALUE OF 3 REPRESENTATIVE DOCS TO 20 HERE:
                representative_docs[topic] = list(np.random.choice(result, 20, replace=False).astype(int))

        # Convert indices to documents
        self.representative_docs = {topic: [documents.iloc[doc_id].Document for doc_id in doc_ids]
                                    for topic, doc_ids in
                                    representative_docs.items()}

import pandas as pd
df=pd.read_csv('')

from sklearn.metrics import silhouette_score


from sentence_transformers import SentenceTransformer

from bertopic import BERTopic

from umap import UMAP
import numpy as np
import gensim.corpora as corpora
from gensim.models.coherencemodel import CoherenceModel
from hdbscan import HDBSCAN
from sklearn.feature_extraction.text import CountVectorizer

docs=df['Text'].to_list()

hdbscan_model = HDBSCAN(min_cluster_size=40, metric='euclidean', 
                        cluster_selection_method='eom', prediction_data=True, min_samples=2,cluster_selection_epsilon=0.2)
umap_model = UMAP(n_neighbors=15, n_components=5, min_dist=0.0, metric='cosine', random_state=42)


sentence_model = SentenceTransformer("all-mpnet-base-v2")
embeddings = sentence_model.encode(docs, show_progress_bar=False)


vectorizer_model = CountVectorizer(stop_words="english")





topic_model = BERTopicNew(diversity=0.25,umap_model=umap_model,hdbscan_model=hdbscan_model,top_n_words=10,n_gram_range=(1, 2),vectorizer_model=vectorizer_model).fit(docs)
topics, probs  = topic_model.fit_transform(docs,embeddings)

dfrepresentative = pd.DataFrame.from_dict(topic_model.get_representative_docs())
display(dfrepresentative)

fsysean avatar Jun 13 '22 09:06 fsysean

In your function, you has a code

clusters = sorted(condensed_tree._select_clusters())

and in the following topic loop, you has a code

leaves = hdbscan.plots._recurse_leaf_dfs(cluster_tree, clusters[topic])

Then, I have a question. Does those codes mean that cluster id = topic id?

Why don't you use leaves = hdbscan.plots._recurse_leaf_dfs(cluster_tree, topic)

If cluster id != topic id, why did you sort condensed_tree._select_clusters()?

And how did you define the relation between cluster id and topic id(label)?

Thank you!

I wrote a print function on topic Id and clusters.

clusters: [16957.0, 16959.0, 16965.0, 16966.0, 16967.0, 16970.0, 16975.0, 16976.0, 16981.0, 16983.0, 16985.0, 16986.0, 16987.0, 16988.0, 17000.0, 17001.0, 17003.0, 17005.0, 17006.0, 17007.0, 17008.0, 17011.0, 17017.0, 17020.0, 17021.0, 17023.0, 17025.0, 17027.0, 17033.0, 17034.0, 17035.0, 17037.0, 17039.0, 17041.0, 17043.0, 17051.0, 17053.0, 17054.0, 17055.0, 17059.0, 17060.0, 17061.0, 17063.0, 17065.0, 17067.0, 17068.0, 17069.0, 17075.0, 17077.0, 17085.0, 17087.0, 17088.0, 17091.0, 17093.0, 17095.0, 17096.0, 17099.0, 17100.0, 17101.0, 17104.0, 17105.0, 17106.0, 17109.0, 17111.0, 17115.0, 17117.0, 17118.0, 17119.0, 17120.0]

But I only got 17 topics. After generating those clusters, they must merge again to 17 clusters.

fsysean avatar Jun 13 '22 09:06 fsysean

@fsysean After some testing it seems to be related to the cluster_selection_epsilon that you set in your custom HDBSCAN model. Removing that parameter in its entirety resolves the issue. With respect to the questions above, I would highly advise reading through the examples here on the HDBSCAN library as it does a much better job at explaining extracting exemplars than I could.

MaartenGr avatar Jun 13 '22 13:06 MaartenGr

@fsysean After some testing it seems to be related to the cluster_selection_epsilon that you set in your custom HDBSCAN model. Removing that parameter in its entirety resolves the issue. With respect to the questions above, I would highly advise reading through the examples here on the HDBSCAN library as it does a much better job at explaining extracting exemplars than I could.

Thank you so much!

fsysean avatar Jun 14 '22 13:06 fsysean

The representative documents are based on HDBSCAN's exemplar points. Essentially, those are points that best represent a density-based cluster. You can find a bit more about that here. I chose to only save three documents as it can quickly result in saving too much text in the model whenever you have millions of documents. Adding yet another parameter for increasing that value would make it a bit more difficult to use with the number of parameter to not only know about but also tweak.

Fortunately, the code of BERTopic is rather straightforward and you could adapt it to your use cases as such:

import numpy as np
import pandas as pd
import hdbscan
from bertopic import BERTopic

class BERTopicNew(BERTopic):
    def _save_representative_docs(self, documents: pd.DataFrame):
        """ Save the most representative docs (3) per topic
        The most representative docs are extracted by taking
        the exemplars from the HDBSCAN-generated clusters.
        Full instructions can be found here:
            https://hdbscan.readthedocs.io/en/latest/soft_clustering_explanation.html
        Arguments:
            documents: Dataframe with documents and their corresponding IDs
        """
        # Prepare the condensed tree and luf clusters beneath a given cluster
        condensed_tree = self.hdbscan_model.condensed_tree_
        raw_tree = condensed_tree._raw_tree
        clusters = sorted(condensed_tree._select_clusters())
        cluster_tree = raw_tree[raw_tree['child_size'] > 1]

        #  Find the points with maximum lambda value in each leaf
        representative_docs = {}
        for topic in documents['Topic'].unique():
            if topic != -1:
                leaves = hdbscan.plots._recurse_leaf_dfs(cluster_tree, clusters[topic])

                result = np.array([])
                for leaf in leaves:
                    max_lambda = raw_tree['lambda_val'][raw_tree['parent'] == leaf].max()
                    points = raw_tree['child'][(raw_tree['parent'] == leaf) & (raw_tree['lambda_val'] == max_lambda)]
                    result = np.hstack((result, points))
                
                # CHANGED THE VALUE OF 3 REPRESENTATIVE DOCS TO 20 HERE:
                representative_docs[topic] = list(np.random.choice(result, 20, replace=False).astype(int))

        # Convert indices to documents
        self.representative_docs = {topic: [documents.iloc[doc_id].Document for doc_id in doc_ids]
                                    for topic, doc_ids in
                                    representative_docs.items()}

Then, you can use that new class as follows instead of the original BERTopic:

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

Do note that each topic should have at least 20 documents for this to work.

I have tried the code, but the output of "representative_docs" is NAN. It is so strange. I just modify "representative_docs[topic] = list(np.random.choice(result, 20, replace=False).astype(int))" to "representative_docs[topic] = list(np.random.choice(result, 5, replace=False).astype(int))"

peiwenT6 avatar Nov 15 '24 04:11 peiwenT6

@peiwenT6 You're right! This was on an older version of BERTopic. You can now run it as such:

import numpy as np
import pandas as pd
import hdbscan
from bertopic import BERTopic

class BERTopicNew(BERTopic):
    def _save_representative_docs(self, documents: pd.DataFrame):
        """Save the 3 most representative docs per topic.

        Arguments:
            documents: Dataframe with documents and their corresponding IDs

        Updates:
            self.representative_docs_: Populate each topic with 3 representative docs
        """
        repr_docs, _, _, _ = self._extract_representative_docs(
            self.c_tf_idf_,
            documents,
            self.topic_representations_,
            nr_samples=500,
            nr_repr_docs=20, # CHANGE THIS VALUE
        )
        self.representative_docs_ = repr_docs

Note that whenever you change private functions, it cannot be guaranteed to work across versions. I'm using this example for the current latest version, v0.16.4.

MaartenGr avatar Nov 15 '24 12:11 MaartenGr

@peiwenT6 You're right! This was on an older version of BERTopic. You can now run it as such:

import numpy as np
import pandas as pd
import hdbscan
from bertopic import BERTopic

class BERTopicNew(BERTopic):
    def _save_representative_docs(self, documents: pd.DataFrame):
        """Save the 3 most representative docs per topic.

        Arguments:
            documents: Dataframe with documents and their corresponding IDs

        Updates:
            self.representative_docs_: Populate each topic with 3 representative docs
        """
        repr_docs, _, _, _ = self._extract_representative_docs(
            self.c_tf_idf_,
            documents,
            self.topic_representations_,
            nr_samples=500,
            nr_repr_docs=20, # CHANGE THIS VALUE
        )
        self.representative_docs_ = repr_docs

Note that whenever you change private functions, it cannot be guaranteed to work across versions. I'm using this example for the current latest version, v0.16.4.

Thank you so much for your quick response! But my bertopic model version is 0.15.0. I have tried the above code, unfortunately it does not work for me. I want to know how can I modify the code to adapt to my current version? I am so sorry for my poor programming foundation.

peiwenT6 avatar Nov 15 '24 12:11 peiwenT6

@peiwenT6 Couldn't you use v0.16.4 instead? Since you are training, you can easily switch over right?

MaartenGr avatar Nov 15 '24 14:11 MaartenGr

@peiwenT6 Couldn't you use v0.16.4 instead? Since you are training, you can easily switch over right?

Sure! I apologize for not considering this matter more carefully. Thank you very much for your kind help!

peiwenT6 avatar Nov 16 '24 04:11 peiwenT6