Upload 255 files
Browse filesFiles changed (7)
80 unmodified lines81828380 unmodified lines.idea/.vscode.DS_Store80 unmodified lines81828384858680 unmodified lines.idea/.vscode.DS_Store# mkdocssite/
157 unmodified lines158159160161162163164156 unmodified lines321322323324325326327371 unmodified lines699700701702703704705706707708117 unmodified lines8268278288298308318322 unmodified lines83583683783883984084190 unmodified lines932933934935936937938939127 unmodified lines1067106810691070107110721073903 unmodified lines19771978197919801981198219831984479 unmodified lines2464246524662467246824692470793 unmodified lines326432653266326732683269327024 unmodified lines3295329632973298329933003301167 unmodified lines346934703471347234733474347544 unmodified lines352035213522352335243525352678 unmodified lines3605360636073608360936103611361236133614361536163617361836193620203 unmodified lines382438253826382738283829383038313832174 unmodified lines4007400840094010401140124013112 unmodified lines4126412741284129413041314132413343 unmodified lines41774178417941804181418241834184294 unmodified lines4479448044814482448344844485448644874488157 unmodified linesNOTE: This param will not be used if you pass in your ownCountVectorizer.min_topic_size: The minimum size of the topic. Increasing this value will leadto a lower number of clusters/topics and vice versa.It is the same parameter as `min_cluster_size` in HDBSCAN.NOTE: This param will not be used if you are using `hdbscan_model`.nr_topics: Specifying the number of topics will reduce the initial156 unmodified linesembeddings: np.ndarray = None,images: List[str] = None,y: Union[List[int], np.ndarray] = None) -> Tuple[List[int],Union[np.ndarray, None]]:""" Fit the models on a collection of documents, generate topics,and return the probabilities and topic per document.371 unmodified linesdef topics_over_time(self,docs: List[str],timestamps: Union[List[str],List[int]],topics: List[int] = None,nr_bins: int = None,datetime_format: str = None,evolution_tuning: bool = True,global_tuning: bool = True) -> pd.DataFrame:117 unmodified lines# Fill dataframe with resultstopics_at_timestamp = [(topic,", ".join([words[0] for words in values][:5]),topic_frequency[topic],timestamp) for topic, values in words_per_topic.items()]topics_over_time.extend(topics_at_timestamp)2 unmodified linesprevious_topics = sorted(list(documents_per_topic.Topic.values))previous_c_tf_idf = c_tf_idf.copy()return pd.DataFrame(topics_over_time, columns=["Topic", "Words", "Frequency", "Timestamp"])def topics_per_class(self,docs: List[str],90 unmodified lines`lambda x: sch.linkage(x, 'ward', optimal_ordering=True)`distance_function: The distance function to use on the c-TF-IDF matrix. Default is:`lambda x: 1 - cosine_similarity(x)`.You can pass any function that returns either a square matrix ofshape (n_samples, n_samples) with zeros on the diagonal andnon-negative values or condensed distance matrix of shape(n_samples * (n_samples - 1) / 2,) containing the uppertriangular of the distance matrix.127 unmodified linesuse_embedding_model: bool = False,calculate_tokens: bool = False,separator: str = " ") -> Tuple[np.ndarray,Union[List[np.ndarray], None]]:""" A post-hoc approximation of topic distributions across documents.In order to perform this approximation, each document is split into tokens903 unmodified linesfor key, val in sorted(mapping.items()):mappings[val].append(key)mappings = {topic_from:{"topics_to": topics_to,"topic_sizes": [self.topic_sizes_[topic] for topic in topics_to]}for topic_from, topics_to in mappings.items()}# Update topics479 unmodified linesspecific points. Helps to speed up generation of visualizations.nr_levels: The number of levels to be visualized in the hierarchy. First, the distancesin `hierarchical_topics.Distance` are split in `nr_levels` lists of distances withequal length. Then, for each list of distances, the merged topics, that havea distance less or equal to the maximum distance of the selected list of distances, are selected.NOTE: To get all possible merged steps, make sure that `nr_levels` is equal tothe length of `hierarchical_topics`.793 unmodified linessims = np.max(sim_matrix, axis=1)to_merge = {a - selected_topics["_outliers"]:b - merged_topics["_outliers"] for a, (b, val) in enumerate(zip(sims_idx, sims))if val >= min_similarity}to_merge.update(new_topics_dict)24 unmodified linesserialization: str = "safetensors",save_embedding_model: Union[str, bool] = True,save_ctfidf: bool = False,):""" Push your BERTopic model to a HuggingFace HubWhenever you want to upload files to the Hub, you need to log in to your HuggingFace account:167 unmodified linesdocuments: pd.DataFrame,partial_fit: bool = False,y: np.ndarray = None) -> Tuple[pd.DataFrame,np.ndarray]:""" Cluster UMAP embeddings with HDBSCANArguments:44 unmodified linesreturn documents, probabilitiesdef _zeroshot_topic_modeling(self, documents: pd.DataFrame, embeddings: np.ndarray) -> Tuple[pd.DataFrame, np.array,pd.DataFrame, np.array]:""" Find documents that could be assigned to either one of the topics in self.zeroshot_topic_listWe transform the topics in `self.zeroshot_topic_list` to embeddings and78 unmodified linesempty_dimensionality_model = BaseDimensionalityReduction()empty_cluster_model = BaseCluster()zeroshot_model = BERTopic(n_gram_range=self.n_gram_range,low_memory=self.low_memory,calculate_probabilities=self.calculate_probabilities,embedding_model=self.embedding_model,umap_model=empty_dimensionality_model,hdbscan_model=empty_cluster_model,vectorizer_model=self.vectorizer_model,ctfidf_model=self.ctfidf_model,representation_model=self.representation_model,verbose=self.verbose).fit(docs, embeddings=embeddings, y=y)logger.info("Zeroshot Step 2 - Completed \u2713")logger.info("Zeroshot Step 3 - Combining clustered topics with the zeroshot model")203 unmodified lines# Sample documents per topicdocuments_per_topic = (documents.drop("Image", axis=1, errors="ignore").groupby('Topic').sample(n=nr_samples, replace=True, random_state=42).drop_duplicates())# Find and extract documents that are most similar to the topic174 unmodified linesdocuments: pd.DataFrame,c_tf_idf: csr_matrix = None,calculate_aspects: bool = True) -> Mapping[str,List[Tuple[str, float]]]:""" Based on tf_idf scores per topic, extract the top n words per topicIf the top words per topic need to be extracted, then only the `words` parameter112 unmodified linesfor key, val in sorted(mapped_topics.items()):mappings[val].append(key)mappings = {topic_from:{"topics_to": topics_to,"topic_sizes": [self.topic_sizes_[topic] for topic in topics_to]}for topic_from, topics_to in mappings.items()}# Map topics43 unmodified linesfor key, val in sorted(mapped_topics.items()):mappings[val].append(key)mappings = {topic_from:{"topics_to": topics_to,"topic_sizes": [self.topic_sizes_[topic] for topic in topics_to]}for topic_from, topics_to in mappings.items()}# Update documents and topics294 unmodified lines# Fit BERTopic without actually performing any clusteringtopic_model = BERTopic(embedding_model=embedding_model,umap_model=empty_dimensionality_model,hdbscan_model=empty_cluster_model,**params)topic_model.topic_embeddings_ = tensors["topic_embeddings"].numpy()topic_model.topic_representations_ = {int(key): val for key, val in topics["topic_representations"].items()}157 unmodified lines158159160161162163164156 unmodified lines321322323324325326327371 unmodified lines699700701702703704705706707708709117 unmodified lines8278288298308318328338342 unmodified lines83783883984084184284390 unmodified lines934935936937938939940941127 unmodified lines1069107010711072107310741075903 unmodified lines19791980198119821983198419851986479 unmodified lines2466246724682469247024712472793 unmodified lines326632673268326932703271327224 unmodified lines3297329832993300330133023303167 unmodified lines347134723473347434753476347744 unmodified lines352235233524352535263527352878 unmodified lines3607360836093610361136123613361436153616361736183619362036213622203 unmodified lines382638273828382938303831383238333834174 unmodified lines4009401040114012401340144015112 unmodified lines4128412941304131413241334134413543 unmodified lines41794180418141824183418441854186294 unmodified lines4481448244834484448544864487448844894490157 unmodified linesNOTE: This param will not be used if you pass in your ownCountVectorizer.min_topic_size: The minimum size of the topic. Increasing this value will leadto a lower number of clusters/topics and vice versa.It is the same parameter as `min_cluster_size` in HDBSCAN.NOTE: This param will not be used if you are using `hdbscan_model`.nr_topics: Specifying the number of topics will reduce the initial156 unmodified linesembeddings: np.ndarray = None,images: List[str] = None,y: Union[List[int], np.ndarray] = None) -> Tuple[List[int],Union[np.ndarray, None]]:""" Fit the models on a collection of documents, generate topics,and return the probabilities and topic per document.371 unmodified linesdef topics_over_time(self,docs: List[str],timestamps: Union[List[str]],topics: List[int] = None,n_topics: int = 5,nr_bins: int = None,n_keywords: int = 5,datetime_format: str = None,evolution_tuning: bool = True,global_tuning: bool = True) -> pd.DataFrame:117 unmodified lines# Fill dataframe with resultstopics_at_timestamp = [(topic,", ".join([words[0] for words in values][:n_topics]),[words[1] for weights in values][:n_topics],topic_frequency[topic],timestamp) for topic, values in words_per_topic.items()]topics_over_time.extend(topics_at_timestamp)2 unmodified linesprevious_topics = sorted(list(documents_per_topic.Topic.values))previous_c_tf_idf = c_tf_idf.copy()return pd.DataFrame(topics_over_time, columns=["Topic", "Words", "Weight", "Frequency", "Timestamp"])def topics_per_class(self,docs: List[str],90 unmodified lines`lambda x: sch.linkage(x, 'ward', optimal_ordering=True)`distance_function: The distance function to use on the c-TF-IDF matrix. Default is:`lambda x: 1 - cosine_similarity(x)`.You can pass any function that returns either a square matrix ofshape (n_samples, n_samples) with zeros on the diagonal andnon-negative values or condensed distance matrix of shape(n_samples * (n_samples - 1) / 2,) containing the uppertriangular of the distance matrix.127 unmodified linesuse_embedding_model: bool = False,calculate_tokens: bool = False,separator: str = " ") -> Tuple[np.ndarray,Union[List[np.ndarray], None]]:""" A post-hoc approximation of topic distributions across documents.In order to perform this approximation, each document is split into tokens903 unmodified linesfor key, val in sorted(mapping.items()):mappings[val].append(key)mappings = {topic_from:{"topics_to": topics_to,"topic_sizes": [self.topic_sizes_[topic] for topic in topics_to]}for topic_from, topics_to in mappings.items()}# Update topics479 unmodified linesspecific points. Helps to speed up generation of visualizations.nr_levels: The number of levels to be visualized in the hierarchy. First, the distancesin `hierarchical_topics.Distance` are split in `nr_levels` lists of distances withequal length. Then, for each list of distances, the merged topics, that havea distance less or equal to the maximum distance of the selected list of distances, are selected.NOTE: To get all possible merged steps, make sure that `nr_levels` is equal tothe length of `hierarchical_topics`.793 unmodified linessims = np.max(sim_matrix, axis=1)to_merge = {a - selected_topics["_outliers"]:b - merged_topics["_outliers"] for a, (b, val) in enumerate(zip(sims_idx, sims))if val >= min_similarity}to_merge.update(new_topics_dict)24 unmodified linesserialization: str = "safetensors",save_embedding_model: Union[str, bool] = True,save_ctfidf: bool = False,):""" Push your BERTopic model to a HuggingFace HubWhenever you want to upload files to the Hub, you need to log in to your HuggingFace account:167 unmodified linesdocuments: pd.DataFrame,partial_fit: bool = False,y: np.ndarray = None) -> Tuple[pd.DataFrame,np.ndarray]:""" Cluster UMAP embeddings with HDBSCANArguments:44 unmodified linesreturn documents, probabilitiesdef _zeroshot_topic_modeling(self, documents: pd.DataFrame, embeddings: np.ndarray) -> Tuple[pd.DataFrame, np.array,pd.DataFrame, np.array]:""" Find documents that could be assigned to either one of the topics in self.zeroshot_topic_listWe transform the topics in `self.zeroshot_topic_list` to embeddings and78 unmodified linesempty_dimensionality_model = BaseDimensionalityReduction()empty_cluster_model = BaseCluster()zeroshot_model = BERTopic(n_gram_range=self.n_gram_range,low_memory=self.low_memory,calculate_probabilities=self.calculate_probabilities,embedding_model=self.embedding_model,umap_model=empty_dimensionality_model,hdbscan_model=empty_cluster_model,vectorizer_model=self.vectorizer_model,ctfidf_model=self.ctfidf_model,representation_model=self.representation_model,verbose=self.verbose).fit(docs, embeddings=embeddings, y=y)logger.info("Zeroshot Step 2 - Completed \u2713")logger.info("Zeroshot Step 3 - Combining clustered topics with the zeroshot model")203 unmodified lines# Sample documents per topicdocuments_per_topic = (documents.drop("Image", axis=1, errors="ignore").groupby('Topic').sample(n=nr_samples, replace=True, random_state=42).drop_duplicates())# Find and extract documents that are most similar to the topic174 unmodified linesdocuments: pd.DataFrame,c_tf_idf: csr_matrix = None,calculate_aspects: bool = True) -> Mapping[str,List[Tuple[str, float]]]:""" Based on tf_idf scores per topic, extract the top n words per topicIf the top words per topic need to be extracted, then only the `words` parameter112 unmodified linesfor key, val in sorted(mapped_topics.items()):mappings[val].append(key)mappings = {topic_from:{"topics_to": topics_to,"topic_sizes": [self.topic_sizes_[topic] for topic in topics_to]}for topic_from, topics_to in mappings.items()}# Map topics43 unmodified linesfor key, val in sorted(mapped_topics.items()):mappings[val].append(key)mappings = {topic_from:{"topics_to": topics_to,"topic_sizes": [self.topic_sizes_[topic] for topic in topics_to]}for topic_from, topics_to in mappings.items()}# Update documents and topics294 unmodified lines# Fit BERTopic without actually performing any clusteringtopic_model = BERTopic(embedding_model=embedding_model,umap_model=empty_dimensionality_model,hdbscan_model=empty_cluster_model,**params)topic_model.topic_embeddings_ = tensors["topic_embeddings"].numpy()topic_model.topic_representations_ = {int(key): val for key, val in topics["topic_representations"].items()}
123# `Document Data Map`::: bertopic.plotting._datamap.visualize_document_datamap123# `Documents with DataMapPlot`::: bertopic.plotting._datamap.visualize_document_datamap
310 unmodified lines311312313310 unmodified lineshave data that contains a lot of noise, for example, HTML-tags, then it would be best to remove them. HTML-tagstypically do not contribute to the meaning of a document and should therefore be removed. However, if you applytopic modeling to HTML-code to extract topics of code, then it becomes important.310 unmodified lines311312313314315316317318319320321322323324325326327328329330331332333310 unmodified lineshave data that contains a lot of noise, for example, HTML-tags, then it would be best to remove them. HTML-tagstypically do not contribute to the meaning of a document and should therefore be removed. However, if you applytopic modeling to HTML-code to extract topics of code, then it becomes important.## **I run into issues running on Apple Silicon. What should I do?**Apple Silicon chips (M1 & M2) are based on the ARM64 (aka [AArch64](https://apple.stackexchange.com/questions/451238/is-m1-chip-aarch64-or-amd64), not to be confused with AMD64). There are known issues with upstream dependencies for this architecture, for example [numba](https://github.com/numba/numba/issues/5520). You may not always run into this issue, depending on the extras that you need.One possible solution to this is to use [VS Code Dev Containers](https://code.visualstudio.com/docs/devcontainers/containers), which allows you to setup a Linux-based environment. To run BERTopic effectively you need to be aware of two things:- Make sure to use a Docker image specifically compiled for ARM64- Make sure to use `volume` instead of `mount-bind`, since the latter significantly reduces I/O speeds to diskUsing the pre-configured [Data Science Devcontainers](https://github.com/b-data/data-science-devcontainers) makes sure these setting are optimized. To start using them, do the following:- Install and run Docker- Install `python-base` or `python-scipy` [devcontainer](https://github.com/b-data/data-science-devcontainers)- ℹ️ Change PYTHON_VERSION to 3.11 in the `devcontainer.json` to work with the latest version of Python 3.11 (currently 3.11.8)- Open VS Code, build the container and start working- Note that data is persisted in the container- When using an unmodified devcontainer.json: work in `/home/vscode` which is the `home` directory of user `vscode`- Python packages are installed to the home directory by default. This is due to env variable `PIP_USER=1`- Note that the directory `/workspaces` is also persisted
12339 unmodified lines43444546474851 unmodified lines100101102Using the `.visualize_topics`, we can visualize the topics and get insight into their relationships. However,you might want a more fine-grained approach where we can visualize the documents inside the topics to seeif they were assigned correctly or whether they make sense. To do so, we can use the `topic_model.visualize_documents()`39 unmodified linestopic_model.visualize_documents(titles, reduced_embeddings=reduced_embeddings)```## **Visualize Probablities or Distribution**We can generate the topic-document probability matrix by simply setting `calculate_probabilities=True` if a HDBSCAN model is used:51 unmodified linesthe distribution of the frequencies of topics across a document. It merely showshow confident BERTopic is that certain topics can be found in a document.1234539 unmodified lines45464748495051525354555657585960616263646566676869707172737451 unmodified lines126127128129## **Visualize documents with Plotly**Using the `.visualize_topics`, we can visualize the topics and get insight into their relationships. However,you might want a more fine-grained approach where we can visualize the documents inside the topics to seeif they were assigned correctly or whether they make sense. To do so, we can use the `topic_model.visualize_documents()`39 unmodified linestopic_model.visualize_documents(titles, reduced_embeddings=reduced_embeddings)```## **Visualize documents with DataMapPlot**`.visualize_document_datamap` provides an alternative way to visualize the documents inside the topics as a static [DataMapPlot](https://datamapplot.readthedocs.io/en/latest/intro_splash.html). Using the same pipeline as above, you can generate a DataMapPlot by running:```python# with the original embeddingstopic_model.visualize_document_datamap(docs, embeddings=embeddings)# with the reduced embeddingstopic_model.visualize_document_datamap(docs, reduced_embeddings=reduced_embeddings)```<br><br><img src="./datamapplot.png"><br><br>Or if you want to save the resulting figure:```pythonfig = topic_model.visualize_document_datamap(docs, reduced_embeddings=reduced_embeddings)fig.savefig("path/to/file.png", bbox_inches="tight")```## **Visualize Probablities or Distribution**We can generate the topic-document probability matrix by simply setting `calculate_probabilities=True` if a HDBSCAN model is used:51 unmodified linesthe distribution of the frequencies of topics across a document. It merely showshow confident BERTopic is that certain topics can be found in a document.
245 unmodified lines2462472482492502512 unmodified lines254255256257258259260245 unmodified lines|-----------------------|---|| Visualize Topics | `.visualize_topics()` || Visualize Documents | `.visualize_documents()` || Visualize Document Hierarchy | `.visualize_hierarchical_documents()` || Visualize Topic Hierarchy | `.visualize_hierarchy()` || Visualize Topic Tree | `.get_topic_tree(hierarchical_topics)` |2 unmodified lines| Visualize Term Score Decline | `.visualize_term_rank()` || Visualize Topic Probability Distribution | `.visualize_distribution(probs[0])` || Visualize Topics over Time | `.visualize_topics_over_time(topics_over_time)` || Visualize Topics per Class | `.visualize_topics_per_class(topics_per_class)` |## **Citation**245 unmodified lines2462472482492502512522 unmodified lines255256257258259260261262245 unmodified lines|-----------------------|---|| Visualize Topics | `.visualize_topics()` || Visualize Documents | `.visualize_documents()` || Visualize Document with DataMapPlot | `.visualize_document_datamap()` || Visualize Document Hierarchy | `.visualize_hierarchical_documents()` || Visualize Topic Hierarchy | `.visualize_hierarchy()` || Visualize Topic Tree | `.get_topic_tree(hierarchical_topics)` |2 unmodified lines| Visualize Term Score Decline | `.visualize_term_rank()` || Visualize Topic Probability Distribution | `.visualize_distribution(probs[0])` || Visualize Topics over Time | `.visualize_topics_over_time(topics_over_time)` || Visualize Topics per Class | `.visualize_topics_per_class(topics_per_class)` |## **Citation**
82 unmodified lines83848586878882 unmodified lines- Plotting:- Barchart: api/plotting/barchart.md- Documents: api/plotting/documents.md- DTM: api/plotting/dtm.md- Hierarchical documents: api/plotting/hierarchical_documents.md- Hierarchical topics: api/plotting/hierarchy.md82 unmodified lines8384858687888982 unmodified lines- Plotting:- Barchart: api/plotting/barchart.md- Documents: api/plotting/documents.md- Documents with DataMapPlot: api/plotting/document_datamap.md- DTM: api/plotting/dtm.md- Hierarchical documents: api/plotting/hierarchical_documents.md- Hierarchical topics: api/plotting/hierarchy.md
BERTopic/.gitignore+3
BERTopic/bertopic/_bertopic.py+40-38
BERTopic/docs/api/plotting/document_datamap.md+1-1
BERTopic/docs/faq.md+20
BERTopic/docs/getting_started/visualization/visualize_documents.md+27
BERTopic/docs/index.md+3-1
BERTopic/mkdocs.yml+1