/
preprocessor.py
1433 lines (1147 loc) · 54.8 KB
/
preprocessor.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
from ..imports import *
from .. import utils as U
from ..preprocessor import Preprocessor
from ..data import SequenceDataset
from . import textutils as TU
from transformers import AutoConfig, TFAutoModelForSequenceClassification, AutoTokenizer, TFAutoModel
DISTILBERT= 'distilbert'
NOSPACE_LANGS = ['zh-cn', 'zh-tw', 'ja']
def is_nospace_lang(lang):
return lang in NOSPACE_LANGS
def fname_from_url(url):
return os.path.split(url)[-1]
#------------------------------------------------------------------------------
# Word Vectors
#------------------------------------------------------------------------------
WV_URL = 'https://dl.fbaipublicfiles.com/fasttext/vectors-english/crawl-300d-2M.vec.zip'
#WV_URL = 'http://nlp.stanford.edu/data/glove.6B.zip
def get_wv_path(wv_path_or_url=WV_URL):
# process if file path given
if os.path.isfile(wv_path_or_url) and wv_path_or_url.endswith('vec'): return wv_path_or_url
elif os.path.isfile(wv_path_or_url):
raise ValueError("wv_path_or_url must either be URL .vec.zip or .vec.gz file or file path to .vec file")
# process if URL is given
fasttext_url = 'https://dl.fbaipublicfiles.com/fasttext'
if not wv_path_or_url.startswith(fasttext_url):
raise ValueError('selected word vector file must be from %s'% (fasttext_url))
if not wv_path_or_url.endswith('.vec.zip') and not wv_path_or_url.endswith('vec.gz'):
raise ValueError('If wv_path_or_url is URL, must be .vec.zip filea from Facebook fasttext site.')
ktrain_data = U.get_ktrain_data()
zip_fpath = os.path.join(ktrain_data, fname_from_url(wv_path_or_url))
wv_path = os.path.join(ktrain_data, os.path.splitext(fname_from_url(wv_path_or_url))[0])
if not os.path.isfile(wv_path):
# download zip
print('downloading pretrained word vectors to %s ...' % (ktrain_data))
U.download(wv_path_or_url, zip_fpath)
# unzip
print('\nextracting pretrained word vectors...')
if wv_path_or_url.endswith('.vec.zip'):
with zipfile.ZipFile(zip_fpath, 'r') as zip_ref:
zip_ref.extractall(ktrain_data)
else: # .vec.gz
with gzip.open(zip_fpath, 'rb') as f_in:
with open(wv_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
print('done.\n')
# cleanup
print('cleanup downloaded zip...')
try:
os.remove(zip_fpath)
print('done.\n')
except OSError:
print('failed to cleanup/remove %s' % (zip_fpath))
return wv_path
def get_coefs(word, *arr): return word, np.asarray(arr, dtype='float32')
#def load_wv(wv_path=None, verbose=1):
#if verbose: print('Loading pretrained word vectors...this may take a few moments...')
#if wv_path is None: wv_path = get_wv_path()
#embeddings_index = dict(get_coefs(*o.rstrip().rsplit(' ')) for o in open(wv_path, encoding='utf-8'))
#if verbose: print('Done.')
#return embeddings_index
def file_len(fname):
with open(fname, encoding='utf-8') as f:
for i, l in enumerate(f):
pass
return i + 1
def load_wv(wv_path_or_url=WV_URL, verbose=1):
wv_path = get_wv_path(wv_path_or_url)
if verbose: print('loading pretrained word vectors...this may take a few moments...')
length = file_len(wv_path)
tups = []
mb = master_bar(range(1))
for i in mb:
f = open(wv_path, encoding='utf-8')
for o in progress_bar(range(length), parent=mb):
o = f.readline()
tups.append(get_coefs(*o.rstrip().rsplit(' ')))
f.close()
#if verbose: mb.write('done.')
return dict(tups)
#------------------------------------------------------------------------------
# BERT
#------------------------------------------------------------------------------
#BERT_PATH = os.path.join(os.path.dirname(os.path.abspath(localbert.__file__)), 'uncased_L-12_H-768_A-12')
BERT_URL = 'https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip'
BERT_URL_MULTI = 'https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip'
BERT_URL_CN = 'https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip'
def get_bert_path(lang='en'):
if lang == 'en':
bert_url = BERT_URL
elif lang.startswith('zh-'):
bert_url = BERT_URL_CN
else:
bert_url = BERT_URL_MULTI
ktrain_data = U.get_ktrain_data()
zip_fpath = os.path.join(ktrain_data, fname_from_url(bert_url))
bert_path = os.path.join( ktrain_data, os.path.splitext(fname_from_url(bert_url))[0] )
if not os.path.isdir(bert_path) or \
not os.path.isfile(os.path.join(bert_path, 'bert_config.json')) or\
not os.path.isfile(os.path.join(bert_path, 'bert_model.ckpt.data-00000-of-00001')) or\
not os.path.isfile(os.path.join(bert_path, 'bert_model.ckpt.index')) or\
not os.path.isfile(os.path.join(bert_path, 'bert_model.ckpt.meta')) or\
not os.path.isfile(os.path.join(bert_path, 'vocab.txt')):
# download zip
print('downloading pretrained BERT model (%s)...' % (fname_from_url(bert_url)))
U.download(bert_url, zip_fpath)
# unzip
print('\nextracting pretrained BERT model...')
with zipfile.ZipFile(zip_fpath, 'r') as zip_ref:
zip_ref.extractall(ktrain_data)
print('done.\n')
# cleanup
print('cleanup downloaded zip...')
try:
os.remove(zip_fpath)
print('done.\n')
except OSError:
print('failed to cleanup/remove %s' % (zip_fpath))
return bert_path
def bert_tokenize(docs, tokenizer, max_length, verbose=1):
if verbose:
mb = master_bar(range(1))
pb = progress_bar(docs, parent=mb)
else:
mb = range(1)
pb = docs
indices = []
for i in mb:
for doc in pb:
ids, segments = tokenizer.encode(doc, max_len=max_length)
indices.append(ids)
if verbose: mb.write('done.')
zeros = np.zeros_like(indices)
return [np.array(indices), np.array(zeros)]
#------------------------------------------------------------------------------
# Transformers UTILITIES
#------------------------------------------------------------------------------
#def convert_to_tfdataset(csv):
#def gen():
#for ex in csv:
#yield {'idx': ex[0],
#'sentence': ex[1],
#'label': str(ex[2])}
#return tf.data.Dataset.from_generator(gen,
#{'idx': tf.int64,
#'sentence': tf.string,
#'label': tf.int64})
#def features_to_tfdataset(features):
# def gen():
# for ex in features:
# yield ({'input_ids': ex.input_ids,
# 'attention_mask': ex.attention_mask,
# 'token_type_ids': ex.token_type_ids},
# ex.label)
# return tf.data.Dataset.from_generator(gen,
# ({'input_ids': tf.int32,
# 'attention_mask': tf.int32,
# 'token_type_ids': tf.int32},
# tf.int64),
# ({'input_ids': tf.TensorShape([None]),
# 'attention_mask': tf.TensorShape([None]),
# 'token_type_ids': tf.TensorShape([None])},
# tf.TensorShape([None])))
# #tf.TensorShape(])))
def _is_sentence_pair(tup):
if isinstance(tup, (tuple)) and len(tup) == 2 and\
isinstance(tup[0], str) and isinstance(tup[1], str):
return True
else:
if isinstance(tup, (list, np.ndarray)) and len(tup) == 2 and\
isinstance(tup[0], str) and isinstance(tup[1], str):
warnings.warn('List or array of two texts supplied, so task being treated as text classification. ' +\
'If this is a sentence pair classification task, please cast to tuple.')
return False
def detect_text_format(texts):
is_pair = False
is_array = False
err_msg = 'invalid text format: texts should be list of strings or list of sentence pairs in form of tuples (str, str)'
if _is_sentence_pair(texts):
is_pair=True
is_array = False
elif isinstance(texts, (tuple, list, np.ndarray)):
is_array = True
if len(texts) == 0: raise ValueError('texts is empty')
peek = texts[0]
is_pair = _is_sentence_pair(peek)
if not is_pair and not isinstance(peek, str):
raise ValueError(err_msg)
return is_array, is_pair
def hf_features_to_tfdataset(features_list, labels):
features_list = np.array(features_list)
labels = np.array(labels) if labels is not None else None
tfdataset = tf.data.Dataset.from_tensor_slices((features_list, labels))
tfdataset = tfdataset.map(lambda x,y: ({'input_ids': x[0],
'attention_mask': x[1],
'token_type_ids': x[2]}, y))
return tfdataset
def hf_convert_example(text_a, text_b=None, tokenizer=None,
max_length=512,
pad_on_left=False,
pad_token=0,
pad_token_segment_id=0,
mask_padding_with_zero=True):
"""
convert InputExample to InputFeature for Hugging Face transformer
"""
if tokenizer is None: raise ValueError('tokenizer is required')
inputs = tokenizer.encode_plus(
text_a,
text_b,
add_special_tokens=True,
return_token_type_ids=True,
max_length=max_length,
truncation='longest_first'
)
input_ids, token_type_ids = inputs["input_ids"], inputs["token_type_ids"]
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
# Zero-pad up to the sequence length.
padding_length = max_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
attention_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
token_type_ids = ([pad_token_segment_id] * padding_length) + token_type_ids
else:
input_ids = input_ids + ([pad_token] * padding_length)
attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
token_type_ids = token_type_ids + ([pad_token_segment_id] * padding_length)
assert len(input_ids) == max_length, "Error with input length {} vs {}".format(len(input_ids), max_length)
assert len(attention_mask) == max_length, "Error with input length {} vs {}".format(len(attention_mask), max_length)
assert len(token_type_ids) == max_length, "Error with input length {} vs {}".format(len(token_type_ids), max_length)
#if ex_index < 1:
#print("*** Example ***")
#print("guid: %s" % (example.guid))
#print("input_ids: %s" % " ".join([str(x) for x in input_ids]))
#print("attention_mask: %s" % " ".join([str(x) for x in attention_mask]))
#print("token_type_ids: %s" % " ".join([str(x) for x in token_type_ids]))
#print("label: %s (id = %d)" % (example.label, label))
return [input_ids, attention_mask, token_type_ids]
def hf_convert_examples(texts, y=None, tokenizer=None,
max_length=512,
pad_on_left=False,
pad_token=0,
pad_token_segment_id=0,
mask_padding_with_zero=True,
use_dynamic_shape=False,
verbose=1):
"""
Loads a data file into a list of ``InputFeatures``
Args:
texts: texts of documents or sentence pairs
y: labels for documents
tokenizer: Instance of a tokenizer that will tokenize the examples
max_length: Maximum example length
pad_on_left: If set to ``True``, the examples will be padded on the left rather than on the right (default)
pad_token: Padding token
pad_token_segment_id: The segment ID for the padding token (It is usually 0, but can vary such as for XLNet where it is 4)
mask_padding_with_zero: If set to ``True``, the attention mask will be filled by ``1`` for actual values
and by ``0`` for padded values. If set to ``False``, inverts it (``1`` for padded values, ``0`` for
actual values)
use_dynamic_shape(bool): If True, supplied max_length will be ignored and will be computed
based on provided texts instead.
verbose(bool): verbosity
Returns:
If the ``examples`` input is a ``tf.data.Dataset``, will return a ``tf.data.Dataset``
containing the task-specific features. If the input is a list of ``InputExamples``, will return
a list of task-specific ``InputFeatures`` which can be fed to the model.
"""
is_array, is_pair = detect_text_format(texts)
if use_dynamic_shape:
sentences = []
for text in texts:
if is_pair:
text_a = text[0]
text_b = text[1]
else:
text_a = text
text_b = None
sentences.append( tokenizer.convert_ids_to_tokens(tokenizer.encode(text_a, text_b)) )
#sentences.append(tokenizer.tokenize(text_a, text_b)) # only works for Fast tokenizers
maxlen = len(max([tokens for tokens in sentences], key=len,)) + 2
if maxlen < max_length: max_length = maxlen
data = []
features_list = []
labels = []
if verbose:
mb = master_bar(range(1))
pb = progress_bar(texts, parent=mb)
else:
mb = range(1)
pb = texts
for i in mb:
#for (idx, text) in enumerate(progress_bar(texts, parent=mb)):
for (idx, text) in enumerate(pb):
if is_pair:
text_a = text[0]
text_b = text[1]
else:
text_a = text
text_b = None
features = hf_convert_example(text_a, text_b=text_b, tokenizer=tokenizer,
max_length=max_length,
pad_on_left=pad_on_left,
pad_token=pad_token,
pad_token_segment_id=pad_token_segment_id,
mask_padding_with_zero=mask_padding_with_zero)
features_list.append(features)
labels.append(y[idx] if y is not None else None)
#tfdataset = hf_features_to_tfdataset(features_list, labels)
#return tfdataset
#return (features_list, labels)
# HF_EXCEPTION
# due to issues in transormers library and TF2 tf.Datasets, arrays are converted
# to iterators on-the-fly
#return TransformerSequence(np.array(features_list), np.array(labels))
return TransformerDataset(np.array(features_list), np.array(labels))
#------------------------------------------------------------------------------
class TextPreprocessor(Preprocessor):
"""
Text preprocessing base class
"""
def __init__(self, maxlen, class_names, lang='en', multilabel=None):
self.set_classes(class_names) # converts to list of necessary
self.maxlen = maxlen
self.lang = lang
self.multilabel = multilabel # currently, this is always initially set None until set by set_multilabel
self.preprocess_train_called = False
#self.label_encoder = None # only set if y is in string format
self.ytransform = None
self.c = self.c.tolist() if isinstance(self.c, np.ndarray) else self.c
def migrate_classes(self, class_names, classes):
# NOTE: this method transforms to np.ndarray to list.
# If removed and "if class_names" is issued prior to set_classes(), an error will occur.
class_names = class_names.tolist() if isinstance(class_names, np.ndarray) else class_names
classes = classes.tolist() if isinstance(classes, np.ndarray) else classes
if not class_names and classes:
class_names = classes
warnings.warn('The class_names argument is replacing the classes argument. Please update your code.')
return class_names
def get_tokenizer(self):
raise NotImplementedError('This method was not overridden in subclass')
def check_trained(self):
if not self.preprocess_train_called:
raise Exception('preprocess_train must be called')
def get_preprocessor(self):
raise NotImplementedError
def get_classes(self):
return self.c
def set_classes(self, class_names):
self.c = class_names.tolist() if isinstance(class_names, np.ndarray) else class_names
def preprocess(self, texts):
raise NotImplementedError
def set_multilabel(self, data, mode, verbose=1):
if mode == 'train' and self.get_classes():
original_multilabel = self.multilabel
discovered_multilabel = U.is_multilabel(data)
if original_multilabel is None:
self.multilabel = discovered_multilabel
elif original_multilabel is True and discovered_multilabel is False:
warnings.warn('The multilabel=True argument was supplied, but labels do not indicate '+\
'a multilabel problem (labels appear to be mutually-exclusive). Using multilabel=True anyways.')
elif original_multilabel is False and discovered_multilabel is True:
warnings.warn('The multilabel=False argument was supplied, but labels inidcate that '+\
'this is a multilabel problem (labels are not mutually-exclusive). Using multilabel=False anyways.')
U.vprint("Is Multi-Label? %s" % (self.multilabel), verbose=verbose)
def undo(self, doc):
"""
undoes preprocessing and returns raw data by:
converting a list or array of Word IDs back to words
"""
raise NotImplementedError
def is_chinese(self):
return TU.is_chinese(self.lang)
def is_nospace_lang(self):
return TU.is_nospace_lang(self.lang)
def process_chinese(self, texts, lang=None):
#if lang is None: lang = langdetect.detect(texts[0])
if lang is None: lang = TU.detect_lang(texts)
if not TU.is_nospace_lang(lang): return texts
return TU.split_chinese(texts)
@classmethod
def seqlen_stats(cls, list_of_texts):
"""
compute sequence length stats from
list of texts in any spaces-segmented language
Args:
list_of_texts: list of strings
Returns:
dict: dictionary with keys: mean, 95percentile, 99percentile
"""
counts = []
for text in list_of_texts:
if isinstance(text, (list, np.ndarray)):
lst = text
else:
lst = text.split()
counts.append(len(lst))
p95 = np.percentile(counts, 95)
p99 = np.percentile(counts, 99)
avg = sum(counts)/len(counts)
return {'mean':avg, '95percentile': p95, '99percentile':p99}
def print_seqlen_stats(self, texts, mode, verbose=1):
"""
prints stats about sequence lengths
"""
if verbose and not self.is_nospace_lang():
stat_dict = TextPreprocessor.seqlen_stats(texts)
print( "%s sequence lengths:" % mode)
for k in stat_dict:
print("\t%s : %s" % (k, int(round(stat_dict[k]))))
def _transform_y(self, y_data, train=False, verbose=1):
"""
preprocess y
If shape of y is 1, then task is considered classification if self.c exists
or regression if not.
"""
if self.ytransform is None:
self.ytransform = U.YTransform(class_names=self.get_classes())
y = self.ytransform.apply(y_data, train=train)
if train: self.c = self.ytransform.get_classes()
return y
class StandardTextPreprocessor(TextPreprocessor):
"""
Standard text preprocessing
"""
def __init__(self, maxlen, max_features, class_names=[], classes=[],
lang='en', ngram_range=1, multilabel=None):
class_names = self.migrate_classes(class_names, classes)
super().__init__(maxlen, class_names, lang=lang, multilabel=multilabel)
self.tok = None
self.tok_dct = {}
self.max_features = max_features
self.ngram_range = ngram_range
def get_tokenizer(self):
return self.tok
def __getstate__(self):
return {k: v for k, v in self.__dict__.items()}
def __setstate__(self, state):
"""
For backwards compatibility with pre-ytransform versions
"""
self.__dict__.update(state)
if not hasattr(self, 'ytransform'):
le = self.label_encoder if hasattr(self, 'label_encoder') else None
self.ytransform = U.YTransform(class_names=self.get_classes(), label_encoder=le)
def get_preprocessor(self):
return (self.tok, self.tok_dct)
def preprocess(self, texts):
return self.preprocess_test(texts, verbose=0)[0]
def undo(self, doc):
"""
undoes preprocessing and returns raw data by:
converting a list or array of Word IDs back to words
"""
dct = self.tok.index_word
return " ".join([dct[wid] for wid in doc if wid != 0 and wid in dct])
def preprocess_train(self, train_text, y_train, verbose=1):
"""
preprocess training set
"""
if self.lang is None: self.lang = TU.detect_lang(train_text)
U.vprint('language: %s' % (self.lang), verbose=verbose)
# special processing if Chinese
train_text = self.process_chinese(train_text, lang=self.lang)
# extract vocabulary
self.tok = Tokenizer(num_words=self.max_features)
self.tok.fit_on_texts(train_text)
U.vprint('Word Counts: {}'.format(len(self.tok.word_counts)), verbose=verbose)
U.vprint('Nrows: {}'.format(len(train_text)), verbose=verbose)
# convert to word IDs
x_train = self.tok.texts_to_sequences(train_text)
U.vprint('{} train sequences'.format(len(x_train)), verbose=verbose)
self.print_seqlen_stats(x_train, 'train', verbose=verbose)
# add ngrams
x_train = self._fit_ngrams(x_train, verbose=verbose)
# pad sequences
x_train = sequence.pad_sequences(x_train, maxlen=self.maxlen)
U.vprint('x_train shape: ({},{})'.format(x_train.shape[0], x_train.shape[1]), verbose=verbose)
# transform y
y_train = self._transform_y(y_train, train=True, verbose=verbose)
if y_train is not None and verbose:
print('y_train shape: %s' % (y_train.shape,))
# return
result = (x_train, y_train)
self.set_multilabel(result, 'train')
self.preprocess_train_called = True
return result
def preprocess_test(self, test_text, y_test=None, verbose=1):
"""
preprocess validation or test dataset
"""
self.check_trained()
if self.tok is None or self.lang is None:
raise Exception('Unfitted tokenizer or missing language. Did you run preprocess_train first?')
# check for and process chinese
test_text = self.process_chinese(test_text, self.lang)
# convert to word IDs
x_test = self.tok.texts_to_sequences(test_text)
U.vprint('{} test sequences'.format(len(x_test)), verbose=verbose)
self.print_seqlen_stats(x_test, 'test', verbose=verbose)
# add n-grams
x_test = self._add_ngrams(x_test, mode='test', verbose=verbose)
# pad sequences
x_test = sequence.pad_sequences(x_test, maxlen=self.maxlen)
U.vprint('x_test shape: ({},{})'.format(x_test.shape[0], x_test.shape[1]), verbose=verbose)
# transform y
y_test = self._transform_y(y_test, train=False, verbose=verbose)
if y_test is not None and verbose:
print('y_test shape: %s' % (y_test.shape,))
# return
return (x_test, y_test)
def _fit_ngrams(self, x_train, verbose=1):
self.tok_dct = {}
if self.ngram_range < 2: return x_train
U.vprint('Adding {}-gram features'.format(self.ngram_range), verbose=verbose)
# Create set of unique n-gram from the training set.
ngram_set = set()
for input_list in x_train:
for i in range(2, self.ngram_range + 1):
set_of_ngram = self._create_ngram_set(input_list, ngram_value=i)
ngram_set.update(set_of_ngram)
# Dictionary mapping n-gram token to a unique integer.
# Integer values are greater than max_features in order
# to avoid collision with existing features.
start_index = self.max_features + 1
token_indice = {v: k + start_index for k, v in enumerate(ngram_set)}
indice_token = {token_indice[k]: k for k in token_indice}
self.tok_dct = token_indice
# max_features is the highest integer that could be found in the dataset.
self.max_features = np.max(list(indice_token.keys())) + 1
U.vprint('max_features changed to %s with addition of ngrams' % (self.max_features), verbose=verbose)
# Augmenting x_train with n-grams features
x_train = self._add_ngrams(x_train, verbose=verbose, mode='train')
return x_train
def _add_ngrams(self, sequences, verbose=1, mode='test'):
"""
Augment the input list of list (sequences) by appending n-grams values.
Example: adding bi-gram
"""
token_indice = self.tok_dct
if self.ngram_range < 2: return sequences
new_sequences = []
for input_list in sequences:
new_list = input_list[:]
for ngram_value in range(2, self.ngram_range + 1):
for i in range(len(new_list) - ngram_value + 1):
ngram = tuple(new_list[i:i + ngram_value])
if ngram in token_indice:
new_list.append(token_indice[ngram])
new_sequences.append(new_list)
U.vprint('Average {} sequence length with ngrams: {}'.format(mode,
np.mean(list(map(len, new_sequences)), dtype=int)), verbose=verbose)
self.print_seqlen_stats(new_sequences, '%s (w/ngrams)' % mode, verbose=verbose)
return new_sequences
def _create_ngram_set(self, input_list, ngram_value=2):
"""
Extract a set of n-grams from a list of integers.
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=2)
{(4, 9), (4, 1), (1, 4), (9, 4)}
>>> create_ngram_set([1, 4, 9, 4, 1, 4], ngram_value=3)
[(1, 4, 9), (4, 9, 4), (9, 4, 1), (4, 1, 4)]
"""
return set(zip(*[input_list[i:] for i in range(ngram_value)]))
def ngram_count(self):
if not self.tok_dct: return 1
s = set()
for k in self.tok_dct.keys():
s.add(len(k))
return max(list(s))
class BERTPreprocessor(TextPreprocessor):
"""
text preprocessing for BERT model
"""
def __init__(self, maxlen, max_features, class_names=[], classes=[],
lang='en', ngram_range=1, multilabel=None):
class_names = self.migrate_classes(class_names, classes)
if maxlen > 512: raise ValueError('BERT only supports maxlen <= 512')
super().__init__(maxlen, class_names, lang=lang, multilabel=multilabel)
vocab_path = os.path.join(get_bert_path(lang=lang), 'vocab.txt')
token_dict = {}
with codecs.open(vocab_path, 'r', 'utf8') as reader:
for line in reader:
token = line.strip()
token_dict[token] = len(token_dict)
tokenizer = BERT_Tokenizer(token_dict)
self.tok = tokenizer
self.tok_dct = dict((v,k) for k,v in token_dict.items())
self.max_features = max_features # ignored
self.ngram_range = 1 # ignored
def get_tokenizer(self):
return self.tok
def __getstate__(self):
return {k: v for k, v in self.__dict__.items()}
def __setstate__(self, state):
"""
For backwards compatibility with pre-ytransform versions
"""
self.__dict__.update(state)
if not hasattr(self, 'ytransform'):
le = self.label_encoder if hasattr(self, 'label_encoder') else None
self.ytransform = U.YTransform(class_names=self.get_classes(), label_encoder=le)
def get_preprocessor(self):
return (self.tok, self.tok_dct)
def preprocess(self, texts):
return self.preprocess_test(texts, verbose=0)[0]
def undo(self, doc):
"""
undoes preprocessing and returns raw data by:
converting a list or array of Word IDs back to words
"""
dct = self.tok_dct
return " ".join([dct[wid] for wid in doc if wid != 0 and wid in dct])
def preprocess_train(self, texts, y=None, mode='train', verbose=1):
"""
preprocess training set
"""
if mode == 'train' and y is None:
raise ValueError('y is required when mode=train')
if self.lang is None and mode=='train': self.lang = TU.detect_lang(texts)
U.vprint('preprocessing %s...' % (mode), verbose=verbose)
U.vprint('language: %s' % (self.lang), verbose=verbose)
x = bert_tokenize(texts, self.tok, self.maxlen, verbose=verbose)
# transform y
y = self._transform_y(y, train=mode=='train', verbose=verbose)
result = (x, y)
self.set_multilabel(result, mode)
if mode == 'train': self.preprocess_train_called = True
return result
def preprocess_test(self, texts, y=None, mode='test', verbose=1):
self.check_trained()
return self.preprocess_train(texts, y=y, mode=mode, verbose=verbose)
class TransformersPreprocessor(TextPreprocessor):
"""
text preprocessing for Hugging Face Transformer models
"""
def __init__(self, model_name,
maxlen, max_features, class_names=[], classes=[],
lang='en', ngram_range=1, multilabel=None):
class_names = self.migrate_classes(class_names, classes)
if maxlen > 512: raise ValueError('Transformer models only supports maxlen <= 512')
super().__init__(maxlen, class_names, lang=lang, multilabel=multilabel)
self.model_name = model_name
self.name = model_name.split('-')[0]
if model_name.startswith('xlm-roberta'):
self.name = 'xlm_roberta'
self.model_name = 'jplu/tf-' + self.model_name
else:
self.name = model_name.split('-')[0]
self.config = AutoConfig.from_pretrained(model_name)
self.model_type = TFAutoModelForSequenceClassification
self.tokenizer_type = AutoTokenizer
if "bert-base-japanese" in model_name:
self.tokenizer_type = transformers.BertJapaneseTokenizer
# NOTE: As of v0.16.1, do not unnecessarily instantiate tokenizer
# as it will be saved/pickled along with Preprocessor, which causes
# problems for some community-uploaded models like bert-base-japanse-whole-word-masking.
#tokenizer = self.tokenizer_type.from_pretrained(model_name)
#self.tok = tokenizer
self.tok = None # not pickled, see __getstate__
self.tok_dct = None
self.max_features = max_features # ignored
self.ngram_range = 1 # ignored
def __getstate__(self):
return {k: v for k, v in self.__dict__.items() if k not in ['tok']}
def __setstate__(self, state):
"""
For backwards compatibility with previous versions of ktrain
that saved tokenizer and did not use ytransform
"""
self.__dict__.update(state)
if not hasattr(self, 'tok'): self.tok = None
if not hasattr(self, 'ytransform'):
le = self.label_encoder if hasattr(self, 'label_encoder') else None
self.ytransform = U.YTransform(class_names=self.get_classes(), label_encoder=le)
def get_tokenizer(self, fpath=None):
model_name = self.model_name if fpath is None else fpath
if self.tok is None:
# use fast tokenizer if possible
if self.name == 'bert' and 'japanese' not in model_name:
from transformers import BertTokenizerFast
self.tok = BertTokenizerFast.from_pretrained(model_name)
elif self.name == 'distilbert':
from transformers import DistilBertTokenizerFast
self.tok = DistilBertTokenizerFast.from_pretrained(model_name)
elif self.name == 'roberta':
from transformers import RobertaTokenizerFast
self.tok = RobertaTokenizerFast.from_pretrained(model_name)
else:
self.tok = self.tokenizer_type.from_pretrained(model_name)
return self.tok
def save_tokenizer(self, fpath):
if os.path.isfile(fpath):
raise ValueError(f'There is an existing file named {fpath}. ' +\
'Please use dfferent value for fpath.')
elif os.path.exists(fpath):
pass
elif not os.path.exists(fpath):
os.makedirs(fpath)
tok =self.get_tokenizer()
tok.save_pretrained(fpath)
return
def get_preprocessor(self):
return (self.get_tokenizer(), self.tok_dct)
def preprocess(self, texts):
tseq = self.preprocess_test(texts, verbose=0)
return tseq.to_tfdataset(train=False)
def undo(self, doc):
"""
undoes preprocessing and returns raw data by:
converting a list or array of Word IDs back to words
"""
tok, _ = self.get_preprocessor()
return self.tok.convert_ids_to_tokens(doc)
#raise Exception('currently_unsupported: Transformers.Preprocessor.undo is not yet supported')
def preprocess_train(self, texts, y=None, mode='train', verbose=1):
"""
preprocess training set
"""
U.vprint('preprocessing %s...' % (mode), verbose=verbose)
U.check_array(texts, y=y, X_name='texts')
# detect sentence pairs
is_array, is_pair = detect_text_format(texts)
if not is_array: raise ValueError('texts must be a list of strings or a list of sentence pairs')
# detect language
if self.lang is None and mode=='train': self.lang = TU.detect_lang(texts)
U.vprint('language: %s' % (self.lang), verbose=verbose)
# print stats
if not is_pair: self.print_seqlen_stats(texts, mode, verbose=verbose)
if is_pair: U.vprint('sentence pairs detected', verbose=verbose)
# transform y
if y is None and mode == 'train':
raise ValueError('y is required for training sets')
elif y is None:
y = np.array([1] * len(texts))
y = self._transform_y(y, train=mode=='train', verbose=verbose)
# convert examples
tok, _ = self.get_preprocessor()
dataset = hf_convert_examples(texts, y=y, tokenizer=tok, max_length=self.maxlen,
pad_on_left=bool(self.name in ['xlnet']),
pad_token=tok.convert_tokens_to_ids([tok.pad_token][0]),
pad_token_segment_id=4 if self.name in ['xlnet'] else 0,
use_dynamic_shape=False if mode == 'train' else True,
verbose=verbose)
self.set_multilabel(dataset, mode, verbose=verbose)
if mode == 'train': self.preprocess_train_called = True
return dataset
def preprocess_test(self, texts, y=None, mode='test', verbose=1):
self.check_trained()
return self.preprocess_train(texts, y=y, mode=mode, verbose=verbose)
@classmethod
def load_model_and_configure_from_data(cls, fpath, transformer_ds):
"""
loads model from file path and configures loss function and metrics automatically
based on inspecting data
Args:
fpath(str): path to model folder
transformer_ds(TransformerDataset): an instance of TransformerDataset
"""
is_regression = U.is_regression_from_data(transformer_ds)
multilabel = U.is_multilabel(transformer_ds)
model = TFAutoModelForSequenceClassification.from_pretrained(fpath)
if is_regression:
metrics = ['mae']
loss_fn = 'mse'
else:
metrics = ['accuracy']
if multilabel:
loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)
else:
loss_fn = keras.losses.CategoricalCrossentropy(from_logits=True)
model.compile(loss=loss_fn,
optimizer=U.DEFAULT_OPT,
metrics=metrics)
return model
def _load_pretrained(self, mname, num_labels):
"""
load pretrained model
"""
if self.config is not None:
self.config.num_labels = num_labels
try: