forked from pycaret/pycaret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nlp.py
2826 lines (1985 loc) · 89.7 KB
/
nlp.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
# Module: Natural Language Processing
# Author: Moez Ali <moez.ali@queensu.ca>
# License: MIT
def setup(data,
target=None,
custom_stopwords=None,
session_id = None):
"""
Description:
------------
This function initializes the environment in pycaret. setup() must called before
executing any other function in pycaret. It takes one mandatory parameter:
dataframe {array-like, sparse matrix} or object of type list. If a dataframe is
passed, target column containing text must be specified. When data passed is of
type list, no target parameter is required. All other parameters are optional.
This module only supports English Language at this time.
Example
-------
from pycaret.datasets import get_data
kiva = get_data('kiva')
experiment_name = setup(data = kiva, target = 'en')
'kiva' is a pandas Dataframe.
Parameters
----------
data : {array-like, sparse matrix}, shape (n_samples, n_features) where n_samples
is the number of samples and n_features is the number of features or object of type
list with n length.
target: string
If data is of type DataFrame, name of column containing text values must be passed as
string.
custom_stopwords: list, default = None
list containing custom stopwords.
session_id: int, default = None
If None, a random seed is generated and returned in the Information grid. The
unique number is then distributed as a seed in all functions used during the
experiment. This can be used for later reproducibility of the entire experiment.
Returns:
--------
info grid: Information grid is printed.
-----------
environment: This function returns various outputs that are stored in variable
----------- as tuple. They are used by other functions in pycaret.
Warnings:
---------
- Some functionalities in pycaret.nlp requires you to have english language model.
The language model is not downloaded automatically when you install pycaret.
You will have to download two models using your Anaconda Prompt or python
command line interface. To download the model, please type the following in
your command line:
python -m spacy download en_core_web_sm
python -m textblob.download_corpora
Once downloaded, please restart your kernel and re-run the setup.
"""
#exception checking
import sys
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
"""
error handling starts here
"""
#checking data type
if hasattr(data,'shape') is False:
if type(data) is not list:
sys.exit('(Type Error): data passed must be of type pandas.DataFrame or list')
#if dataframe is passed then target is mandatory
if hasattr(data,'shape'):
if target is None:
sys.exit('(Type Error): When DataFrame is passed as data param. Target column containing text must be specified in target param.')
#checking target parameter
if target is not None:
if target not in data.columns:
sys.exit('(Value Error): Target parameter doesnt exist in the data provided.')
#custom stopwords checking
if custom_stopwords is not None:
if type(custom_stopwords) is not list:
sys.exit('(Type Error): custom_stopwords must be of list type.')
#checking session_id
if session_id is not None:
if type(session_id) is not int:
sys.exit('(Type Error): session_id parameter must be an integer.')
#chcek if spacy is loaded
try:
import spacy
sp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])
except:
sys.exit('(Type Error): spacy english model is not yet downloaded. See the documentation of setup to see installation guide.')
"""
error handling ends here
"""
#pre-load libraries
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
'''
generate monitor starts
'''
#progress bar
max_steps = 11
total_steps = 9
progress = ipw.IntProgress(value=0, min=0, max=max_steps, step=1 , description='Processing: ')
display(progress)
try:
max_sub = len(data[target].values.tolist())
except:
max_sub = len(data)
#sub_progress = ipw.IntProgress(value=0, min=0, max=max_sub, step=1, bar_style='', description='Sub Process: ')
#display(sub_progress)
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Loading Dependencies' ],
['Step' , '. . . . . . . . . . . . . . . . . .', 'Step 0 of ' + str(total_steps)] ],
columns=['', ' ', ' ']).set_index('')
display(monitor, display_id = 'monitor')
'''
generate monitor end
'''
#general dependencies
import numpy as np
import random
import spacy
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
import spacy
import re
#defining global variables
global text, id2word, corpus, data_, seed, target_, experiment__
#create an empty list for pickling later.
try:
experiment__.append('dummy')
experiment__.pop()
except:
experiment__ = []
#converting to dataframe if list provided
if type(data) is list:
data = pd.DataFrame(data, columns=['en'])
target = 'en'
#converting target column into list
try:
text = data[target].values.tolist()
target_ = str(target)
except:
text = data
target_ = 'en'
#generate seed to be used globally
if session_id is None:
seed = random.randint(150,9000)
else:
seed = session_id
#copying dataframe
if type(data) is list:
data_ = pd.DataFrame(data)
data_.columns = ['en']
else:
data_ = data.copy()
progress.value += 1
"""
DEFINE STOPWORDS
"""
try:
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
stop_words = stopwords.words('english')
except:
stop_words = ['ourselves', 'hers', 'between', 'yourself', 'but', 'again', 'there', 'about', 'once', 'during',
'out', 'very', 'having', 'with', 'they', 'own', 'an', 'be', 'some', 'for', 'do', 'its', 'yours',
'such', 'into', 'of', 'most', 'itself', 'other', 'off', 'is', 's', 'am', 'or', 'who', 'as', 'from',
'him', 'each', 'the', 'themselves', 'until', 'below', 'are', 'we', 'these', 'your', 'his', 'through',
'don', 'nor', 'me', 'were', 'her', 'more', 'himself', 'this', 'down', 'should', 'our', 'their', 'while',
'above', 'both', 'up', 'to', 'ours', 'had', 'she', 'all', 'no', 'when', 'at', 'any', 'before', 'them',
'same', 'and', 'been', 'have', 'in', 'will', 'on', 'does', 'yourselves', 'then', 'that', 'because', 'what',
'over', 'why', 'so', 'can', 'did', 'not', 'now', 'under', 'he', 'you', 'herself', 'has', 'just', 'where',
'too', 'only', 'myself', 'which', 'those', 'i', 'after', 'few', 'whom', 't', 'being', 'if', 'theirs', 'my',
'against', 'a', 'by', 'doing', 'it', 'how', 'further', 'was', 'here', 'than']
if custom_stopwords is not None:
stop_words = stop_words + custom_stopwords
progress.value += 1
"""
TEXT PRE-PROCESSING STARTS HERE
"""
"""
STEP 1 - REMOVE NUMERIC CHARACTERS FROM THE LIST
"""
monitor.iloc[1,1:] = 'Removing Numeric Characters'
monitor.iloc[2,1:] = 'Step 1 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
text_step1 = []
for i in range(0,len(text)):
review = re.sub("\d+", "", str(text[i]))
text_step1.append(review)
#sub_progress.value += 1
#sub_progress.value = 0
text = text_step1 #re-assigning
del(text_step1)
progress.value += 1
"""
STEP 2 - REGULAR EXPRESSIONS
"""
monitor.iloc[1,1:] = 'Removing Special Characters'
monitor.iloc[2,1:] = 'Step 2 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
text_step2 = []
for i in range(0,len(text)):
review = re.sub(r'\W', ' ', str(text[i]))
review = review.lower()
review = re.sub(r'\s+[a-z]\s+', ' ', review)
review = re.sub(r'^[a-z]\s+', ' ', review)
review = re.sub(r'\d+', ' ', review)
review = re.sub(r'\s+', ' ', review)
text_step2.append(review)
#sub_progress.value += 1
#sub_progress.value = 0
text = text_step2 #re-assigning
del(text_step2)
progress.value += 1
"""
STEP 3 - WORD TOKENIZATION
"""
monitor.iloc[1,1:] = 'Tokenizing Words'
monitor.iloc[2,1:] = 'Step 3 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
text_step3 = []
for i in text:
review = gensim.utils.simple_preprocess(str(i), deacc=True)
text_step3.append(review)
#sub_progress.value += 1
#sub_progress.value = 0
text = text_step3
del(text_step3)
progress.value += 1
"""
STEP 4 - REMOVE STOPWORDS
"""
monitor.iloc[1,1:] = 'Removing Stopwords'
monitor.iloc[2,1:] = 'Step 4 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
text_step4 = []
for i in text:
ii = []
for word in i:
if word not in stop_words:
ii.append(word)
text_step4.append(ii)
#sub_progress.value += 1
text = text_step4
del(text_step4)
#sub_progress.value = 0
progress.value += 1
"""
STEP 5 - BIGRAM EXTRACTION
"""
monitor.iloc[1,1:] = 'Extracting Bigrams'
monitor.iloc[2,1:] = 'Step 5 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
bigram = gensim.models.Phrases(text, min_count=5, threshold=100)
bigram_mod = gensim.models.phrases.Phraser(bigram)
text_step5 = []
for i in text:
text_step5.append(bigram_mod[i])
#sub_progress.value += 1
text = text_step5
del(text_step5)
#sub_progress.value = 0
progress.value += 1
"""
STEP 6 - TRIGRAM EXTRACTION
"""
monitor.iloc[1,1:] = 'Extracting Trigrams'
monitor.iloc[2,1:] = 'Step 6 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
trigram = gensim.models.Phrases(bigram[text], threshold=100)
trigram_mod = gensim.models.phrases.Phraser(trigram)
text_step6 = []
for i in text:
text_step6.append(trigram_mod[bigram_mod[i]])
#sub_progress.value += 1
#sub_progress.value = 0
text = text_step6
del(text_step6)
progress.value += 1
"""
STEP 7 - LEMMATIZATION USING SPACY
"""
monitor.iloc[1,1:] = 'Lemmatizing'
monitor.iloc[2,1:] = 'Step 7 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])
allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']
text_step7 = []
for i in text:
doc = nlp(" ".join(i))
text_step7.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
#sub_progress.value += 1
#sub_progress.value = 0
text = text_step7
del(text_step7)
progress.value += 1
"""
STEP 8 - CUSTOM STOPWORD REMOVER
"""
monitor.iloc[1,1:] = 'Removing Custom Stopwords'
monitor.iloc[2,1:] = 'Step 8 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
text_step8 = []
for i in text:
ii = []
for word in i:
if word not in stop_words:
ii.append(word)
text_step8.append(ii)
#sub_progress.value += 1
text = text_step8
del(text_step8)
#sub_progress.value = 0
progress.value += 1
"""
STEP 8 - CREATING CORPUS AND DICTIONARY
"""
monitor.iloc[1,1:] = 'Compiling Corpus'
monitor.iloc[2,1:] = 'Step 9 of '+ str(total_steps)
update_display(monitor, display_id = 'monitor')
#creating dictionary
id2word = corpora.Dictionary(text)
#creating corpus
corpus = []
for i in text:
d = id2word.doc2bow(i)
corpus.append(d)
#sub_progress.value += 1
#sub_progress.value = 0
progress.value += 1
"""
PROGRESS NOT YET TRACKED - TO BE CODED LATER
"""
text_join = []
for i in text:
word = ' '.join(i)
text_join.append(word)
data_[target_] = text_join
'''
Final display Starts
'''
clear_output()
if custom_stopwords is None:
csw = False
else:
csw = True
functions = pd.DataFrame ( [ ['session_id', seed ],
['# Documents', len(corpus) ],
['Vocab Size',len(id2word.keys()) ],
['Custom Stopwords',csw ],
], columns = ['Description', 'Value'] )
functions_ = functions.style.hide_index()
display(functions_)
'''
Final display Ends
'''
#log into experiment
experiment__.append(('Info', functions))
experiment__.append(('Dataset', data_))
experiment__.append(('Corpus', corpus))
experiment__.append(('Dictionary', id2word))
experiment__.append(('Text', text))
return text, data_, corpus, id2word, seed, target_, experiment__
def create_model(model=None,
multi_core=False,
num_topics = None,
verbose=True):
"""
Description:
------------
This function creates a model on the dataset passed as a data param during
the setup stage. setup() function must be called before using create_model().
This function returns a trained model object.
Example
-------
from pycaret.datasets import get_data
kiva = get_data('kiva')
experiment_name = setup(data = kiva, target = 'en')
lda = create_model('lda')
This will return trained Latent Dirichlet Allocation model.
Parameters
----------
model : string, default = None
Enter abbreviated string of the model class. List of models supported:
Model Abbreviated String Original Implementation
--------- ------------------ -----------------------
Latent Dirichlet Allocation 'lda' gensim/models/ldamodel.html
Latent Semantic Indexing 'lsi' gensim/models/lsimodel.html
Hierarchical Dirichlet Process 'hdp' gensim/models/hdpmodel.html
Random Projections 'rp' gensim/models/rpmodel.html
Non-Negative Matrix Factorization 'nmf' sklearn.decomposition.NMF.html
multi_core: Boolean, default = False
True would utilize all CPU cores to parallelize and speed up model training. Only
available for 'lda'. For all other models, the multi_core parameter is ignored.
num_topics: integer, default = 4
Number of topics to be created. If None, default is set to 4.
verbose: Boolean, default = True
Status update is not printed when verbose is set to False.
Returns:
--------
model: trained model object
------
Warnings:
---------
None
"""
#exception checking
import sys
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
"""
error handling starts here
"""
#checking for model parameter
if model is None:
sys.exit('(Value Error): Model parameter Missing. Please see docstring for list of available models.')
#checking for allowed models
allowed_models = ['lda', 'lsi', 'hdp', 'rp', 'nmf']
if model not in allowed_models:
sys.exit('(Value Error): Model Not Available. Please see docstring for list of available models.')
#checking multicore type:
if type(multi_core) is not bool:
sys.exit('(Type Error): multi_core parameter can only take argument as True or False.')
#checking round parameter
if num_topics is not None:
if type(num_topics) is not int:
sys.exit('(Type Error): num_topics parameter only accepts integer value.')
#checking verbose parameter
if type(verbose) is not bool:
sys.exit('(Type Error): Verbose parameter can only take argument as True or False.')
"""
error handling ends here
"""
#pre-load libraries
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
"""
monitor starts
"""
#progress bar and monitor control
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
progress = ipw.IntProgress(value=0, min=0, max=4, step=1 , description='Processing: ')
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Initializing'] ],
columns=['', ' ', ' ']).set_index('')
if verbose:
display(progress)
display(monitor, display_id = 'monitor')
progress.value += 1
"""
monitor starts
"""
#define topic_model_name
if model == 'lda':
topic_model_name = 'Latent Dirichlet Allocation'
elif model == 'lsi':
topic_model_name = 'Latent Semantic Indexing'
elif model == 'hdp':
topic_model_name = 'Hierarchical Dirichlet Process'
elif model == 'nmf':
topic_model_name = 'Non-Negative Matrix Factorization'
elif model == 'rp':
topic_model_name = 'Random Projections'
#defining default number of topics
if num_topics is None:
n_topics = 4
else:
n_topics = num_topics
#monitor update
monitor.iloc[1,1:] = 'Fitting Topic Model'
progress.value += 1
if verbose:
update_display(monitor, display_id = 'monitor')
if model == 'lda':
if multi_core:
from gensim.models.ldamulticore import LdaMulticore
model = LdaMulticore(corpus=corpus,
num_topics=n_topics,
id2word=id2word,
workers=4,
random_state=seed,
chunksize=100,
passes=10,
alpha= 'symmetric',
per_word_topics=True)
progress.value += 1
else:
from gensim.models.ldamodel import LdaModel
model = LdaModel(corpus=corpus,
num_topics=n_topics,
id2word=id2word,
random_state=seed,
update_every=1,
chunksize=100,
passes=10,
alpha='auto',
per_word_topics=True)
progress.value += 1
elif model == 'lsi':
from gensim.models.lsimodel import LsiModel
model = LsiModel(corpus=corpus,
num_topics=n_topics,
id2word=id2word)
progress.value += 1
elif model == 'hdp':
from gensim.models import HdpModel
model = HdpModel(corpus=corpus,
id2word=id2word,
random_state=seed,
chunksize=100,
T=n_topics)
progress.value += 1
elif model == 'rp':
from gensim.models import RpModel
model = RpModel(corpus=corpus,
id2word=id2word,
num_topics=n_topics)
progress.value += 1
elif model == 'nmf':
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.decomposition import NMF
from sklearn.preprocessing import normalize
text_join = []
for i in text:
word = ' '.join(i)
text_join.append(word)
progress.value += 1
vectorizer = CountVectorizer(analyzer='word', max_features=5000)
x_counts = vectorizer.fit_transform(text_join)
transformer = TfidfTransformer(smooth_idf=False);
x_tfidf = transformer.fit_transform(x_counts);
xtfidf_norm = normalize(x_tfidf, norm='l1', axis=1)
model = NMF(n_components=n_topics, init='nndsvd', random_state=seed);
model.fit(xtfidf_norm)
progress.value += 1
#storing into experiment
if verbose:
clear_output()
tup = (topic_model_name,model)
experiment__.append(tup)
return model
def assign_model(model,
verbose=True):
"""
Description:
------------
This function assigns each of the data point in the dataset passed during setup
stage to one of the topic using trained model object passed as model param.
create_model() function must be called before using assign_model().
This function returns dataframe with topic weights, dominant topic and % of the
dominant topic (where applicable).
Example
-------
from pycaret.datasets import get_data
kiva = get_data('kiva')
experiment_name = setup(data = kiva, target = 'en')
lda = create_model('lda')
lda_df = assign_model(lda)
This will return a dataframe with inferred topics using trained model.
Parameters
----------
model : trained model object, default = None
verbose: Boolean, default = True
Status update is not printed when verbose is set to False.
Returns:
--------
dataframe: Returns dataframe with inferred topics using trained model object.
---------
Warnings:
---------
None
"""
#determine model type
if 'LdaModel' in str(type(model)):
mod_type = 'lda'
elif 'LdaMulticore' in str(type(model)):
mod_type = 'lda'
elif 'LsiModel' in str(type(model)):
mod_type = 'lsi'
elif 'NMF' in str(type(model)):
mod_type = 'nmf'
elif 'HdpModel' in str(type(model)):
mod_type = 'hdp'
elif 'RpModel' in str(type(model)):
mod_type = 'rp'
else:
mod_type = None
#exception checking
import sys
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
"""
error handling starts here
"""
#checking for allowed models
allowed_models = ['lda', 'lsi', 'hdp', 'rp', 'nmf']
if mod_type not in allowed_models:
sys.exit('(Value Error): Model Not Recognized. Please see docstring for list of available models.')
#checking verbose parameter
if type(verbose) is not bool:
sys.exit('(Type Error): Verbose parameter can only take argument as True or False.')
"""
error handling ends here
"""
#pre-load libraries
import numpy as np
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
#progress bar and monitor control
max_progress = len(text) + 5
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
progress = ipw.IntProgress(value=0, min=0, max=max_progress, step=1 , description='Processing: ')
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Initializing'] ],
columns=['', ' ', ' ']).set_index('')
if verbose:
display(progress)
display(monitor, display_id = 'monitor')
progress.value += 1
monitor.iloc[1,1:] = 'Extracting Topics from Model'
if verbose:
update_display(monitor, display_id = 'monitor')
progress.value += 1
#assignment starts here
if mod_type == 'lda':
c = model.get_document_topics(corpus, minimum_probability=0)
ls = []
for i in range(len(c)):
ls.append(c[i])
bb = []
for i in ls:
bs = []
for k in i:
progress.value += 1
bs.append(k[1])
bb.append(bs)
Dominant_Topic = []
for i in bb:
max_ = max(i)
max_ = i.index(max_)
Dominant_Topic.append('Topic ' + str(max_))
pdt = []
for i in range(0,len(bb)):
l = max(bb[i]) / sum(bb[i])
pdt.append(round(l,2))
col_names = []
for i in range(len(model.show_topics(num_topics=999999))):
a = 'Topic_' + str(i)
col_names.append(a)
progress.value += 1
bb = pd.DataFrame(bb,columns=col_names)
bb_ = pd.concat([data_,bb], axis=1)
dt_ = pd.DataFrame(Dominant_Topic, columns=['Dominant_Topic'])
bb_ = pd.concat([bb_,dt_], axis=1)
pdt_ = pd.DataFrame(pdt, columns=['Perc_Dominant_Topic'])
bb_ = pd.concat([bb_,pdt_], axis=1)
progress.value += 1
if verbose:
clear_output()
#return bb_
elif mod_type == 'lsi':
col_names = []
for i in range(0,len(model.print_topics(num_topics=999999))):
a = 'Topic_' + str(i)
col_names.append(a)
df_ = pd.DataFrame()
Dominant_Topic = []
for i in range(0,len(text)):
progress.value += 1
db = id2word.doc2bow(text[i])
db_ = model[db]
db_array = np.array(db_)
db_array_ = db_array[:,1]
max_ = max(db_array_)
max_ = list(db_array_).index(max_)
Dominant_Topic.append('Topic ' + str(max_))
db_df_ = pd.DataFrame([db_array_])
df_ = pd.concat([df_,db_df_])
progress.value += 1
df_.columns = col_names
df_['Dominant_Topic'] = Dominant_Topic
df_ = df_.reset_index(drop=True)
bb_ = pd.concat([data_,df_], axis=1)
progress.value += 1
if verbose:
clear_output()
#return bb_
elif mod_type == 'hdp' or mod_type == 'rp':
rate = []
for i in range(0,len(corpus)):
progress.value += 1
rate.append(model[corpus[i]])
topic_num = []
topic_weight = []
doc_num = []
counter = 0
for i in rate:
for k in i:
topic_num.append(k[0])
topic_weight.append(k[1])
doc_num.append(counter)
counter += 1
progress.value += 1