-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
2739 lines (2315 loc) · 94.9 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 -*-
"""
#这是包含SS3分类器实现的主模块。
"""
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:
"""
:param s: (“平滑度”(sigma)超参数值)
:type s: float
:param l: (显著性”(λ)超参数值)
:type l: float
:param p: “制裁”(rho)超参数值)
:type p: float
:param a: (alpha超参数值(即分类期间,小于alpha的置信值(cv)将被忽略))
:type a: float
:param name: (模型名称(用于从磁盘保存和加载模型))
:type name: str
:param cv_m: 用于计算每个参数的置信值(cv)的方法(单词或n-grams),选项包括:"norm_gv_xai", "norm_gv" and "gv" (默认值: "norm_gv_xai"))
term (word or n-grams), options are:
:type cv_m: str
:param sg_m: 用于计算显著性(sg)函数的方法,选项是:“vanilla”和“xai”(默认值:“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
):
"""
类构造函数。
"""
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):
"""局部值函数"""
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):
"""制裁(sn)功能。"""
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):
""" 显著性(sg)函数定义。"""
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):
"""
显著性(sn)函数的变体。此版本的sg函数为改进视觉解释。
"""
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):
"""
(全局值(gv)函数。这是计算置信值(cv)的原始方法)
"""
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):
"""
计算术语置信值(cv)的替代方法。此变体规范化gv值,并将该值用作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):
"""
计算置信值(cv)的替代方法。这种变化不仅规范了gv值,还改进了视觉解释。
"""
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):
"""gv、lv、sn、sg函数使用的私有方法。"""
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):
"""如果摘要运算符未更改,则返回True。"""
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):
"""对给定的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_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
# 如果它是一个习得单词(对于这个类别来说不是未知和可见的),
# 然后也试着识别学习过的n-gram
if wordi != IDX_UNKNOWN_WORD and wordi in categories[icat][VOCAB]:
# while单词或单词分隔符(例如空格)
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):
"""对给定段落进行分类。"""
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):
"""获取此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):
"""
给定类别名称,返回类别数据。如果类别名称不存在,则创建一个新的类别名称。
"""
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):
"""
返回类别长度。类别长度是训练期间看到的单词总数。
"""
size = 0
vocab = self.__categories__[icat][VOCAB]
for word in vocab:
size += vocab[word][FR]
return size
def __get_most_probable_category__(self):
"""返回最可能类别的索引"""
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="_"):
"""获取包含信息的n-grams类别列表。"""
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):
"""获取按置信值排序的n-gram的类别列表。"""
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):
"""给定`def_cat`参数,获取默认类别值。"""
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):
"""返回可能的后续单词索引列表。"""
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):
"""删减给定类别的trie单词查找树。"""
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):
"""删减每个类别的单词查找树"""
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):
"""缓存所有局部值"""
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):
"""缓存所有全局值"""
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):
"""缓存所有显著性权重值"""
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):
"""缓存所有置信值"""
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):
"""更新所有最大全局值"""
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):
"""(参数更新函数)如果需要更新,则返回True,否则返回false。"""
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):
"""将类别词汇保存在``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):
"""更新置信值缓存"""
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
):
"""“predict”方法的更快版本(使用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):
"""
n元置信向量的汇总运算符。
默认情况下,它返回所有置信度的添加矢量。但是,如果您想使用自定义摘要运算符,必须替换此函数
如下例所示:
>>> def my_summary_op(cvs):
>>> return cvs[0]
>>> ...
>>> clf = SS3()
>>> ...
>>> clf.summary_op_ngrams = my_summary_op
任何接收矢量列表和可以使用返回单个矢量。在上面的例子中摘要运算符被用户定义的
``my_summary_op``忽略所有置信向量仅返回第一个n-gram的置信向量(这除了是一个说明性的例子外,没有任何实际意义)。)
:param cvs: (n-gram置信向量列表)
:type cvs: (浮点数列表)
:returns: 句子置信向量)
:rtype: list (of float)
"""
return reduce(vsum, cvs)
def summary_op_sentences(self, cvs):
"""
句子置信向量的摘要运算符)
:param cvs:(列出句子置信向量)
:type cvs: (浮点数列表)
:returns: 段落置信向量)
:rtype: list (of float)
"""
return reduce(vsum, cvs)
def summary_op_paragraphs(self, cvs):
"""
段落置信向量的汇总运算符。
:param cvs: 段落置信向量列表
:type cvs: list (of list of float)
:returns: 文档置信向量
:rtype: list (of float)
"""
return reduce(vsum, cvs)
def get_name(self):
"""
返回模型名称
:returns: the model's name.
:rtype: str
"""
return self.__name__
def set_name(self, name):
"""
设置模型名称)
:param name: the model's name.
:type name: str
"""
self.__name__ = name
def set_hyperparameters(self, s=None, l=None, p=None, a=None):
"""
设置超参数
"""
if s is not None:
self.set_s(s)
if l is not None:
self.set_l(l)
if p is not None:
self.set_p(p)
if a is not None:
self.set_a(a)
def get_hyperparameters(self):
"""
获得超参数值
:returns: 返回具有超参数当前值的元组
:rtype: tuple
"""
return self.__s__, self.__l__, self.__p__, self.__a__
def set_model_path(self, path):
"""
Overwrite the default path from which the model will be loaded (or saved to).
Note: be aware that the PySS3 Command Line tool looks for
a local folder called ``ss3_models`` to load models.
Therefore, the ``ss3_models`` folder will be always automatically
append to the given ``path`` (e.g. if ``path="my/path/"``, it will
be converted into ``my/path/ss3_models``).
:param path: the path
:type path: str
"""
self.__models_folder__ = os.path.join(path, STR_MODEL_FOLDER)
def set_block_delimiters(self, parag=None, sent=None, word=None):
r"""覆盖用于将输入文档拆分为块的默认分隔符。)
分隔符是从简单的(例如``“”``)到更复杂的(例如`r“[^\s\w\d]”``)。注意:记住正则表达式有一些保留字符,
例如,点(.),在这种情况下,使用反斜杠表示引用字符本身(例如``\.``)
e.g.
>>> ss3.set_block_delimiters(word="\s"),,
>>> ss3.set_block_delimiters(word="\s", parag="\n\n")
>>> ss3.set_block_delimiters(parag="\n---\n")
>>> ss3.set_block_delimiters(sent="\.")
>>> ss3.set_block_delimiters(word="\|")
>>> ss3.set_block_delimiters(word=" ")
:param parag: (段落新分隔符)
:type parag: str
:param sent: 句子新分隔符)
:type sent: str
:param word: 单词新分隔符)
:type word: str
"""
if parag:
self.set_delimiter_paragraph(parag)
if sent:
self.set_delimiter_sentence(sent)
if word:
self.set_delimiter_word(word)
def set_delimiter_paragraph(self, regex):
r"""
设置用于将文档拆分为段落的分隔符。
请记住,正则表达式有某些保留字符,例如,点(.),
在这种情况下,使用反斜杠表示引用字符本身(例如``\.``)
:param regex: 新分隔符的正则表达式)
:type regex: str
"""
self.__parag_delimiter__ = regex