-
Notifications
You must be signed in to change notification settings - Fork 373
/
Copy pathtop2vec.py
3271 lines (2567 loc) · 130 KB
/
top2vec.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
# Author: Dimo Angelov
#
# License: BSD 3 clause
import logging
import numpy as np
import pandas as pd
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import strip_tags
from gensim.models.phrases import Phrases
import umap
import hdbscan
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from joblib import dump, load
from sklearn.cluster import dbscan
import tempfile
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import normalize
from scipy.special import softmax
import os
from collections import namedtuple
from typing import List
from . import embedding
from .embedding import contextual_token_embeddings, sliding_window_average, average_embeddings, \
smooth_document_token_embeddings
from tqdm import tqdm
try:
from cuml.manifold.umap import UMAP as cuUMAP
_HAVE_CUMAP = True
except ImportError:
_HAVE_CUMAP = False
try:
from cuml.cluster import HDBSCAN as cuHDBSCAN
_HAVE_CUHDBSCAN = True
except ImportError:
_HAVE_CUHDBSCAN = False
try:
import hnswlib
_HAVE_HNSWLIB = True
except ImportError:
_HAVE_HNSWLIB = False
try:
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_text
_HAVE_TENSORFLOW = True
except ImportError:
_HAVE_TENSORFLOW = False
try:
from sentence_transformers import SentenceTransformer
_HAVE_TORCH = True
except ImportError:
_HAVE_TORCH = False
logger = logging.getLogger('top2vec')
logger.setLevel(logging.WARNING)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(sh)
contextual_top2vec_models = ["all-MiniLM-L6-v2", "all-mpnet-base-v2"]
contextual_top2vec_model_paths = {
"all-MiniLM-L6-v2": "sentence-transformers/all-MiniLM-L6-v2",
"all-mpnet-base-v2": "sentence-transformers/all-mpnet-base-v2"
}
use_models = ["universal-sentence-encoder-multilingual",
"universal-sentence-encoder",
"universal-sentence-encoder-large",
"universal-sentence-encoder-multilingual-large"]
use_model_urls = {
"universal-sentence-encoder-multilingual": "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3",
"universal-sentence-encoder": "https://tfhub.dev/google/universal-sentence-encoder/4",
"universal-sentence-encoder-large": "https://tfhub.dev/google/universal-sentence-encoder-large/5",
"universal-sentence-encoder-multilingual-large": "https://tfhub.dev/google/universal-sentence-encoder"
"-multilingual-large/3"
}
sbert_models = ["distiluse-base-multilingual-cased",
"all-MiniLM-L6-v2",
"paraphrase-multilingual-MiniLM-L12-v2"]
acceptable_embedding_models = use_models + sbert_models
Topic = namedtuple('Topic', ['topic_index', 'tokens', 'score'])
Document = namedtuple('Document', ['document_index', 'topics'])
def contextual_top2vec_req(required_state: bool):
def decorator(func):
def wrapper(self, *args, **kwargs):
if self.contextual_top2vec == required_state:
return func(self, *args, **kwargs)
else:
if required_state:
raise RuntimeError(f"Method only allowed for contextual top2vec")
else:
raise RuntimeError(f"Method not allowed for contextual top2vec")
return wrapper
return decorator
def default_tokenizer(document):
"""Tokenize a document for training and remove too long/short words
Parameters
----------
document: List of str
Input document.
Returns
-------
tokenized_document: List of str
List of tokens.
"""
return simple_preprocess(strip_tags(document), deacc=True)
def get_chunks(tokens, chunk_length, max_num_chunks, chunk_overlap_ratio):
"""Split a document into sequential chunks
Parameters
----------
tokens: List of str
Input document tokens.
chunk_length: int
Length of each document chunk.
max_num_chunks: int (Optional, default None)
Limit the number of document chunks
chunk_overlap_ratio: float
Fraction of overlapping tokens between sequential chunks.
Returns
-------
chunked_document: List of str
List of document chunks.
"""
num_tokens = len(tokens)
if num_tokens == 0:
return [""]
num_chunks = int(np.ceil(num_tokens / chunk_length))
if max_num_chunks is not None:
num_chunks = min(num_chunks, max_num_chunks)
return [" ".join(tokens[i:i + chunk_length])
for i in list(range(0, num_tokens, int(chunk_length * (1 - chunk_overlap_ratio))))[0:num_chunks]]
def get_random_chunks(tokens, chunk_length, chunk_len_coverage_ratio, max_num_chunks):
"""Split a document into chunks starting at random positions
Parameters
----------
tokens: List of str
Input document tokens.
chunk_length: int
Length of each document chunk.
chunk_len_coverage_ratio: float
Proportion of token length that will be covered by chunks. Default
value of 1.0 means chunk lengths will add up to number of tokens.
This does not mean all tokens will be covered.
max_num_chunks: int (Optional, default None)
Limit the number of document chunks
Returns
-------
chunked_document: List of str
List of document chunks.
"""
num_tokens = len(tokens)
if num_tokens == 0:
return [""]
num_chunks = int(np.ceil(num_tokens * chunk_len_coverage_ratio / chunk_length))
if max_num_chunks is not None:
num_chunks = min(num_chunks, max_num_chunks)
starts = np.random.choice(range(0, num_tokens), size=num_chunks)
return [" ".join(tokens[i:i + chunk_length]) for i in starts]
class Top2Vec:
"""
Top2Vec
Creates jointly embedded topic, document and word vectors.
Parameters
----------
documents: List of str
Input corpus, should be a list of strings.
contextual_top2vec: bool (Optional, default False)
If set to True, the model will be trained using contextual token
embeddings from each document and will find multiple topics per
document. It will also find topic segments within each document.
The only valid embedding_model options are:
* all-MiniLM-L6-v2
* all-mpnet-base-v2
c_top2vec_smoothing_window: int (Optional, default 5)
The size of the window used for smoothing the contextual token
embeddings.
min_count: int (Optional, default 50)
Ignores all words with total frequency lower than this. For smaller
corpora a smaller min_count will be necessary.
topic_merge_delta: float (default 0.1)
Merges topic vectors which have a cosine distance smaller than
topic_merge_delta using dbscan. The epsilon parameter of dbscan is
set to the topic_merge_delta.
ngram_vocab: bool (Optional, default False)
Use phrases as topic descriptions.
Uses gensim phrases to find common phrases in the corpus and adds them
to the vocabulary.
For more information visit:
https://radimrehurek.com/gensim/models/phrases.html
ngram_vocab_args: dict (Optional, default None)
Pass custom arguments to gensim phrases.
For more information visit:
https://radimrehurek.com/gensim/models/phrases.html
combine_ngram_vocab: bool (Optional, default False)
If set to True alongside ngram_vocab, then both common words and
common phrases will be added to the vocabulary from which topic labels
are considered.
If using top topic words, leave this disabled. If searching for
documents by individual terms, enable this.
This parameter is ignored when using doc2vec as embedding_model,
behaving as "True".
For more information visit:
https://github.com/ddangelov/Top2Vec/issues/364
embedding_model: string or callable
This will determine which model is used to generate the document and
word embeddings. The valid string options are:
* doc2vec
* universal-sentence-encoder
* universal-sentence-encoder-large
* universal-sentence-encoder-multilingual
* universal-sentence-encoder-multilingual-large
* distiluse-base-multilingual-cased
* all-MiniLM-L6-v2
* paraphrase-multilingual-MiniLM-L12-v2
For large data sets and data sets with very unique vocabulary doc2vec
could produce better results. This will train a doc2vec model from
scratch. This method is language agnostic. However multiple languages
will not be aligned.
Using the universal sentence encoder options will be much faster since
those are pre-trained and efficient models. The universal sentence
encoder options are suggested for smaller data sets. They are also
good options for large data sets that are in English or in languages
covered by the multilingual model. It is also suggested for data sets
that are multilingual.
For more information on universal-sentence-encoder options visit:
https://tfhub.dev/google/collections/universal-sentence-encoder/1
The SBERT pre-trained sentence transformer options are
distiluse-base-multilingual-cased,
paraphrase-multilingual-MiniLM-L12-v2, and all-MiniLM-L6-v2.
The distiluse-base-multilingual-cased and
paraphrase-multilingual-MiniLM-L12-v2 are suggested for multilingual
datasets and languages that are not
covered by the multilingual universal sentence encoder. The
transformer is significantly slower than the universal sentence
encoder options(except for the large options).
For more information on SBERT options visit:
https://www.sbert.net/docs/pretrained_models.html
If passing a callable embedding_model note that it will not be saved
when saving a top2vec model. After loading such a saved top2vec model
the set_embedding_model method will need to be called and the same
embedding_model callable used during training must be passed to it.
embedding_model_path: string (Optional)
Pre-trained embedding models will be downloaded automatically by
default. However they can also be uploaded from a file that is in the
location of embedding_model_path.
Warning: the model at embedding_model_path must match the
embedding_model parameter type.
embedding_batch_size: int (default=32)
Batch size for documents being embedded.
split_documents: bool (default False)
If set to True, documents will be split into parts before embedding.
After embedding the multiple document part embeddings will be averaged
to create a single embedding per document. This is useful when documents
are very large or when the embedding model has a token limit.
Document chunking or a senticizer can be used for document splitting.
document_chunker: string or callable (default 'sequential')
This will break the document into chunks. The valid string options are:
* sequential
* random
The sequential chunker will split the document into chunks of specified
length and ratio of overlap. This is the recommended method.
The random chunking option will take random chunks of specified length
from the document. These can overlap and should be thought of as
sampling chunks with replacement from the document.
If a callable is passed it must take as input a list of tokens of
a document and return a list of strings representing the resulting
document chunks.
Only one of document_chunker or sentincizer should be used.
chunk_length: int (default 100)
The number of tokens per document chunk if using the document chunker
string options.
max_num_chunks: int (Optional)
The maximum number of chunks generated per document if using the
document chunker string options.
chunk_overlap_ratio: float (default 0.5)
Only applies to the 'sequential' document chunker.
Fraction of overlapping tokens between sequential chunks. A value of
0 will result i no overlap, where as 0.5 will overlap half of the
previous chunk.
chunk_len_coverage_ratio: float (default 1.0)
Only applies to the 'random' document chunker option.
Proportion of token length that will be covered by chunks. Default
value of 1.0 means chunk lengths will add up to number of tokens of
the document. This does not mean all tokens will be covered since
chunks can be overlapping.
sentencizer: callable (Optional)
A sentincizer callable can be passed. The input should be a string
representing the document and the output should be a list of strings
representing the document sentence chunks.
Only one of document_chunker or sentincizer should be used.
speed: string (Optional, default 'learn')
This parameter is only used when using doc2vec as embedding_model.
It will determine how fast the model takes to train. The
fast-learn option is the fastest and will generate the lowest quality
vectors. The learn option will learn better quality vectors but take
a longer time to train. The deep-learn option will learn the best
quality vectors but will take significant time to train. The valid
string speed options are:
* fast-learn
* learn
* deep-learn
use_corpus_file: bool (Optional, default False)
This parameter is only used when using doc2vec as embedding_model.
Setting use_corpus_file to True can sometimes provide speedup for
large datasets when multiple worker threads are available. Documents
are still passed to the model as a list of str, the model will create
a temporary corpus file for training.
document_ids: List of str, int (Optional)
A unique value per document that will be used for referring to
documents in search results. If ids are not given to the model, the
index of each document in the original corpus will become the id.
keep_documents: bool (Optional, default True)
If set to False documents will only be used for training and not saved
as part of the model. This will reduce model size. When using search
functions only document ids will be returned, not the actual
documents.
workers: int (Optional)
The amount of worker threads to be used in training the model. Larger
amount will lead to faster training.
tokenizer: callable (Optional, default None)
Override the default tokenization method. If None then
gensim.utils.simple_preprocess will be used.
Tokenizer must take a document and return a list of tokens.
use_embedding_model_tokenizer: bool (Optional, default True)
If using an embedding model other than doc2vec, use the model's
tokenizer for document embedding. If set to True the tokenizer, either
default or passed callable will be used to tokenize the text to
extract the vocabulary for word embedding.
umap_args: dict (Optional, default None)
Pass custom arguments to UMAP.
gpu_umap: bool (default False)
If True umap will use the rapidsai cuml library to perform the
dimensionality reduction. This will lead to a significant speedup
in the computation time during model createion. To install rapidsai
cuml follow the instructions here: https://docs.rapids.ai/install
hdbscan_args: dict (Optional, default None)
Pass custom arguments to HDBSCAN.
gpu_hdbscan: bool (default False)
If True hdbscan will use the rapidsai cuml library to perform the
clustering. This will lead to a significant speedup in the computation
time during model creation. To install rapidsai cuml follow the
instructions here: https://docs.rapids.ai/install
index_topics: bool (Optional, default False)
If True, the topic vectors will be indexed using hnswlib. This will
significantly speed up finding topics during model creation for
very large datasets.
verbose: bool (Optional, default True)
Whether to print status data during training.
"""
def __init__(self,
documents: list[str],
contextual_top2vec=False,
c_top2vec_smoothing_window=5,
min_count=50,
topic_merge_delta=0.1,
ngram_vocab=False,
ngram_vocab_args=None,
combine_ngram_vocab=False,
embedding_model='all-MiniLM-L6-v2',
embedding_model_path=None,
embedding_batch_size=32,
split_documents=False,
document_chunker='sequential',
chunk_length=100,
max_num_chunks=None,
chunk_overlap_ratio=0.5,
chunk_len_coverage_ratio=1.0,
sentencizer=None,
speed='learn',
use_corpus_file=False,
document_ids=None,
keep_documents=True,
workers=None,
tokenizer=None,
use_embedding_model_tokenizer=True,
umap_args=None,
gpu_umap=False,
hdbscan_args=None,
gpu_hdbscan=False,
index_topics=False,
verbose=True
):
if verbose:
logger.setLevel(logging.DEBUG)
self.verbose = True
else:
logger.setLevel(logging.WARNING)
self.verbose = False
if tokenizer is None:
tokenizer = default_tokenizer
# validate documents
if not (isinstance(documents, list) or isinstance(documents, np.ndarray)):
raise ValueError("Documents need to be a list of strings")
if not all((isinstance(doc, str) or isinstance(doc, np.str_)) for doc in documents):
raise ValueError("Documents need to be a list of strings")
if keep_documents:
self.documents = np.array(documents, dtype="object")
self.num_documents = len(documents)
else:
self.documents = None
self.num_documents = 0
# validate document ids
if document_ids is not None:
if not (isinstance(document_ids, list) or isinstance(document_ids, np.ndarray)):
raise ValueError("Documents ids need to be a list of str or int")
if len(documents) != len(document_ids):
raise ValueError("Document ids need to match number of documents")
elif len(document_ids) != len(set(document_ids)):
raise ValueError("Document ids need to be unique")
if all((isinstance(doc_id, str) or isinstance(doc_id, np.str_)) for doc_id in document_ids):
self.doc_id_type = np.str_
elif all((isinstance(doc_id, int) or isinstance(doc_id, np.int_)) for doc_id in document_ids):
self.doc_id_type = np.int_
else:
raise ValueError("Document ids need to be str or int")
self.document_ids_provided = True
self.document_ids = np.array(document_ids)
self.doc_id2index = dict(zip(document_ids, list(range(0, len(document_ids)))))
else:
self.document_ids_provided = False
self.document_ids = np.array(range(0, len(documents)))
self.doc_id2index = dict(zip(self.document_ids, list(range(0, len(self.document_ids)))))
self.doc_id_type = np.int_
self.embedding_model_path = embedding_model_path
self.contextual_top2vec = contextual_top2vec
# validate document splitting
use_sentencizer = False
custom_chunker = False
if split_documents:
if document_chunker == 'sequential':
document_chunker = get_chunks
document_chunker_args = {"chunk_length": chunk_length,
"max_num_chunks": max_num_chunks,
"chunk_overlap_ratio": chunk_overlap_ratio}
elif document_chunker == 'random':
document_chunker = get_random_chunks
document_chunker_args = {"chunk_length": chunk_length,
"max_num_chunks": max_num_chunks,
"chunk_len_coverage_ratio": chunk_len_coverage_ratio}
elif callable(document_chunker):
custom_chunker = True
elif sentencizer is None:
raise ValueError(f"{document_chunker} is an invalid document chunker.")
elif callable(sentencizer):
use_sentencizer = True
else:
raise ValueError(f"{sentencizer} is invalid. Document sentencizer must be callable.")
if embedding_model == 'doc2vec':
# validate training inputs
if speed == "fast-learn":
hs = 0
negative = 5
epochs = 40
elif speed == "learn":
hs = 1
negative = 0
epochs = 40
elif speed == "deep-learn":
hs = 1
negative = 0
epochs = 400
elif speed == "test-learn":
hs = 0
negative = 5
epochs = 1
else:
raise ValueError("speed parameter needs to be one of: fast-learn, learn or deep-learn")
if workers is None:
pass
elif isinstance(workers, int):
pass
else:
raise ValueError("workers needs to be an int")
doc2vec_args = {"vector_size": 300,
"min_count": min_count,
"window": 15,
"sample": 1e-5,
"negative": negative,
"hs": hs,
"epochs": epochs,
"dm": 0,
"dbow_words": 1}
if workers is not None:
doc2vec_args["workers"] = workers
logger.info('Pre-processing documents for training')
if use_corpus_file:
processed = [' '.join(tokenizer(doc)) for doc in documents]
lines = "\n".join(processed)
temp = tempfile.NamedTemporaryFile(mode='w+t')
temp.write(lines)
doc2vec_args["corpus_file"] = temp.name
else:
train_corpus = [TaggedDocument(tokenizer(doc), [i]) for i, doc in enumerate(documents)]
doc2vec_args["documents"] = train_corpus
logger.info('Creating joint document/word embedding')
self.embedding_model = 'doc2vec'
self.model = Doc2Vec(**doc2vec_args)
self.word_vectors = self.model.wv.get_normed_vectors()
self.word_indexes = self.model.wv.key_to_index
self.vocab = list(self.model.wv.key_to_index.keys())
self.document_vectors = self.model.dv.get_normed_vectors()
if ngram_vocab:
tokenized_corpus = [tokenizer(doc) for doc in documents]
if ngram_vocab_args is None:
ngram_vocab_args = {'sentences': tokenized_corpus,
'min_count': 5,
'threshold': 10.0,
'delimiter': ' '}
else:
ngram_vocab_args['sentences'] = tokenized_corpus
ngram_vocab_args['delimiter'] = ' '
phrase_model = Phrases(**ngram_vocab_args)
phrase_results = phrase_model.find_phrases(tokenized_corpus)
phrases = list(phrase_results.keys())
phrases_processed = [tokenizer(phrase) for phrase in phrases]
phrase_vectors = np.vstack([self.model.infer_vector(doc_words=phrase,
alpha=0.025,
min_alpha=0.01,
epochs=100) for phrase in phrases_processed])
phrase_vectors = self._l2_normalize(phrase_vectors)
self.word_vectors = np.vstack([self.word_vectors, phrase_vectors])
self.vocab = self.vocab + phrases
self.word_indexes = dict(zip(self.vocab, range(len(self.vocab))))
if use_corpus_file:
temp.close()
elif ((embedding_model in acceptable_embedding_models) or callable(embedding_model)) and not contextual_top2vec:
self.embed = None
self.embedding_model = embedding_model
self._check_import_status()
logger.info('Pre-processing documents for training')
# preprocess documents
tokenized_corpus = [tokenizer(doc) for doc in documents]
self.vocab = self.get_label_vocabulary(tokenized_corpus,
min_count,
ngram_vocab,
ngram_vocab_args,
combine_ngram_vocab)
self._check_model_status()
logger.info('Creating joint document/word embedding')
# embed words
self.word_indexes = dict(zip(self.vocab, range(len(self.vocab))))
self.word_vectors = self._embed_documents(self.vocab, embedding_batch_size)
# embed documents
# split documents
if split_documents:
if use_sentencizer:
chunk_id = 0
chunked_docs = []
chunked_doc_ids = []
for doc in documents:
doc_chunks = sentencizer(doc)
doc_chunk_ids = [chunk_id] * len(doc_chunks)
chunk_id += 1
chunked_docs.extend(doc_chunks)
chunked_doc_ids.extend(doc_chunk_ids)
else:
chunk_id = 0
chunked_docs = []
chunked_doc_ids = []
for tokens in tokenized_corpus:
if custom_chunker:
doc_chunks = document_chunker(tokens)
else:
doc_chunks = document_chunker(tokens, **document_chunker_args)
doc_chunk_ids = [chunk_id] * len(doc_chunks)
chunk_id += 1
chunked_docs.extend(doc_chunks)
chunked_doc_ids.extend(doc_chunk_ids)
chunked_doc_ids = np.array(chunked_doc_ids)
document_chunk_vectors = self._embed_documents(chunked_docs, embedding_batch_size)
self.document_vectors = self._l2_normalize(
np.vstack([document_chunk_vectors[np.where(chunked_doc_ids == label)[0]]
.mean(axis=0) for label in set(chunked_doc_ids)]))
# original documents
else:
if use_embedding_model_tokenizer:
self.document_vectors = self._embed_documents(documents, embedding_batch_size)
else:
train_corpus = [' '.join(tokens) for tokens in tokenized_corpus]
self.document_vectors = self._embed_documents(train_corpus, embedding_batch_size)
elif contextual_top2vec:
if not embedding_model:
embedding_model = "all-MiniLM-L6-v2"
elif embedding_model not in contextual_top2vec_models:
raise ValueError(f"{embedding_model} is not a valid contextual top2vec model.")
self.contextual_top2vec = True
self.embedding_model = embedding_model
# create contextualized document embeddings
model_name = contextual_top2vec_model_paths[embedding_model]
logger.info('Pre-processing documents for training')
# create vocab
tokenized_corpus = [tokenizer(doc) for doc in documents]
self.vocab = self.get_label_vocabulary(tokenized_corpus,
min_count,
ngram_vocab,
ngram_vocab_args,
combine_ngram_vocab)
logger.info('Creating vocabulary embedding')
self.word_indexes = dict(zip(self.vocab, range(len(self.vocab))))
self.word_vectors = average_embeddings(self.vocab,
batch_size=32,
model_max_length=512,
embedding_model=model_name)
logger.info('Create contextualized document embeddings')
(document_token_embeddings,
document_tokens,
document_labels) = contextual_token_embeddings(documents,
batch_size=32,
model_max_length=512,
embedding_model=model_name)
(averaged_embeddings,
chunk_tokens,
multi_document_labels) = sliding_window_average(document_token_embeddings,
document_tokens,
window_size=50,
stride=40)
self.document_token_embeddings = document_token_embeddings
self.document_vectors = averaged_embeddings
self.document_tokens = document_tokens
self.document_labels = document_labels
self.multi_document_labels = multi_document_labels
if not umap_args:
umap_args = {
'n_neighbors': 50,
'n_components': 5,
'metric': 'euclidean'}
if not hdbscan_args:
hdbscan_args = {
'min_cluster_size': 15}
else:
raise ValueError(f"{embedding_model} is an invalid embedding model.")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
self.c_top2vec_smoothing_window = c_top2vec_smoothing_window
# initialize topic indexing variables
self.topic_index = None
self.serialized_topic_index = None
self.topics_indexed = False
self.compute_topics(umap_args=umap_args,
hdbscan_args=hdbscan_args,
topic_merge_delta=topic_merge_delta,
gpu_umap=gpu_umap,
gpu_hdbscan=gpu_hdbscan,
index_topics=index_topics,
contextual_top2vec=contextual_top2vec,
c_top2vec_smoothing_window=c_top2vec_smoothing_window)
# initialize document indexing variables
self.document_index = None
self.serialized_document_index = None
self.documents_indexed = False
self.index_id2doc_id = None
self.doc_id2index_id = None
# initialize word indexing variables
self.word_index = None
self.serialized_word_index = None
self.words_indexed = False
def calculate_documents_topic_distributions(self,
topic_vectors,
stacked_document_embeddings,
document_labels):
doc_top, doc_dist = self._calculate_documents_topic(topic_vectors=topic_vectors,
document_vectors=stacked_document_embeddings)
topic_sizes = pd.Series(doc_top).value_counts()
# Ensure doc_top and doc_dist are numpy arrays
doc_top = np.array(doc_top)
doc_dist = np.array(doc_dist)
# Preallocate arrays
doc_top_tokens = dict()
doc_top_token_dists = dict() # New dictionary to store scores instead of indices
doc_topic_distribution = np.zeros((self.num_documents, len(topic_vectors)))
doc_topic_scores = np.zeros((self.num_documents, len(topic_vectors)))
# Convert document labels to numpy array for fast indexing
document_labels = np.array(document_labels)
# Iterate over unique document labels
for doc_ind in tqdm(np.unique(document_labels), desc="Calculating document topic distributions"):
# Get indices and relevant data for the current document
doc_inds = np.where(document_labels == doc_ind)[0]
token_topics = doc_top[doc_inds]
token_scores = doc_dist[doc_inds]
doc_num_tokens = len(doc_inds)
doc_top_tokens[doc_ind] = dict()
doc_top_token_dists[doc_ind] = dict() # Initialize for each document
# Find unique topics and their counts in the current document
unique_topics, topic_counts = np.unique(token_topics, return_counts=True)
mean_scores = np.array([token_scores[token_topics == topic].mean() for topic in unique_topics])
# Update doc_top_tokens, doc_top_token_dists, and calculate topic distribution and score
for i, topic in enumerate(unique_topics):
topic_inds = np.where(token_topics == topic)[0]
# Store indices in doc_top_tokens as before
doc_top_tokens[doc_ind][topic] = topic_inds
# Store corresponding scores in doc_top_token_dists
doc_top_token_dists[doc_ind][topic] = token_scores[topic_inds]
# Calculate topic distribution and mean score
doc_topic_distribution[doc_ind, topic] = topic_counts[i] / doc_num_tokens
doc_topic_scores[doc_ind, topic] = mean_scores[i]
return doc_top_tokens, doc_topic_distribution, doc_topic_scores, doc_top_token_dists, topic_sizes
@staticmethod
def get_label_vocabulary(tokenized_corpus,
min_count,
ngram_vocab,
ngram_vocab_args,
combine_ngram_vocab):
def return_doc(doc):
return doc
# preprocess vocabulary
vectorizer = CountVectorizer(tokenizer=return_doc, preprocessor=return_doc)
doc_word_counts = vectorizer.fit_transform(tokenized_corpus)
words = vectorizer.get_feature_names_out()
word_counts = np.array(np.sum(doc_word_counts, axis=0).tolist()[0])
vocab_inds = np.where(word_counts > min_count)[0]
if len(vocab_inds) == 0:
raise ValueError(f"A min_count of {min_count} results in "
f"all words being ignored, choose a lower value.")
vocab = [words[ind] for ind in vocab_inds]
if ngram_vocab:
if ngram_vocab_args is None:
ngram_vocab_args = {'sentences': tokenized_corpus,
'min_count': 5,
'threshold': 10.0,
'delimiter': ' '}
else:
ngram_vocab_args['sentences'] = tokenized_corpus
ngram_vocab_args['delimiter'] = ' '
phrase_model = Phrases(**ngram_vocab_args)
phrase_results = phrase_model.find_phrases(tokenized_corpus)
phrases = list(phrase_results.keys())
if combine_ngram_vocab:
vocab += phrases
else:
vocab = phrases
return vocab
def save(self, file):
"""
Saves the current model to the specified file.
Parameters
----------
file: str
File where model will be saved.
"""
document_index_temp = None
word_index_temp = None
topic_index_temp = None
# do not save sentence encoders, sentence transformers and custom embedding
if self.embedding_model not in ["doc2vec"]:
self.embed = None
# serialize document index so that it can be saved
if self.documents_indexed:
temp = tempfile.NamedTemporaryFile(mode='w+b')
self.document_index.save_index(temp.name)
self.serialized_document_index = temp.read()
temp.close()
document_index_temp = self.document_index
self.document_index = None
# serialize word index so that it can be saved
if self.words_indexed:
temp = tempfile.NamedTemporaryFile(mode='w+b')
self.word_index.save_index(temp.name)
self.serialized_word_index = temp.read()
temp.close()
word_index_temp = self.word_index
self.word_index = None
# serialize word index so that it can be saved
if self.topics_indexed:
temp = tempfile.NamedTemporaryFile(mode='w+b')
self.topic_index.save_index(temp.name)
self.serialized_topic_index = temp.read()
temp.close()
topic_index_temp = self.topic_index
self.topic_index = None
dump(self, file)
self.document_index = document_index_temp
self.word_index = word_index_temp
self.topic_index = topic_index_temp
@classmethod
def load(cls, file):
"""
Load a pre-trained model from the specified file.
Parameters
----------
file: str
File where model will be loaded from.
"""
top2vec_model = load(file)
# load document index
if top2vec_model.documents_indexed:
if not _HAVE_HNSWLIB:
raise ImportError(f"Cannot load document index.\n\n"
"Try: pip install top2vec[indexing]\n\n"
"Alternatively try: pip install hnswlib")
temp = tempfile.NamedTemporaryFile(mode='w+b')
temp.write(top2vec_model.serialized_document_index)