-
Notifications
You must be signed in to change notification settings - Fork 764
/
_bertopic.py
2953 lines (2421 loc) · 131 KB
/
_bertopic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import yaml
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
try:
yaml._warnings_enabled["YAMLLoadWarning"] = False
except (KeyError, AttributeError, TypeError) as e:
pass
import re
import joblib
import inspect
import numpy as np
import pandas as pd
from tqdm import tqdm
from packaging import version
from scipy.sparse import csr_matrix
from scipy.cluster import hierarchy as sch
from typing import List, Tuple, Union, Mapping, Any, Callable, Iterable
# Models
import hdbscan
from umap import UMAP
from sklearn.preprocessing import normalize
from sklearn import __version__ as sklearn_version
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
# BERTopic
from bertopic import plotting
from bertopic._mmr import mmr
from bertopic.vectorizers import ClassTfidfTransformer
from bertopic.backend._utils import select_backend
from bertopic._utils import MyLogger, check_documents_type, check_embeddings_shape, check_is_fitted
# Visualization
import plotly.graph_objects as go
logger = MyLogger("WARNING")
class BERTopic:
"""BERTopic is a topic modeling technique that leverages BERT embeddings and
c-TF-IDF to create dense clusters allowing for easily interpretable topics
whilst keeping important words in the topic descriptions.
The default embedding model is `all-MiniLM-L6-v2` when selecting `language="english"`
and `paraphrase-multilingual-MiniLM-L12-v2` when selecting `language="multilingual"`.
Attributes:
topics_ (List[int]) : The topics that are generated for each document after training or updating
the topic model. The most recent topics are tracked.
probabilities_ (List[float]): The probability of the assigned topic per document. These are
only calculated if a HDBSCAN model is used for the clustering step.
When `calculate_probabilities=True`, then it is the probabilities
of all topics per document.
topic_sizes_ (Mapping[int, int]) : The size of each topic
topic_mapper_ (TopicMapper) : A class for tracking topics and their mappings anytime they are
merged, reduced, added, or removed.
topic_representations_ (Mapping[int, Tuple[int, float]]) : The top n terms per topic and their respective
c-TF-IDF values.
c_tf_idf_ (csr_matrix) : The topic-term matrix as calculated through c-TF-IDF. To access its respective
words, run `.vectorizer_model.get_feature_names()` or
`.vectorizer_model.get_feature_names_out()`
topic_labels_ (Mapping[int, str]) : The default labels for each topic.
custom_labels_ (List[str]) : Custom labels for each topic.
topic_embeddings_ (np.ndarray) : The embeddings for each topic. It is calculated by taking the
weighted average of word embeddings in a topic based on their c-TF-IDF values.
representative_docs_ (Mapping[int, str]) : The representative documents for each topic.
Examples:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(subset='all')['data']
topic_model = BERTopic()
topics, probabilities = topic_model.fit_transform(docs)
```
If you want to use your own embedding model, use it as follows:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
docs = fetch_20newsgroups(subset='all')['data']
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
topic_model = BERTopic(embedding_model=sentence_model)
```
Due to the stochastisch nature of UMAP, the results from BERTopic might differ
and the quality can degrade. Using your own embeddings allows you to
try out BERTopic several times until you find the topics that suit
you best.
"""
def __init__(self,
language: str = "english",
top_n_words: int = 10,
n_gram_range: Tuple[int, int] = (1, 1),
min_topic_size: int = 10,
nr_topics: Union[int, str] = None,
low_memory: bool = False,
calculate_probabilities: bool = False,
diversity: float = None,
seed_topic_list: List[List[str]] = None,
embedding_model=None,
umap_model: UMAP = None,
hdbscan_model: hdbscan.HDBSCAN = None,
vectorizer_model: CountVectorizer = None,
ctfidf_model: TfidfTransformer = None,
verbose: bool = False,
):
"""BERTopic initialization
Arguments:
language: The main language used in your documents. The default sentence-transformers
model for "english" is `all-MiniLM-L6-v2`. For a full overview of
supported languages see bertopic.backend.languages. Select
"multilingual" to load in the `paraphrase-multilingual-MiniLM-L12-v2`
sentence-tranformers model that supports 50+ languages.
top_n_words: The number of words per topic to extract. Setting this
too high can negatively impact topic embeddings as topics
are typically best represented by at most 10 words.
n_gram_range: The n-gram range for the CountVectorizer.
Advised to keep high values between 1 and 3.
More would likely lead to memory issues.
NOTE: This param will not be used if you pass in your own
CountVectorizer.
min_topic_size: The minimum size of the topic. Increasing this value will lead
to a lower number of clusters/topics.
nr_topics: Specifying the number of topics will reduce the initial
number of topics to the value specified. This reduction can take
a while as each reduction in topics (-1) activates a c-TF-IDF
calculation. If this is set to None, no reduction is applied. Use
"auto" to automatically reduce topics using HDBSCAN.
low_memory: Sets UMAP low memory to True to make sure less memory is used.
NOTE: This is only used in UMAP. For example, if you use PCA instead of UMAP
this parameter will not be used.
calculate_probabilities: Whether to calculate the probabilities of all topics
per document instead of the probability of the assigned
topic per document. This could slow down the extraction
of topics if you have many documents (> 100_000). Set this
only to True if you have a low amount of documents or if
you do not mind more computation time.
NOTE: If false you cannot use the corresponding
visualization method `visualize_probabilities`.
diversity: Whether to use MMR to diversify the resulting topic representations.
If set to None, MMR will not be used. Accepted values lie between
0 and 1 with 0 being not at all diverse and 1 being very diverse.
seed_topic_list: A list of seed words per topic to converge around
verbose: Changes the verbosity of the model, Set to True if you want
to track the stages of the model.
embedding_model: Use a custom embedding model.
The following backends are currently supported
* SentenceTransformers
* Flair
* Spacy
* Gensim
* USE (TF-Hub)
You can also pass in a string that points to one of the following
sentence-transformers models:
* https://www.sbert.net/docs/pretrained_models.html
umap_model: Pass in a UMAP model to be used instead of the default.
NOTE: You can also pass in any dimensionality reduction algorithm as long
as it has `.fit` and `.transform` functions.
hdbscan_model: Pass in a hdbscan.HDBSCAN model to be used instead of the default
NOTE: You can also pass in any clustering algorithm as long as it has
`.fit` and `.predict` functions along with the `.labels_` variable.
vectorizer_model: Pass in a custom `CountVectorizer` instead of the default model.
ctfidf_model: Pass in a custom ClassTfidfTransformer instead of the default model.
"""
# Topic-based parameters
if top_n_words > 30:
raise ValueError("top_n_words should be lower or equal to 30. The preferred value is 10.")
self.top_n_words = top_n_words
self.min_topic_size = min_topic_size
self.nr_topics = nr_topics
self.low_memory = low_memory
self.calculate_probabilities = calculate_probabilities
self.diversity = diversity
self.verbose = verbose
self.seed_topic_list = seed_topic_list
# Embedding model
self.language = language if not embedding_model else None
self.embedding_model = embedding_model
# Vectorizer
self.n_gram_range = n_gram_range
self.vectorizer_model = vectorizer_model or CountVectorizer(ngram_range=self.n_gram_range)
self.ctfidf_model = ctfidf_model or ClassTfidfTransformer()
# UMAP or another algorithm that has .fit and .transform functions
self.umap_model = umap_model or UMAP(n_neighbors=15,
n_components=5,
min_dist=0.0,
metric='cosine',
low_memory=self.low_memory)
# HDBSCAN or another clustering algorithm that has .fit and .predict functions and
# the .labels_ variable to extract the labels
self.hdbscan_model = hdbscan_model or hdbscan.HDBSCAN(min_cluster_size=self.min_topic_size,
metric='euclidean',
cluster_selection_method='eom',
prediction_data=True)
# Public attributes
self.topics_ = None
self.probabilities_ = None
self.topic_sizes_ = None
self.topic_mapper_ = None
self.topic_representations_ = None
self.topic_embeddings_ = None
self.topic_labels_ = None
self.custom_labels_ = None
self.representative_docs_ = None
self.c_tf_idf_ = None
# Private attributes for internal tracking purposes
self._outliers = 1
self._merged_topics = None
if verbose:
logger.set_level("DEBUG")
def fit(self,
documents: List[str],
embeddings: np.ndarray = None,
y: Union[List[int], np.ndarray] = None):
""" Fit the models (Bert, UMAP, and, HDBSCAN) on a collection of documents and generate topics
Arguments:
documents: A list of documents to fit on
embeddings: Pre-trained document embeddings. These can be used
instead of the sentence-transformer model
y: The target class for (semi)-supervised modeling. Use -1 if no class for a
specific instance is specified.
Examples:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(subset='all')['data']
topic_model = BERTopic().fit(docs)
```
If you want to use your own embeddings, use it as follows:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
# Create embeddings
docs = fetch_20newsgroups(subset='all')['data']
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = sentence_model.encode(docs, show_progress_bar=True)
# Create topic model
topic_model = BERTopic().fit(docs, embeddings)
```
"""
self.fit_transform(documents, embeddings, y)
return self
def fit_transform(self,
documents: List[str],
embeddings: np.ndarray = 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 docs with topics
Arguments:
documents: A list of documents to fit on
embeddings: Pre-trained document embeddings. These can be used
instead of the sentence-transformer model
y: The target class for (semi)-supervised modeling. Use -1 if no class for a
specific instance is specified.
Returns:
predictions: Topic predictions for each documents
probabilities: The probability of the assigned topic per document.
If `calculate_probabilities` in BERTopic is set to True, then
it calculates the probabilities of all topics across all documents
instead of only the assigned topic. This, however, slows down
computation and may increase memory usage.
Examples:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(subset='all')['data']
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)
```
If you want to use your own embeddings, use it as follows:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
# Create embeddings
docs = fetch_20newsgroups(subset='all')['data']
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = sentence_model.encode(docs, show_progress_bar=True)
# Create topic model
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs, embeddings)
```
"""
check_documents_type(documents)
check_embeddings_shape(embeddings, documents)
documents = pd.DataFrame({"Document": documents,
"ID": range(len(documents)),
"Topic": None})
# Extract embeddings
if embeddings is None:
self.embedding_model = select_backend(self.embedding_model,
language=self.language)
embeddings = self._extract_embeddings(documents.Document,
method="document",
verbose=self.verbose)
logger.info("Transformed documents to Embeddings")
else:
if self.embedding_model is not None:
self.embedding_model = select_backend(self.embedding_model,
language=self.language)
# Reduce dimensionality
if self.seed_topic_list is not None and self.embedding_model is not None:
y, embeddings = self._guided_topic_modeling(embeddings)
umap_embeddings = self._reduce_dimensionality(embeddings, y)
# Cluster reduced embeddings
documents, probabilities = self._cluster_embeddings(umap_embeddings, documents)
# Sort and Map Topic IDs by their frequency
if not self.nr_topics:
documents = self._sort_mappings_by_frequency(documents)
# Extract topics by calculating c-TF-IDF
self._extract_topics(documents)
# Reduce topics
if self.nr_topics:
documents = self._reduce_topics(documents)
self._map_representative_docs(original_topics=True)
self.probabilities_ = self._map_probabilities(probabilities, original_topics=True)
predictions = documents.Topic.to_list()
return predictions, self.probabilities_
def transform(self,
documents: Union[str, List[str]],
embeddings: np.ndarray = None) -> Tuple[List[int], np.ndarray]:
""" After having fit a model, use transform to predict new instances
Arguments:
documents: A single document or a list of documents to fit on
embeddings: Pre-trained document embeddings. These can be used
instead of the sentence-transformer model.
Returns:
predictions: Topic predictions for each documents
probabilities: The topic probability distribution which is returned by default.
If `calculate_probabilities` in BERTopic is set to False, then the
probabilities are not calculated to speed up computation and
decrease memory usage.
Examples:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
docs = fetch_20newsgroups(subset='all')['data']
topic_model = BERTopic().fit(docs)
topics, probs = topic_model.transform(docs)
```
If you want to use your own embeddings:
```python
from bertopic import BERTopic
from sklearn.datasets import fetch_20newsgroups
from sentence_transformers import SentenceTransformer
# Create embeddings
docs = fetch_20newsgroups(subset='all')['data']
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = sentence_model.encode(docs, show_progress_bar=True)
# Create topic model
topic_model = BERTopic().fit(docs, embeddings)
topics, probs = topic_model.transform(docs, embeddings)
```
"""
check_is_fitted(self)
check_embeddings_shape(embeddings, documents)
if isinstance(documents, str):
documents = [documents]
if embeddings is None:
embeddings = self._extract_embeddings(documents,
method="document",
verbose=self.verbose)
umap_embeddings = self.umap_model.transform(embeddings)
logger.info("Reduced dimensionality")
# Extract predictions and probabilities if it is a HDBSCAN model
if isinstance(self.hdbscan_model, hdbscan.HDBSCAN):
predictions, probabilities = hdbscan.approximate_predict(self.hdbscan_model, umap_embeddings)
# Calculate probabilities
if self.calculate_probabilities:
probabilities = hdbscan.membership_vector(self.hdbscan_model, umap_embeddings)
logger.info("Calculated probabilities with HDBSCAN")
else:
predictions = self.hdbscan_model.predict(umap_embeddings)
probabilities = None
logger.info("Predicted clusters")
# Map probabilities and predictions
probabilities = self._map_probabilities(probabilities, original_topics=True)
predictions = self._map_predictions(predictions)
return predictions, probabilities
def partial_fit(self,
documents: List[str],
embeddings: np.ndarray = None,
y: Union[List[int], np.ndarray] = None):
""" Fit BERTopic on a subset of the data and perform online learning
with batch-like data.
Online topic modeling in BERTopic is performed by using dimensionality
reduction and cluster algorithms that support a `partial_fit` method
in order to incrementally train the topic model.
Likewise, the `bertopic.vectorizers.OnlineCountVectorizer` is used
to dynamically update its vocabulary when presented with new data.
It has several parameters for modeling decay and updating the
representations.
In other words, although the main algorithm stays the same, the training
procedure now works as follows:
For each subset of the data:
1. Generate embeddings with a pre-traing language model
2. Incrementally update the dimensionality reduction algorithm with `partial_fit`
3. Incrementally update the cluster algorithm with `partial_fit`
4. Incrementally update the OnlineCountVectorizer and apply some form of decay
Note that it is advised to use `partial_fit` with batches and
not single documents for the best performance.
Arguments:
documents: A list of documents to fit on
embeddings: Pre-trained document embeddings. These can be used
instead of the sentence-transformer model
y: The target class for (semi)-supervised modeling. Use -1 if no class for a
specific instance is specified.
Examples:
```python
from sklearn.datasets import fetch_20newsgroups
from sklearn.cluster import MiniBatchKMeans
from sklearn.decomposition import IncrementalPCA
from bertopic.vectorizers import OnlineCountVectorizer
from bertopic import BERTopic
# Prepare documents
docs = fetch_20newsgroups(subset=subset, remove=('headers', 'footers', 'quotes'))["data"]
# Prepare sub-models that support online learning
umap_model = IncrementalPCA(n_components=5)
cluster_model = MiniBatchKMeans(n_clusters=50, random_state=0)
vectorizer_model = OnlineCountVectorizer(stop_words="english", decay=.01)
topic_model = BERTopic(umap_model=umap_model,
hdbscan_model=cluster_model,
vectorizer_model=vectorizer_model)
# Incrementally fit the topic model by training on 1000 documents at a time
for index in range(0, len(docs), 1000):
topic_model.partial_fit(docs[index: index+1000])
```
"""
# Checks
check_embeddings_shape(embeddings, documents)
if not hasattr(self.hdbscan_model, "partial_fit"):
raise ValueError("In order to use `.partial_fit`, the cluster model should have "
"a `.partial_fit` function.")
# Prepare documents
if isinstance(documents, str):
documents = [documents]
documents = pd.DataFrame({"Document": documents,
"ID": range(len(documents)),
"Topic": None})
# Extract embeddings
if embeddings is None:
if self.topic_representations_ is None:
self.embedding_model = select_backend(self.embedding_model,
language=self.language)
embeddings = self._extract_embeddings(documents.Document,
method="document",
verbose=self.verbose)
else:
if self.embedding_model is not None and self.topic_representations_ is None:
self.embedding_model = select_backend(self.embedding_model,
language=self.language)
# Reduce dimensionality
if self.seed_topic_list is not None and self.embedding_model is not None:
y, embeddings = self._guided_topic_modeling(embeddings)
umap_embeddings = self._reduce_dimensionality(embeddings, y, partial_fit=True)
# Cluster reduced embeddings
documents, self.probabilities_ = self._cluster_embeddings(umap_embeddings, documents, partial_fit=True)
topics = documents.Topic.to_list()
# Map and find new topics
if not self.topic_mapper_:
self.topic_mapper_ = TopicMapper(topics)
mappings = self.topic_mapper_.get_mappings()
new_topics = set(topics).difference(set(mappings.keys()))
new_topic_ids = {topic: max(mappings.values()) + index + 1 for index, topic in enumerate(new_topics)}
self.topic_mapper_.add_new_topics(new_topic_ids)
updated_mappings = self.topic_mapper_.get_mappings()
updated_topics = [updated_mappings[topic] for topic in topics]
documents["Topic"] = updated_topics
# Add missing topics (topics that were originally created but are now missing)
if self.topic_representations_:
missing_topics = set(self.topic_representations_.keys()).difference(set(updated_topics))
for missing_topic in missing_topics:
documents.loc[len(documents), :] = [" ", len(documents), missing_topic]
else:
missing_topics = {}
# Prepare documents
documents_per_topic = documents.sort_values("Topic").groupby(['Topic'], as_index=False)
updated_topics = documents_per_topic.first().Topic.astype(int)
documents_per_topic = documents_per_topic.agg({'Document': ' '.join})
# Update topic representations
self.c_tf_idf_, updated_words = self._c_tf_idf(documents_per_topic, partial_fit=True)
self.topic_representations_ = self._extract_words_per_topic(updated_words, self.c_tf_idf_, labels=updated_topics)
self._create_topic_vectors()
self.topic_labels_ = {key: f"{key}_" + "_".join([word[0] for word in values[:4]])
for key, values in self.topic_representations_.items()}
# Update topic sizes
if len(missing_topics) > 0:
documents = documents.iloc[:-len(missing_topics)]
if self.topic_sizes_ is None:
self._update_topic_size(documents)
else:
sizes = documents.groupby(['Topic'], as_index=False).count()
for _, row in sizes.iterrows():
topic = int(row.Topic)
if self.topic_sizes_.get(topic) is not None and topic not in missing_topics:
self.topic_sizes_[topic] += int(row.Document)
elif self.topic_sizes_.get(topic) is None:
self.topic_sizes_[topic] = int(row.Document)
self.topics_ = documents.Topic.astype(int).tolist()
return self
def topics_over_time(self,
docs: List[str],
timestamps: Union[List[str],
List[int]],
nr_bins: int = None,
datetime_format: str = None,
evolution_tuning: bool = True,
global_tuning: bool = True) -> pd.DataFrame:
""" Create topics over time
To create the topics over time, BERTopic needs to be already fitted once.
From the fitted models, the c-TF-IDF representations are calculate at
each timestamp t. Then, the c-TF-IDF representations at timestamp t are
averaged with the global c-TF-IDF representations in order to fine-tune the
local representations.
NOTE:
Make sure to use a limited number of unique timestamps (<100) as the
c-TF-IDF representation will be calculated at each single unique timestamp.
Having a large number of unique timestamps can take some time to be calculated.
Moreover, there aren't many use-cased where you would like to see the difference
in topic representations over more than 100 different timestamps.
Arguments:
docs: The documents you used when calling either `fit` or `fit_transform`
timestamps: The timestamp of each document. This can be either a list of strings or ints.
If it is a list of strings, then the datetime format will be automatically
inferred. If it is a list of ints, then the documents will be ordered by
ascending order.
nr_bins: The number of bins you want to create for the timestamps. The left interval will
be chosen as the timestamp. An additional column will be created with the
entire interval.
datetime_format: The datetime format of the timestamps if they are strings, eg “%d/%m/%Y”.
Set this to None if you want to have it automatically detect the format.
See strftime documentation for more information on choices:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.
evolution_tuning: Fine-tune each topic representation at timestamp *t* by averaging its
c-TF-IDF matrix with the c-TF-IDF matrix at timestamp *t-1*. This creates
evolutionary topic representations.
global_tuning: Fine-tune each topic representation at timestamp *t* by averaging its c-TF-IDF matrix
with the global c-TF-IDF matrix. Turn this off if you want to prevent words in
topic representations that could not be found in the documents at timestamp *t*.
Returns:
topics_over_time: A dataframe that contains the topic, words, and frequency of topic
at timestamp *t*.
Examples:
The timestamps variable represent the timestamp of each document. If you have over
100 unique timestamps, it is advised to bin the timestamps as shown below:
```python
from bertopic import BERTopic
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)
topics_over_time = topic_model.topics_over_time(docs, timestamps, nr_bins=20)
```
"""
check_is_fitted(self)
check_documents_type(docs)
documents = pd.DataFrame({"Document": docs, "Topic": self.topics_, "Timestamps": timestamps})
global_c_tf_idf = normalize(self.c_tf_idf_, axis=1, norm='l1', copy=False)
all_topics = sorted(list(documents.Topic.unique()))
all_topics_indices = {topic: index for index, topic in enumerate(all_topics)}
if isinstance(timestamps[0], str):
infer_datetime_format = True if not datetime_format else False
documents["Timestamps"] = pd.to_datetime(documents["Timestamps"],
infer_datetime_format=infer_datetime_format,
format=datetime_format)
if nr_bins:
documents["Bins"] = pd.cut(documents.Timestamps, bins=nr_bins)
documents["Timestamps"] = documents.apply(lambda row: row.Bins.left, 1)
# Sort documents in chronological order
documents = documents.sort_values("Timestamps")
timestamps = documents.Timestamps.unique()
if len(timestamps) > 100:
warnings.warn(f"There are more than 100 unique timestamps (i.e., {len(timestamps)}) "
"which significantly slows down the application. Consider setting `nr_bins` "
"to a value lower than 100 to speed up calculation. ")
# For each unique timestamp, create topic representations
topics_over_time = []
for index, timestamp in tqdm(enumerate(timestamps), disable=not self.verbose):
# Calculate c-TF-IDF representation for a specific timestamp
selection = documents.loc[documents.Timestamps == timestamp, :]
documents_per_topic = selection.groupby(['Topic'], as_index=False).agg({'Document': ' '.join,
"Timestamps": "count"})
c_tf_idf, words = self._c_tf_idf(documents_per_topic, fit=False)
if global_tuning or evolution_tuning:
c_tf_idf = normalize(c_tf_idf, axis=1, norm='l1', copy=False)
# Fine-tune the c-TF-IDF matrix at timestamp t by averaging it with the c-TF-IDF
# matrix at timestamp t-1
if evolution_tuning and index != 0:
current_topics = sorted(list(documents_per_topic.Topic.values))
overlapping_topics = sorted(list(set(previous_topics).intersection(set(current_topics))))
current_overlap_idx = [current_topics.index(topic) for topic in overlapping_topics]
previous_overlap_idx = [previous_topics.index(topic) for topic in overlapping_topics]
c_tf_idf.tolil()[current_overlap_idx] = ((c_tf_idf[current_overlap_idx] +
previous_c_tf_idf[previous_overlap_idx]) / 2.0).tolil()
# Fine-tune the timestamp c-TF-IDF representation based on the global c-TF-IDF representation
# by simply taking the average of the two
if global_tuning:
selected_topics = [all_topics_indices[topic] for topic in documents_per_topic.Topic.values]
c_tf_idf = (global_c_tf_idf[selected_topics] + c_tf_idf) / 2.0
# Extract the words per topic
labels = sorted(list(documents_per_topic.Topic.unique()))
words_per_topic = self._extract_words_per_topic(words, c_tf_idf, labels)
topic_frequency = pd.Series(documents_per_topic.Timestamps.values,
index=documents_per_topic.Topic).to_dict()
# Fill dataframe with results
topics_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)
if evolution_tuning:
previous_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],
classes: Union[List[int], List[str]],
global_tuning: bool = True) -> pd.DataFrame:
""" Create topics per class
To create the topics per class, BERTopic needs to be already fitted once.
From the fitted models, the c-TF-IDF representations are calculate at
each class c. Then, the c-TF-IDF representations at class c are
averaged with the global c-TF-IDF representations in order to fine-tune the
local representations. This can be turned off if the pure representation is
needed.
NOTE:
Make sure to use a limited number of unique classes (<100) as the
c-TF-IDF representation will be calculated at each single unique class.
Having a large number of unique classes can take some time to be calculated.
Arguments:
docs: The documents you used when calling either `fit` or `fit_transform`
classes: The class of each document. This can be either a list of strings or ints.
global_tuning: Fine-tune each topic representation at timestamp t by averaging its c-TF-IDF matrix
with the global c-TF-IDF matrix. Turn this off if you want to prevent words in
topic representations that could not be found in the documents at timestamp t.
Returns:
topics_per_class: A dataframe that contains the topic, words, and frequency of topics
for each class.
Examples:
```python
from bertopic import BERTopic
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)
topics_per_class = topic_model.topics_per_class(docs, classes)
```
"""
documents = pd.DataFrame({"Document": docs, "Topic": self.topics_, "Class": classes})
global_c_tf_idf = normalize(self.c_tf_idf_, axis=1, norm='l1', copy=False)
# For each unique timestamp, create topic representations
topics_per_class = []
for _, class_ in tqdm(enumerate(set(classes)), disable=not self.verbose):
# Calculate c-TF-IDF representation for a specific timestamp
selection = documents.loc[documents.Class == class_, :]
documents_per_topic = selection.groupby(['Topic'], as_index=False).agg({'Document': ' '.join,
"Class": "count"})
c_tf_idf, words = self._c_tf_idf(documents_per_topic, fit=False)
# Fine-tune the timestamp c-TF-IDF representation based on the global c-TF-IDF representation
# by simply taking the average of the two
if global_tuning:
c_tf_idf = normalize(c_tf_idf, axis=1, norm='l1', copy=False)
c_tf_idf = (global_c_tf_idf[documents_per_topic.Topic.values + self._outliers] + c_tf_idf) / 2.0
# Extract the words per topic
labels = sorted(list(documents_per_topic.Topic.unique()))
words_per_topic = self._extract_words_per_topic(words, c_tf_idf, labels)
topic_frequency = pd.Series(documents_per_topic.Class.values,
index=documents_per_topic.Topic).to_dict()
# Fill dataframe with results
topics_at_class = [(topic,
", ".join([words[0] for words in values][:5]),
topic_frequency[topic],
class_) for topic, values in words_per_topic.items()]
topics_per_class.extend(topics_at_class)
topics_per_class = pd.DataFrame(topics_per_class, columns=["Topic", "Words", "Frequency", "Class"])
return topics_per_class
def hierarchical_topics(self,
docs: List[int],
linkage_function: Callable[[csr_matrix], np.ndarray] = None,
distance_function: Callable[[csr_matrix], csr_matrix] = None) -> pd.DataFrame:
""" Create a hierarchy of topics
To create this hierarchy, BERTopic needs to be already fitted once.
Then, a hierarchy is calculated on the distance matrix of the c-TF-IDF
representation using `scipy.cluster.hierarchy.linkage`.
Based on that hierarchy, we calculate the topic representation at each
merged step. This is a local representation, as we only assume that the
chosen step is merged and not all others which typically improves the
topic representation.
Arguments:
docs: The documents you used when calling either `fit` or `fit_transform`
linkage_function: The linkage function to use. Default is:
`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)`
Returns:
hierarchical_topics: A dataframe that contains a hierarchy of topics
represented by their parents and their children
Examples:
```python
from bertopic import BERTopic
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)
hierarchical_topics = topic_model.hierarchical_topics(docs)
```
A custom linkage function can be used as follows:
```python
from scipy.cluster import hierarchy as sch
from bertopic import BERTopic
topic_model = BERTopic()
topics, probs = topic_model.fit_transform(docs)
# Hierarchical topics
linkage_function = lambda x: sch.linkage(x, 'ward', optimal_ordering=True)
hierarchical_topics = topic_model.hierarchical_topics(docs, linkage_function=linkage_function)
```
"""
if distance_function is None:
distance_function = lambda x: 1 - cosine_similarity(x)
if linkage_function is None:
linkage_function = lambda x: sch.linkage(x, 'ward', optimal_ordering=True)
# Calculate linkage
embeddings = self.c_tf_idf_[self._outliers:]
X = distance_function(embeddings)
Z = linkage_function(X)
# Calculate basic bag-of-words to be iteratively merged later
documents = pd.DataFrame({"Document": docs,
"ID": range(len(docs)),
"Topic": self.topics_})
documents_per_topic = documents.groupby(['Topic'], as_index=False).agg({'Document': ' '.join})
documents_per_topic = documents_per_topic.loc[documents_per_topic.Topic != -1, :]
documents = self._preprocess_text(documents_per_topic.Document.values)
# Scikit-Learn Deprecation: get_feature_names is deprecated in 1.0
# and will be removed in 1.2. Please use get_feature_names_out instead.
if version.parse(sklearn_version) >= version.parse("1.0.0"):
words = self.vectorizer_model.get_feature_names_out()
else:
words = self.vectorizer_model.get_feature_names()
bow = self.vectorizer_model.transform(documents)
# Extract clusters
hier_topics = pd.DataFrame(columns=["Parent_ID", "Parent_Name", "Topics",
"Child_Left_ID", "Child_Left_Name",
"Child_Right_ID", "Child_Right_Name"])
for index in tqdm(range(len(Z))):
# Find clustered documents
clusters = sch.fcluster(Z, t=Z[index][2], criterion='distance') - self._outliers
cluster_df = pd.DataFrame({"Topic": range(len(clusters)), "Cluster": clusters})
cluster_df = cluster_df.groupby("Cluster").agg({'Topic': lambda x: list(x)}).reset_index()
nr_clusters = len(clusters)
# Extract first topic we find to get the set of topics in a merged topic
topic = None
val = Z[index][0]
while topic is None:
if val - len(clusters) < 0:
topic = int(val)
else:
val = Z[int(val - len(clusters))][0]
clustered_topics = [i for i, x in enumerate(clusters) if x == clusters[topic]]
# Group bow per cluster, calculate c-TF-IDF and extract words
grouped = csr_matrix(bow[clustered_topics].sum(axis=0))
c_tf_idf = self.ctfidf_model.transform(grouped)
words_per_topic = self._extract_words_per_topic(words, c_tf_idf, labels=[0])
# Extract parent's name and ID
parent_id = index + len(clusters)
parent_name = "_".join([x[0] for x in words_per_topic[0]][:5])
# Extract child's name and ID
Z_id = Z[index][0]
child_left_id = Z_id if Z_id - nr_clusters < 0 else Z_id - nr_clusters
if Z_id - nr_clusters < 0:
child_left_name = "_".join([x[0] for x in self.get_topic(Z_id)][:5])
else:
child_left_name = hier_topics.iloc[int(child_left_id)].Parent_Name
# Extract child's name and ID
Z_id = Z[index][1]
child_right_id = Z_id if Z_id - nr_clusters < 0 else Z_id - nr_clusters
if Z_id - nr_clusters < 0:
child_right_name = "_".join([x[0] for x in self.get_topic(Z_id)][:5])
else:
child_right_name = hier_topics.iloc[int(child_right_id)].Parent_Name
# Save results
hier_topics.loc[len(hier_topics), :] = [parent_id, parent_name,
clustered_topics,
int(Z[index][0]), child_left_name,
int(Z[index][1]), child_right_name]
hier_topics["Distance"] = Z[:, 2]
hier_topics = hier_topics.sort_values("Parent_ID", ascending=False)
hier_topics[["Parent_ID", "Child_Left_ID", "Child_Right_ID"]] = hier_topics[["Parent_ID", "Child_Left_ID", "Child_Right_ID"]].astype(str)
return hier_topics
def find_topics(self,
search_term: str,
top_n: int = 5) -> Tuple[List[int], List[float]]:
""" Find topics most similar to a search_term
Creates an embedding for search_term and compares that with
the topic embeddings. The most similar topics are returned
along with their similarity values.
The search_term can be of any size but since it compares
with the topic representation it is advised to keep it
below 5 words.
Arguments:
search_term: the term you want to use to search for topics
top_n: the number of topics to return
Returns:
similar_topics: the most similar topics from high to low
similarity: the similarity scores from high to low
Examples:
You can use the underlying embedding model to find topics that
best represent the search term:
```python
topics, similarity = topic_model.find_topics("sports", top_n=5)
```
Note that the search query is typically more accurate if the
search_term consists of a phrase or multiple words.
"""
if self.embedding_model is None:
raise Exception("This method can only be used if you did not use custom embeddings.")
topic_list = list(self.topic_representations_.keys())
topic_list.sort()
# Extract search_term embeddings and compare with topic embeddings
search_embedding = self._extract_embeddings([search_term],
method="word",
verbose=False).flatten()
sims = cosine_similarity(search_embedding.reshape(1, -1), self.topic_embeddings_).flatten()
# Extract topics most similar to search_term
ids = np.argsort(sims)[-top_n:]
similarity = [sims[i] for i in ids][::-1]
similar_topics = [topic_list[index] for index in ids][::-1]
return similar_topics, similarity
def update_topics(self,
docs: List[str],
topics: List[int] = None,
n_gram_range: Tuple[int, int] = None,
vectorizer_model: CountVectorizer = None,
ctfidf_model: ClassTfidfTransformer = None):
""" Updates the topic representation by recalculating c-TF-IDF with the new
parameters as defined in this function.
When you have trained a model and viewed the topics and the words that represent them,
you might not be satisfied with the representation. Perhaps you forgot to remove
stop_words or you want to try out a different n_gram_range. This function allows you