/
__init__.py
2947 lines (2505 loc) · 104 KB
/
__init__.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
# -*- coding: utf-8 -*-
"""
This is the main module containing the implementation of the SS3 classifier.
(Please, visit https://github.com/sergioburdisso/pyss3 for more info)
"""
from __future__ import print_function
import os
import re
import json
import errno
import numbers
import numpy as np
from io import open
from time import time
from tqdm import tqdm
from math import pow, tanh, log
from sklearn.feature_extraction.text import CountVectorizer
from .util import is_a_collection, Print, VERBOSITY, Preproc as Pp
# python 2 and 3 compatibility
from functools import reduce
from six.moves import xrange
__version__ = "0.6.4"
ENCODING = "utf-8"
PARA_DELTR = "\n"
SENT_DELTR = r"\."
WORD_DELTR = r"\s"
WORD_REGEX = r"\w+(?:'\w+)?"
STR_UNKNOWN, STR_MOST_PROBABLE = "unknown", "most-probable"
STR_OTHERS_CATEGORY = "[others]"
STR_UNKNOWN_CATEGORY = "[unknown]"
IDX_UNKNOWN_CATEGORY = -1
STR_UNKNOWN_WORD = ''
IDX_UNKNOWN_WORD = -1
STR_VANILLA, STR_XAI = "vanilla", "xai"
STR_GV, STR_NORM_GV, STR_NORM_GV_XAI = "gv", "norm_gv", "norm_gv_xai"
STR_MODEL_FOLDER = "ss3_models"
STR_MODEL_EXT = "ss3m"
WEIGHT_SCHEMES_SS3 = ['only_cat', 'diff_all', 'diff_max', 'diff_median', 'diff_mean']
WEIGHT_SCHEMES_TF = ['binary', 'raw_count', 'term_freq', 'log_norm', 'double_norm']
VERBOSITY = VERBOSITY # to allow "from pyss3 import VERBOSITY"
NAME = 0
VOCAB = 1
NEXT = 0
FR = 1
CV = 2
SG = 3
GV = 4
LV = 5
EMPTY_WORD_INFO = [0, 0, 0, 0, 0, 0]
NOISE_FR = 1
MIN_MAD_SD = .03
class SS3:
"""
The SS3 classifier class.
The SS3 classifier was originally defined in Section 3 of
https://dx.doi.org/10.1016/j.eswa.2019.05.023
(preprint avialable here: https://arxiv.org/abs/1905.08772)
:param s: the "smoothness"(sigma) hyperparameter value
:type s: float
:param l: the "significance"(lambda) hyperparameter value
:type l: float
:param p: the "sanction"(rho) hyperparameter value
:type p: float
:param a: the alpha hyperparameter value (i.e. all terms with a
confidence value (cv) less than alpha will be ignored during
classification)
:type a: float
:param name: the model's name (to save and load the model from disk)
:type name: str
:param cv_m: method used to compute the confidence value (cv) of each
term (word or n-grams), options are:
"norm_gv_xai", "norm_gv" and "gv" (default: "norm_gv_xai")
:type cv_m: str
:param sg_m: method used to compute the significance (sg) function, options
are: "vanilla" and "xai" (default: "xai")
:type sg_m: str
"""
__name__ = "model"
__models_folder__ = STR_MODEL_FOLDER
__s__ = .45
__l__ = .5
__p__ = 1
__a__ = .0
__multilabel__ = False
__l_update__ = None
__s_update__ = None
__p_update__ = None
__cv_cache__ = None
__last_x_test__ = None
__last_x_test_idx__ = None
__prun_floor__ = 10
__prun_trigger__ = 1000000
__prun_counter__ = 0
__zero_cv__ = None
__parag_delimiter__ = PARA_DELTR
__sent_delimiter__ = SENT_DELTR
__word_delimiter__ = WORD_DELTR
__word_regex__ = WORD_REGEX
def __init__(
self, s=None, l=None, p=None, a=None,
name="", cv_m=STR_NORM_GV_XAI, sg_m=STR_XAI
):
"""
Class constructor.
:param s: the "smoothness"(sigma) hyperparameter value
:type s: float
:param l: the "significance"(lambda) hyperparameter value
:type l: float
:param p: the "sanction"(rho) hyperparameter value
:type p: float
:param a: the alpha hyperparameter value (i.e. all terms with a
confidence value (cv) less than alpha will be ignored during
classification)
:type a: float
:param name: the model's name (to save and load the model from disk)
:type name: str
:param cv_m: method used to compute the confidence value (cv) of each
term (word or n-grams), options are:
"norm_gv_xai", "norm_gv" and "gv" (default: "norm_gv_xai")
:type cv_m: str
:param sg_m: method used to compute the significance (sg) function, options
are: "vanilla" and "xai" (default: "xai")
:type sg_m: str
:raises: ValueError
"""
self.__name__ = (name or self.__name__).lower()
self.__s__ = self.__s__ if s is None else s
self.__l__ = self.__l__ if l is None else l
self.__p__ = self.__p__ if p is None else p
self.__a__ = self.__a__ if a is None else a
try:
float(self.__s__ + self.__l__ + self.__p__ + self.__a__)
except BaseException:
raise ValueError("hyperparameter values must be numbers")
self.__categories_index__ = {}
self.__categories__ = []
self.__max_fr__ = []
self.__max_gv__ = []
self.__index_to_word__ = {}
self.__word_to_index__ = {}
if cv_m == STR_NORM_GV_XAI:
self.__cv__ = self.__cv_norm_gv_xai__
elif cv_m == STR_NORM_GV:
self.__cv__ = self.__cv_norm_gv__
elif cv_m == STR_GV:
self.__cv__ = self.__gv__
if sg_m == STR_XAI:
self.__sg__ = self.__sg_xai__
elif sg_m == STR_VANILLA:
self.__sg__ = self.__sg_vanilla__
self.__cv_mode__ = cv_m
self.__sg_mode__ = sg_m
self.original_sumop_ngrams = self.summary_op_ngrams
self.original_sumop_sentences = self.summary_op_sentences
self.original_sumop_paragraphs = self.summary_op_paragraphs
def __lv__(self, ngram, icat, cache=True):
"""Local value function."""
if cache:
return self.__trie_node__(ngram, icat)[LV]
else:
try:
ilength = len(ngram) - 1
fr = self.__trie_node__(ngram, icat)[FR]
if fr > NOISE_FR:
max_fr = self.__max_fr__[icat][ilength]
local_value = (fr / float(max_fr)) ** self.__s__
return local_value
else:
return 0
except TypeError:
return 0
except IndexError:
return 0
def __sn__(self, ngram, icat):
"""The sanction (sn) function."""
m_values = [
self.__sg__(ngram, ic)
for ic in xrange(len(self.__categories__)) if ic != icat
]
c = len(self.__categories__)
s = sum([min(v, 1) for v in m_values])
try:
return pow((c - (s + 1)) / ((c - 1) * (s + 1)), self.__p__)
except ZeroDivisionError: # if c <= 1
return 1.
def __sg_vanilla__(self, ngram, icat, cache=True):
"""The original significance (sg) function definition."""
try:
if cache:
return self.__trie_node__(ngram, icat)[SG]
else:
ncats = len(self.__categories__)
l = self.__l__
lvs = [self.__lv__(ngram, ic) for ic in xrange(ncats)]
lv = lvs[icat]
M, sd = mad(lvs, ncats)
if not sd and lv:
return 1.
else:
return sigmoid(lv - M, l * sd)
except TypeError:
return 0.
def __sg_xai__(self, ngram, icat, cache=True):
"""
A variation of the significance (sn) function.
This version of the sg function adds extra checks to
improve visual explanations.
"""
try:
if cache:
return self.__trie_node__(ngram, icat)[SG]
else:
ncats = len(self.__categories__)
l = self.__l__
lvs = [self.__lv__(ngram, ic) for ic in xrange(ncats)]
lv = lvs[icat]
M, sd = mad(lvs, ncats)
if l * sd <= MIN_MAD_SD:
sd = MIN_MAD_SD / l if l else 0
# stopwords filter
stopword = (M > .2) or (
sum(map(lambda v: v > 0.09, lvs)) == ncats
)
if (stopword and sd <= .1) or (M >= .3):
return 0.
if not sd and lv:
return 1.
return sigmoid(lv - M, l * sd)
except TypeError:
return 0.
def __gv__(self, ngram, icat, cache=True):
"""
The global value (gv) function.
This is the original way of computing the confidence value (cv)
of a term.
"""
if cache:
return self.__trie_node__(ngram, icat)[GV]
else:
lv = self.__lv__(ngram, icat)
weight = self.__sg__(ngram, icat) * self.__sn__(ngram, icat)
return lv * weight
def __cv_norm_gv__(self, ngram, icat, cache=True):
"""
Alternative way of computing the confidence value (cv) of terms.
This variations normalizes the gv value and uses that value as the cv.
"""
try:
if cache:
return self.__trie_node__(ngram, icat)[CV]
else:
try:
cv = self.__gv__(ngram, icat)
return cv / self.__max_gv__[icat][len(ngram) - 1]
except (ZeroDivisionError, IndexError):
return .0
except TypeError:
return 0
def __cv_norm_gv_xai__(self, ngram, icat, cache=True):
"""
Alternative way of computing the confidence value (cv) of terms.
This variations not only normalizes the gv value but also adds extra
checks to improve visual explanations.
"""
try:
if cache:
return self.__trie_node__(ngram, icat)[CV]
else:
try:
max_gv = self.__max_gv__[icat][len(ngram) - 1]
if (len(ngram) > 1):
# stopwords guard
n_cats = len(self.__categories__)
cats = xrange(n_cats)
sum_words_gv = sum([
self.__gv__([w], ic) for w in ngram for ic in cats
])
if (sum_words_gv < .05):
return .0
elif len([
w for w in ngram
if self.__gv__([w], icat) >= .01
]) == len(ngram):
gv = self.__gv__(ngram, icat)
return gv / max_gv + sum_words_gv
# return gv / max_gv * len(ngram)
gv = self.__gv__(ngram, icat)
return gv / max_gv
except (ZeroDivisionError, IndexError):
return .0
except TypeError:
return 0
def __apply_fn__(self, fn, ngram, cat=None):
"""Private method used by gv, lv, sn, sg functions."""
if ngram.strip() == '':
return 0
ngram = [self.get_word_index(w)
for w in re.split(self.__word_delimiter__, ngram)
if w]
if cat is None:
return fn(ngram) if IDX_UNKNOWN_WORD not in ngram else 0
icat = self.get_category_index(cat)
if icat == IDX_UNKNOWN_CATEGORY:
raise InvalidCategoryError
return fn(ngram, icat) if IDX_UNKNOWN_WORD not in ngram else 0
def __summary_ops_are_pristine__(self):
"""Return True if summary operators haven't changed."""
return self.original_sumop_ngrams == self.summary_op_ngrams and \
self.original_sumop_sentences == self.summary_op_sentences and \
self.original_sumop_paragraphs == self.summary_op_paragraphs
def __classify_ngram__(self, ngram):
"""Classify the given n-gram."""
cv = [
self.__cv__(ngram, icat)
for icat in xrange(len(self.__categories__))
]
cv[:] = [(v if v > self.__a__ else 0) for v in cv]
return cv
def __classify_sentence__(self, sent, prep, json=False, prep_func=None):
"""Classify the given sentence."""
classify_trans = self.__classify_ngram__
categories = self.__categories__
cats = xrange(len(categories))
word_index = self.get_word_index
word_delimiter = self.__word_delimiter__
word_regex = self.__word_regex__
if not json:
if prep or prep_func is not None:
prep_func = prep_func or Pp.clean_and_ready
sent = prep_func(sent)
sent_words = [
(w, w)
for w in re_split_keep(word_regex, sent)
if w
]
else:
if prep or prep_func is not None:
sent_words = [
(w, Pp.clean_and_ready(w, dots=False) if prep_func is None else prep_func(w))
for w in re_split_keep(word_regex, sent)
if w
]
else:
sent_words = [
(w, w)
for w in re_split_keep(word_regex, sent)
if w
]
if not sent_words:
sent_words = [(u'.', u'.')]
sent_iwords = [word_index(w) for _, w in sent_words]
sent_len = len(sent_iwords)
sent_parsed = []
wcur = 0
while wcur < sent_len:
cats_ngrams_cv = [[0] for icat in cats]
cats_ngrams_offset = [[0] for icat in cats]
cats_ngrams_iword = [[-1] for icat in cats]
cats_max_cv = [.0 for icat in cats]
for icat in cats:
woffset = 0
word_raw = sent_words[wcur + woffset][0]
wordi = sent_iwords[wcur + woffset]
word_info = categories[icat][VOCAB]
if wordi in word_info:
cats_ngrams_cv[icat][0] = word_info[wordi][CV]
word_info = word_info[wordi][NEXT]
cats_ngrams_iword[icat][0] = wordi
cats_ngrams_offset[icat][0] = woffset
# if it is a learned word (not unknown and seen for this category),
# then try to recognize learned n-grams too
if wordi != IDX_UNKNOWN_WORD and wordi in categories[icat][VOCAB]:
# while word or word delimiter (e.g. space)
while wordi != IDX_UNKNOWN_WORD or re.match(word_delimiter, word_raw):
woffset += 1
if wcur + woffset >= sent_len:
break
word_raw = sent_words[wcur + woffset][0]
wordi = sent_iwords[wcur + woffset]
# if word is a word:
if wordi != IDX_UNKNOWN_WORD:
# if this word belongs to this category
if wordi in word_info:
cats_ngrams_cv[icat].append(word_info[wordi][CV])
cats_ngrams_iword[icat].append(wordi)
cats_ngrams_offset[icat].append(woffset)
word_info = word_info[wordi][NEXT]
else:
break
cats_max_cv[icat] = (max(cats_ngrams_cv[icat])
if cats_ngrams_cv[icat] else .0)
max_gv = max(cats_max_cv)
use_ngram = True
if (max_gv > self.__a__):
icat_max_gv = cats_max_cv.index(max_gv)
ngram_max_gv = cats_ngrams_cv[icat_max_gv].index(max_gv)
offset_max_gv = cats_ngrams_offset[icat_max_gv][ngram_max_gv] + 1
max_gv_sum_1_grams = max([
sum([
(categories[ic][VOCAB][wi][CV]
if wi in categories[ic][VOCAB]
else 0)
for wi
in cats_ngrams_iword[ic]
])
for ic in cats
])
if (max_gv_sum_1_grams > max_gv):
use_ngram = False
else:
use_ngram = False
if not use_ngram:
offset_max_gv = 1
icat_max_gv = 0
ngram_max_gv = 0
sent_parsed.append(
(
u"".join([raw_word for raw_word, _ in sent_words[wcur:wcur + offset_max_gv]]),
cats_ngrams_iword[icat_max_gv][:ngram_max_gv + 1]
)
)
wcur += offset_max_gv
get_word = self.get_word
if not json:
words_cvs = [classify_trans(seq) for _, seq in sent_parsed]
if words_cvs:
return self.summary_op_ngrams(words_cvs)
return self.__zero_cv__
else:
get_tip = self.__trie_node__
local_value = self.__lv__
info = [
{
"token": u"→".join(map(get_word, sequence)),
"lexeme": raw_sequence,
"cv": classify_trans(sequence),
"lv": [local_value(sequence, ic) for ic in cats],
"fr": [get_tip(sequence, ic)[FR] for ic in cats]
}
for raw_sequence, sequence in sent_parsed
]
return {
"words": info,
"cv": self.summary_op_ngrams([v["cv"] for v in info]),
"wmv": reduce(vmax, [v["cv"] for v in info]) # word max value
}
def __classify_paragraph__(self, parag, prep, json=False, prep_func=None):
"""Classify the given paragraph."""
if not json:
sents_cvs = [
self.__classify_sentence__(sent, prep=prep, prep_func=prep_func)
for sent in re.split(self.__sent_delimiter__, parag)
if sent
]
if sents_cvs:
return self.summary_op_sentences(sents_cvs)
return self.__zero_cv__
else:
info = [
self.__classify_sentence__(sent, prep=prep, prep_func=prep_func, json=True)
for sent in re_split_keep(self.__sent_delimiter__, parag)
if sent
]
if info:
sents_cvs = [v["cv"] for v in info]
cv = self.summary_op_sentences(sents_cvs)
wmv = reduce(vmax, [v["wmv"] for v in info])
else:
cv = self.__zero_cv__
wmv = cv
return {
"sents": info,
"cv": cv,
"wmv": wmv # word max value
}
def __trie_node__(self, ngram, icat):
"""Get the trie's node for this n-gram."""
try:
word_info = self.__categories__[icat][VOCAB][ngram[0]]
for word in ngram[1:]:
word_info = word_info[NEXT][word]
return word_info
except BaseException:
return EMPTY_WORD_INFO
def __get_category__(self, name):
"""
Given the category name, return the category data.
If category name doesn't exist, creates a new one.
"""
try:
return self.__categories_index__[name]
except KeyError:
self.__max_fr__.append([])
self.__max_gv__.append([])
self.__categories_index__[name] = len(self.__categories__)
self.__categories__.append([name, {}]) # name, vocabulary
self.__zero_cv__ = (0,) * len(self.__categories__)
return self.__categories_index__[name]
def __get_category_length__(self, icat):
"""
Return the category length.
The category length is the total number of words seen during training.
"""
size = 0
vocab = self.__categories__[icat][VOCAB]
for word in vocab:
size += vocab[word][FR]
return size
def __get_most_probable_category__(self):
"""Return the index of the most probable category."""
sizes = []
for icat in xrange(len(self.__categories__)):
sizes.append((icat, self.__get_category_length__(icat)))
return sorted(sizes, key=lambda v: v[1])[-1][0]
def __get_vocabularies__(self, icat, vocab, preffix, n_grams, output, ngram_char="_"):
"""Get category list of n-grams with info."""
senq_ilen = len(preffix)
get_name = self.get_word
seq = preffix + [None]
if len(seq) > n_grams:
return
for word in vocab:
seq[-1] = word
if (self.__cv__(seq, icat) > 0):
output[senq_ilen].append(
(
ngram_char.join([get_name(wi) for wi in seq]),
vocab[word][FR],
self.__gv__(seq, icat),
self.__cv__(seq, icat)
)
)
self.__get_vocabularies__(
icat, vocab[word][NEXT], seq, n_grams, output, ngram_char
)
def __get_category_vocab__(self, icat):
"""Get category list of n-grams ordered by confidence value."""
category = self.__categories__[icat]
vocab = category[VOCAB]
w_seqs = ([w] for w in vocab)
vocab_icat = (
(
self.get_word(wseq[0]),
vocab[wseq[0]][FR],
self.__lv__(wseq, icat),
self.__gv__(wseq, icat),
self.__cv__(wseq, icat)
)
for wseq in w_seqs if self.__gv__(wseq, icat) > self.__a__
)
return sorted(vocab_icat, key=lambda k: -k[-1])
def __get_def_cat__(self, def_cat):
"""Given the `def_cat` argument, get the default category value."""
if def_cat is not None and (def_cat not in [STR_MOST_PROBABLE, STR_UNKNOWN] and
self.get_category_index(def_cat) == IDX_UNKNOWN_CATEGORY):
raise ValueError(
"the default category must be 'most-probable', 'unknown', or a category name"
" (current value is '%s')." % str(def_cat)
)
def_cat = None if def_cat == STR_UNKNOWN else def_cat
return self.get_most_probable_category() if def_cat == STR_MOST_PROBABLE else def_cat
def __get_next_iwords__(self, sent, icat):
"""Return the list of possible following words' indexes."""
if not self.get_category_name(icat):
return []
vocab = self.__categories__[icat][VOCAB]
word_index = self.get_word_index
sent = Pp.clean_and_ready(sent)
sent = [
word_index(w)
for w in sent.strip(".").split(".")[-1].split(" ") if w
]
tips = []
for word in sent:
if word is None:
tips[:] = []
continue
tips.append(vocab)
tips[:] = (
tip[word][NEXT]
for tip in tips if word in tip and tip[word][NEXT]
)
if len(tips) == 0:
return []
next_words = tips[0]
next_nbr_words = float(sum([next_words[w][FR] for w in next_words]))
return sorted(
[
(
word1,
next_words[word1][FR],
next_words[word1][FR] / next_nbr_words
)
for word1 in next_words
],
key=lambda k: -k[1]
)
def __prune_cat_trie__(self, vocab, prune=False, min_n=None):
"""Prune the trie of the given category."""
prun_floor = min_n or self.__prun_floor__
remove = []
for word in vocab:
if prune and vocab[word][FR] <= prun_floor:
vocab[word][NEXT] = None
remove.append(word)
else:
self.__prune_cat_trie__(vocab[word][NEXT], prune=True)
for word in remove:
del vocab[word]
def __prune_tries__(self):
"""Prune the trie of every category."""
Print.info("pruning tries...", offset=1)
for category in self.__categories__:
self.__prune_cat_trie__(category[VOCAB])
self.__prun_counter__ = 0
def __cache_lvs__(self, icat, vocab, preffix):
"""Cache all local values."""
for word in vocab:
sequence = preffix + [word]
vocab[word][LV] = self.__lv__(sequence, icat, cache=False)
self.__cache_lvs__(icat, vocab[word][NEXT], sequence)
def __cache_gvs__(self, icat, vocab, preffix):
"""Cache all global values."""
for word in vocab:
sequence = preffix + [word]
vocab[word][GV] = self.__gv__(sequence, icat, cache=False)
self.__cache_gvs__(icat, vocab[word][NEXT], sequence)
def __cache_sg__(self, icat, vocab, preffix):
"""Cache all significance weight values."""
for word in vocab:
sequence = preffix + [word]
vocab[word][SG] = self.__sg__(sequence, icat, cache=False)
self.__cache_sg__(icat, vocab[word][NEXT], sequence)
def __cache_cvs__(self, icat, vocab, preffix):
"""Cache all confidence values."""
for word in vocab:
sequence = preffix + [word]
vocab[word][CV] = self.__cv__(sequence, icat, False)
self.__cache_cvs__(icat, vocab[word][NEXT], sequence)
def __update_max_gvs__(self, icat, vocab, preffix):
"""Update all maximum global values."""
gv = self.__gv__
max_gvs = self.__max_gv__[icat]
sentence_ilength = len(preffix)
sequence = preffix + [None]
for word in vocab:
sequence[-1] = word
sequence_gv = gv(sequence, icat)
if sequence_gv > max_gvs[sentence_ilength]:
max_gvs[sentence_ilength] = sequence_gv
self.__update_max_gvs__(icat, vocab[word][NEXT], sequence)
def __update_needed__(self):
"""Return True if an update is needed, false otherwise."""
return (self.__s__ != self.__s_update__ or
self.__l__ != self.__l_update__ or
self.__p__ != self.__p_update__)
def __save_cat_vocab__(self, icat, path, n_grams):
"""Save the category vocabulary inside ``path``."""
if n_grams == -1:
n_grams = 20 # infinite
category = self.__categories__[icat]
cat_name = self.get_category_name(icat)
vocab = category[VOCAB]
vocabularies_out = [[] for _ in xrange(n_grams)]
terms = ["words", "bigrams", "trigrams"]
self.__get_vocabularies__(icat, vocab, [], n_grams, vocabularies_out)
Print.info("saving '%s' vocab" % cat_name)
for ilen in xrange(n_grams):
if vocabularies_out[ilen]:
term = terms[ilen] if ilen <= 2 else "%d-grams" % (ilen + 1)
voc_path = os.path.join(
path, "ss3_vocab_%s(%s).csv" % (cat_name, term)
)
f = open(voc_path, "w+", encoding=ENCODING)
vocabularies_out[ilen].sort(key=lambda k: -k[-1])
f.write(u"%s,%s,%s,%s\n" % ("term", "fr", "gv", "cv"))
for trans in vocabularies_out[ilen]:
f.write(u"%s,%d,%f,%f\n" % tuple(trans))
f.close()
Print.info("\t[ %s stored in '%s'" % (term, voc_path))
def __update_cv_cache__(self):
"""Update numpy darray confidence values cache."""
if self.__cv_cache__ is None:
self.__cv_cache__ = np.zeros((len(self.__index_to_word__), len(self.__categories__)))
cv = self.__cv__
for term_idx, cv_vec in enumerate(self.__cv_cache__):
for cat_idx, _ in enumerate(cv_vec):
try:
cv_vec[cat_idx] = cv([term_idx], cat_idx)
except KeyError:
cv_vec[cat_idx] = 0
def __predict_fast__(
self, x_test, def_cat=STR_MOST_PROBABLE, labels=True,
multilabel=False, proba=False, prep=True, leave_pbar=True
):
"""A faster version of the `predict` method (using numpy)."""
if not def_cat or def_cat == STR_UNKNOWN:
def_cat = IDX_UNKNOWN_CATEGORY
elif def_cat == STR_MOST_PROBABLE:
def_cat = self.__get_most_probable_category__()
else:
def_cat = self.get_category_index(def_cat)
if def_cat == IDX_UNKNOWN_CATEGORY:
raise InvalidCategoryError
# does the special "[others]" category exist? (only used in multilabel classification)
__other_idx__ = self.get_category_index(STR_OTHERS_CATEGORY)
if self.__update_needed__():
self.update_values()
if self.__cv_cache__ is None:
self.__update_cv_cache__()
self.__last_x_test__ = None # could have learned a new word (in `learn`)
cv_cache = self.__cv_cache__
x_test_hash = list_hash(x_test)
if x_test_hash == self.__last_x_test__:
x_test_idx = self.__last_x_test_idx__
else:
self.__last_x_test__ = x_test_hash
self.__last_x_test_idx__ = [None] * len(x_test)
x_test_idx = self.__last_x_test_idx__
word_index = self.get_word_index
for doc_idx, doc in enumerate(tqdm(x_test, desc="Caching documents",
leave=False, disable=Print.is_quiet())):
x_test_idx[doc_idx] = [
word_index(w)
for w
in re.split(self.__word_delimiter__, Pp.clean_and_ready(doc) if prep else doc)
if word_index(w) != IDX_UNKNOWN_WORD
]
y_pred = [None] * len(x_test)
for doc_idx, doc in enumerate(tqdm(x_test_idx, desc="Classification",
leave=leave_pbar, disable=Print.is_quiet())):
if self.__a__ > 0:
doc_cvs = cv_cache[doc]
doc_cvs[doc_cvs <= self.__a__] = 0
pred_cv = np.add.reduce(doc_cvs, 0)
else:
pred_cv = np.add.reduce(cv_cache[doc], 0)
if proba:
y_pred[doc_idx] = list(pred_cv)
continue
if not multilabel:
if pred_cv.sum() == 0:
y_pred[doc_idx] = def_cat
else:
y_pred[doc_idx] = np.argmax(pred_cv)
if labels:
if y_pred[doc_idx] != IDX_UNKNOWN_CATEGORY:
y_pred[doc_idx] = self.__categories__[y_pred[doc_idx]][NAME]
else:
y_pred[doc_idx] = STR_UNKNOWN_CATEGORY
else:
if pred_cv.sum() == 0:
if def_cat == IDX_UNKNOWN_CATEGORY:
y_pred[doc_idx] = []
else:
y_pred[doc_idx] = [self.get_category_name(def_cat) if labels else def_cat]
else:
r = sorted([(i, pred_cv[i])
for i in range(pred_cv.size)],
key=lambda e: -e[1])
if labels:
y_pred[doc_idx] = [self.get_category_name(cat_i)
for cat_i, _ in r[:kmean_multilabel_size(r)]]
else:
y_pred[doc_idx] = [cat_i for cat_i, _ in r[:kmean_multilabel_size(r)]]
# if the special "[others]" category exists
if __other_idx__ != IDX_UNKNOWN_CATEGORY:
# if its among the predicted labels, remove (hide) it
if labels:
if STR_OTHERS_CATEGORY in y_pred[doc_idx]:
y_pred[doc_idx].remove(STR_OTHERS_CATEGORY)
else:
if __other_idx__ in y_pred[doc_idx]:
y_pred[doc_idx].remove(__other_idx__)
return y_pred
def summary_op_ngrams(self, cvs):
"""
Summary operator for n-gram confidence vectors.
By default it returns the addition of all confidence
vectors. However, in case you want to use a custom
summary operator, this function must be replaced
as shown in the following example:
>>> def my_summary_op(cvs):
>>> return cvs[0]
>>> ...
>>> clf = SS3()
>>> ...
>>> clf.summary_op_ngrams = my_summary_op
Note that any function receiving a list of vectors and
returning a single vector could be used. In the above example
the summary operator is replaced by the user-defined
``my_summary_op`` which ignores all confidence vectors
returning only the confidence vector of the first n-gram
(which besides being an illustrative example, makes no real sense).
:param cvs: a list n-grams confidence vectors
:type cvs: list (of list of float)
:returns: a sentence confidence vector
:rtype: list (of float)
"""
return reduce(vsum, cvs)
def summary_op_sentences(self, cvs):
"""
Summary operator for sentence confidence vectors.
By default it returns the addition of all confidence
vectors. However, in case you want to use a custom
summary operator, this function must be replaced
as shown in the following example:
>>> def dummy_summary_op(cvs):
>>> return cvs[0]
>>> ...
>>> clf = SS3()
>>> ...
>>> clf.summary_op_sentences = dummy_summary_op
Note that any function receiving a list of vectors and
returning a single vector could be used. In the above example
the summary operator is replaced by the user-defined
``dummy_summary_op`` which ignores all confidence vectors
returning only the confidence vector of the first sentence
(which besides being an illustrative example, makes no real sense).
:param cvs: a list sentence confidence vectors
:type cvs: list (of list of float)
:returns: a paragraph confidence vector
:rtype: list (of float)
"""
return reduce(vsum, cvs)
def summary_op_paragraphs(self, cvs):
"""
Summary operator for paragraph confidence vectors.
By default it returns the addition of all confidence
vectors. However, in case you want to use a custom
summary operator, this function must be replaced
as shown in the following example:
>>> def dummy_summary_op(cvs):
>>> return cvs[0]
>>> ...
>>> clf = SS3()
>>> ...
>>> clf.summary_op_paragraphs = dummy_summary_op
Note that any function receiving a list of vectors and
returning a single vector could be used. In the above example
the summary operator is replaced by the user-defined
``dummy_summary_op`` which ignores all confidence vectors
returning only the confidence vector of the first paragraph
(which besides being an illustrative example, makes no real sense).
:param cvs: a list paragraph confidence vectors
:type cvs: list (of list of float)
:returns: the document confidence vector
:rtype: list (of float)
"""
return reduce(vsum, cvs)
def get_name(self):
"""
Return the model's name.