-
Notifications
You must be signed in to change notification settings - Fork 0
/
XLNET_NER.py
1888 lines (1511 loc) · 70 KB
/
XLNET_NER.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
#! usr/bin/env python3
# -*- coding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import io
import pickle
import re
import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
from absl import flags, logging
from xlnet import modeling
from xlnet import xlnet
# from xlnet import optimization
# from xlnet import tokenization
from xlnet import prepro_utils
import tensorflow as tf
import metrics
from tensorflow.contrib.layers.python.layers import initializers
from xlnet import model_utils
import numpy as np
from lstm_crf_layer import BLSTM_CRF
FLAGS = flags.FLAGS
import time
import json
import sentencepiece as sp
from tensorflow.contrib.layers.python.layers import initializers
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
MIN_FLOAT = -1e30
start=time.time()
## Required parameters
flags.DEFINE_string(
"data_dir", None,
"The input data dir. Should contain the .tsv files (or other data files) "
"for the task.")
flags.DEFINE_string(
"xlnet_config_file", None,
"The config json file corresponding to the pre-trained xlnet model. "
"This specifies the model architecture.")
flags.DEFINE_string(
"export_dir", None,
"export_dir")
flags.DEFINE_string("task_name", None, "The name of the task to train.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
flags.DEFINE_string(
"prefile", None,
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string(
"save_steps", None,
"save_steps")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_string(
"model_dir", None,
"model_dir")
flags.DEFINE_bool(
"do_export", True,
"do_export")
flags.DEFINE_bool(
"use_bfloat16", False,
"use_bfloat16")
# if you download cased checkpoint you should use "False",if uncased you should use
# "True"
# if we used in bio-medical field,don't do lower case would be better!
flags.DEFINE_bool(
"do_lower_case", False,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_float(
"dropout", 0.1,
"dropout")
flags.DEFINE_float(
"dropatt", 0.1,
"dropatt")
flags.DEFINE_string(
"init", "normal",
"init")
flags.DEFINE_string(
"decay_method", "poly",
"decay_method")
flags.DEFINE_string(
"predict_tag", "这个很好",
"predict_tag")
flags.DEFINE_float(
"init_range", 0.1,
"init_range")
flags.DEFINE_float(
"init_std", 0.02,
"init_range")
flags.DEFINE_float(
"min_lr_ratio", 0.0,
"min_lr_ratio")
flags.DEFINE_float(
"weight_decay", 0.15,
"weight_decay")
flags.DEFINE_float(
"adam_epsilon", 1e-8,
"adam_epsilon")
flags.DEFINE_float(
"clip", 1.0,
"clip")
flags.DEFINE_integer(
"clamp_len", -1,
"clamp_len")
flags.DEFINE_integer(
"warmup_steps", 0,
"warmup_steps")
flags.DEFINE_integer(
"train_steps", 100000,
"warmup_steps")
flags.DEFINE_integer(
"iterations", 1000,
"iterations")
flags.DEFINE_integer(
"num_hosts", 1,
"num_hosts")
flags.DEFINE_integer(
"max_save", 100000,
"max_save")
flags.DEFINE_integer(
"max_seq_length", 128,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_integer(
"num_core_per_host", 1,
"num_core_per_host")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.")
flags.DEFINE_bool(
"do_predict", False,
"Whether to run the model in inference mode on the test set.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.")
flags.DEFINE_integer("predict_batch_size", 16, "Total batch size for predict.")
flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
flags.DEFINE_string(
"do_pre_eval", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_string("middle_output", "middle_data", "Dir was used to store middle data!")
flags.DEFINE_bool("crf", True, "use crf!")
class InputExample(object):
"""A single training/test example for simple sequence classification."""
def __init__(self, guid, text, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
self.guid = guid
self.text = text
self.label = label
class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. The alternative is to drop the last batch, which is bad because it means
the entire output data won't be generated.
We use this class instead of `None` because treating `None` as padding
battches could cause silent errors.
"""
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
input_ids,
input_masks,
segment_ids,
label_ids):
self.input_ids = input_ids
self.input_masks = input_masks
self.segment_ids = segment_ids
self.label_ids = label_ids
class DataProcessor(object):
"""Base class for data converters for sequence classification data sets."""
def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError()
def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError()
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
def remove(text):
remove_chars = '[0-9’!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘’![\\]^_`{|}~]+'
return re.sub(remove_chars, ' ', text)
@classmethod
def _read_data(cls, input_file):
"""Read a BIO data!"""
rf = io.open(input_file, 'r', encoding='utf-8')
lines = [];
words = [];
labels = [];
num_words=0
num_sents=0
for line in rf:
word = line.strip().split(' ')[0]
label = line.strip().split(' ')[-1]
# here we dont do "DOCSTART" check
if len(line.strip()) == 0: #一句话的结束
num_sents+=1
num_words+=len(words)
l = ' '.join([label for label in labels if len(label) > 0])
w = ' '.join([word for word in words if len(word) > 0])
lines.append((l, w))
words = []
labels = []
words.append(word)
labels.append(label)
rf.close()
print("numbers of words",num_words)
print("numbers of sentences", num_sents)
return lines
class NerProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "eng.train.openNLP")), "train"
)
def get_dev_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "eng.testa.openNLP")), "dev"
)
def get_test_examples(self, data_dir):
return self._create_example(
self._read_data(os.path.join(data_dir, "eng.testb.openNLP")), "test"
)
def get_labels(self):
"""
here "X" used to represent "##eer","##soo" and so on!
"[PAD]" for padding
:return:
"""
return [ "<pad>", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "O", "X",
"<cls>", "<sep>"]
def _create_example(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
texts = prepro_utils.convert_to_unicode(line[1])
labels = prepro_utils.convert_to_unicode(line[0])
examples.append(InputExample(guid=guid, text=texts, label=labels))
return examples
class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. The alternative is to drop the last batch, which is bad because it means
the entire output data won't be generated.
We use this class instead of `None` because treating `None` as padding
battches could cause silent errors.
"""
# XLNET 分词类
class XLNetTokenizer(object):
"""Default text tokenizer for XLNet"""
def __init__(self,
sp_model_file,
lower_case=False):
"""Construct XLNet tokenizer"""
self.sp_processor = sp.SentencePieceProcessor()
self.sp_processor.Load(sp_model_file)
self.lower_case = lower_case
def tokenize(self, text):
"""Tokenize text for XLNet"""
processed_text = prepro_utils.preprocess_text(text, lower=self.lower_case)
tokenized_pieces = prepro_utils.encode_pieces(self.sp_processor, processed_text)
return tokenized_pieces
def encode(self, text):
"""Encode text for XLNet"""
processed_text = prepro_utils.preprocess_text(text, lower=self.lower_case)
encoded_ids = prepro_utils.encode_ids(self.sp_processor, processed_text)
return encoded_ids
def token_to_id(self,
token):
"""Convert token to id for XLNet"""
return self.sp_processor.PieceToId(token)
def id_to_token(self,
id):
"""Convert id to token for XLNet"""
return self.sp_processor.IdToPiece(id)
def tokens_to_ids(self,
tokens):
"""Convert tokens to ids for XLNet"""
return [self.sp_processor.PieceToId(token) for token in tokens]
def ids_to_tokens(self,
ids):
"""Convert ids to tokens for XLNet"""
return [self.sp_processor.IdToPiece(id) for id in ids]
# XLNET 数据预处理与模型
class XLNetExampleConverter(object):
"""Default example converter for XLNet"""
def __init__(self,
label_list,
max_seq_length,
tokenizer):
"""Construct XLNet example converter"""
self.special_vocab_list = ["<unk>", "<s>", "</s>", "<cls>", "<sep>", "<pad>", "<mask>", "<eod>", "<eop>"]
self.special_vocab_map = {}
for (i, special_vocab) in enumerate(self.special_vocab_list):
self.special_vocab_map[special_vocab] = i
self.segment_vocab_list = ["<a>", "<b>", "<cls>", "<sep>", "<pad>"]
self.segment_vocab_map = {}
for (i, segment_vocab) in enumerate(self.segment_vocab_list):
self.segment_vocab_map[segment_vocab] = i
self.label_list = label_list
self.label_map = {}
for (i, label) in enumerate(self.label_list):
self.label_map[label] = i
self.max_seq_length = max_seq_length
self.tokenizer = tokenizer
def convert_single_example(self, example, logging=True):
'''
对单个样本进行分析, 然后将字转化为id,标签转化为id,然后结构化到InputFeature中
:param example:
:param logging:
:return:
'''
# processors = {"ner": NerProcessor}
# label_list = processor.get_labels()
default_feature = InputFeatures(
input_ids=[0] * self.max_seq_length,
input_masks=[1] * self.max_seq_length,
segment_ids=[0] * self.max_seq_length,
label_ids=[0] * self.max_seq_length)
if isinstance(example, PaddingInputExample):
return default_feature
#token_items = self.tokenizer.tokenize(example.text)
textlist = example.text.split(' ')
label_items = example.label.split(' ')
# if len(label_items) != len([token for token in token_items if token.startswith(prepro_utils.SPIECE_UNDERLINE)]):
# return default_feature
tokens = []
labels = []
#idx = 0
for i, (word, label) in enumerate(zip(textlist, label_items)):
token = self.tokenizer.tokenize(word)
tokens.extend(token)
for i, _ in enumerate(token):
if i == 0:
labels.append(label)
else:
labels.append("X")
# print("len of tokens2",len(tokens))
# for token in textlist:
# tokn=self.tokenizer.tokenize(token)
# tokens.append(tokn)
# if token.startswith(prepro_utils.SPIECE_UNDERLINE):
# label = label_items[idx]
# idx += 1
# else:
# label = "X"
#
#
# labels.append(label)
if len(tokens) > self.max_seq_length - 2:
tokens = tokens[0:(self.max_seq_length - 2)]
if len(labels) > self.max_seq_length - 2:
labels = labels[0:(self.max_seq_length - 2)]
# for (i,token) in enumerate(tokens):
# print("token:",tokens[i])
# print("label",labels[i])
printable_tokens = [prepro_utils.printable_text(token) for token in tokens]
# The convention in XLNet is:
# (a) For sequence pairs:
# tokens: is it a dog ? [SEP] no , it is not . [SEP] [CLS]
# segment_ids: 0 0 0 0 0 0 1 1 1 1 1 1 1 2
# (b) For single sequences:
# tokens: this dog is big . [SEP] [CLS]
# segment_ids: 0 0 0 0 0 0 2
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the last vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense when
# the entire model is fine-tuned.
input_tokens = []
segment_ids = []
label_ids = []
for i, token in enumerate(tokens):
input_tokens.append(token)
segment_ids.append(self.segment_vocab_map["<a>"])
label_ids.append(self.label_map[labels[i]])
# input_tokens.append("<sep>")
# segment_ids.append(self.segment_vocab_map["<a>"])
# label_ids.append(self.label_map["<sep>"])
input_tokens.append("<cls>")
segment_ids.append(self.segment_vocab_map["<cls>"])
label_ids.append(self.label_map["<cls>"])
input_ids = self.tokenizer.tokens_to_ids(input_tokens)
# The mask has 0 for real tokens and 1 for padding tokens. Only real tokens are attended to.
input_masks = [0] * len(input_ids)
# Zero-pad up to the sequence length.
# while len(input_ids) < self.max_seq_length:
# input_ids.append(0)
# input_masks.append(0)
# segment_ids.append(0)
# label_ids.append(0)
if len(input_ids) < self.max_seq_length:
pad_seq_length = self.max_seq_length - len(input_ids)
input_ids = input_ids + [self.special_vocab_map["<pad>"]] * pad_seq_length
input_masks = input_masks + [1] * pad_seq_length
segment_ids = segment_ids + [self.segment_vocab_map["<pad>"]] * pad_seq_length
label_ids = label_ids + [self.label_map["<pad>"]] * pad_seq_length
input_tokens = input_tokens + ["<pad>"] * pad_seq_length
assert len(input_ids) == self.max_seq_length
assert len(input_masks) == self.max_seq_length
assert len(segment_ids) == self.max_seq_length
assert len(label_ids) == self.max_seq_length
assert len(input_masks) == self.max_seq_length
if logging:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("labels: %s" % " ".join(labels))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_masks: %s" % " ".join([str(x) for x in input_masks]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids]))
feature = InputFeatures(
input_ids=input_ids,
input_masks=input_masks,
segment_ids=segment_ids,
label_ids=label_ids)
return feature
def convert_single_example_2return(self, example, logging=True):
'''
对单个样本进行分析, 然后将字转化为id,标签转化为id,然后结构化到InputFeature中
:param example:
:param logging:
:return:
'''
# processors = {"ner": NerProcessor}
# label_list = processor.get_labels()
default_feature = InputFeatures(
input_ids=[0] * self.max_seq_length,
input_masks=[1] * self.max_seq_length,
segment_ids=[0] * self.max_seq_length,
label_ids=[0] * self.max_seq_length)
if isinstance(example, PaddingInputExample):
return default_feature
#token_items = self.tokenizer.tokenize(example.text)
textlist = example.text.split(' ')
label_items = example.label.split(' ')
# if len(label_items) != len([token for token in token_items if token.startswith(prepro_utils.SPIECE_UNDERLINE)]):
# return default_feature
tokens = []
labels = []
#idx = 0
for i, (word, label) in enumerate(zip(textlist, label_items)):
token = self.tokenizer.tokenize(word)
tokens.extend(token)
for i, _ in enumerate(token):
if i == 0:
labels.append(label)
else:
labels.append("X")
if len(tokens) > self.max_seq_length - 2:
tokens = tokens[0:(self.max_seq_length - 2)]
if len(labels) > self.max_seq_length - 2:
labels = labels[0:(self.max_seq_length - 2)]
# for (i,token) in enumerate(tokens):
# print("token:",tokens[i])
# print("label",labels[i])
printable_tokens = [prepro_utils.printable_text(token) for token in tokens]
# The convention in XLNet is:
# (a) For sequence pairs:
# tokens: is it a dog ? [SEP] no , it is not . [SEP] [CLS]
# segment_ids: 0 0 0 0 0 0 1 1 1 1 1 1 1 2
# (b) For single sequences:
# tokens: this dog is big . [SEP] [CLS]
# segment_ids: 0 0 0 0 0 0 2
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the last vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense when
# the entire model is fine-tuned.
input_tokens = []
segment_ids = []
label_ids = []
for i, token in enumerate(tokens):
input_tokens.append(token)
segment_ids.append(self.segment_vocab_map["<a>"])
label_ids.append(self.label_map[labels[i]])
# input_tokens.append("<sep>")
# segment_ids.append(self.segment_vocab_map["<a>"])
# label_ids.append(self.label_map["<sep>"])
input_tokens.append("<cls>")
segment_ids.append(self.segment_vocab_map["<cls>"])
label_ids.append(self.label_map["<cls>"])
input_ids = self.tokenizer.tokens_to_ids(input_tokens)
# The mask has 0 for real tokens and 1 for padding tokens. Only real tokens are attended to.
input_masks = [0] * len(input_ids)
# Zero-pad up to the sequence length.
# while len(input_ids) < self.max_seq_length:
# input_ids.append(0)
# input_masks.append(0)
# segment_ids.append(0)
# label_ids.append(0)
if len(input_ids) < self.max_seq_length:
pad_seq_length = self.max_seq_length - len(input_ids)
input_ids = input_ids + [self.special_vocab_map["<pad>"]] * pad_seq_length
input_masks = input_masks + [1] * pad_seq_length
segment_ids = segment_ids + [self.segment_vocab_map["<pad>"]] * pad_seq_length
label_ids = label_ids + [self.label_map["<pad>"]] * pad_seq_length
input_tokens = input_tokens + ["<pad>"] * pad_seq_length
assert len(input_ids) == self.max_seq_length
assert len(input_masks) == self.max_seq_length
assert len(segment_ids) == self.max_seq_length
assert len(label_ids) == self.max_seq_length
assert len(input_masks) == self.max_seq_length
if logging:
tf.logging.info("*** Example ***")
tf.logging.info("guid: %s" % (example.guid))
tf.logging.info("labels: %s" % " ".join(labels))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info("input_masks: %s" % " ".join([str(x) for x in input_masks]))
tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
tf.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids]))
feature = InputFeatures(
input_ids=input_ids,
input_masks=input_masks,
segment_ids=segment_ids,
label_ids=label_ids)
return feature, input_tokens, label_ids
def convert_examples_to_features(self, examples):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
for (idx, example) in enumerate(examples):
if idx % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (idx, len(examples)))
feature = self.convert_single_example(example, logging=(idx < 5))
features.append(feature)
return features
def convert_examples_to_features2return(self, examples):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
batch_tokens = []
batch_labels = []
for (idx, example) in enumerate(examples):
if idx % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (idx, len(examples)))
feature,ntokens, label_ids = self.convert_single_example_2return(example, logging=(idx < 5))
features.append(feature)
batch_tokens.extend(ntokens)
batch_labels.extend(label_ids)
print("len of grenerate dev tokens",len(batch_tokens))
return features,batch_tokens, batch_labels
def file_based_convert_examples_to_features(self, examples, output_file):
'''
将数据转化为TF_Record 结构,作为模型数据输入
:param examples:
:param output_file: tf_record数据
:return:
'''
def create_int_feature(values):
return tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
def create_float_feature(values):
return tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
with tf.python_io.TFRecordWriter(output_file) as writer:
alltokens = []
for (idx, example) in enumerate(examples):
if idx % 10000 == 0:
tf.logging.info("Writing example %d of %d" % (idx, len(examples)))
feature,token,lable = self.convert_single_example_2return(example, logging=(idx < 5))
# alltokens.append(token)
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_masks"] = create_float_feature(feature.input_masks)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["label_ids"] = create_int_feature(feature.label_ids)
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
# print("aaaaaaaaaaaaaaaaThis number of all tokens",len(alltokens))
class XLNetInputBuilder(object):
"""Default input builder for XLNet"""
@staticmethod
def get_input_builder(features,
seq_length,
is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
all_input_ids = []
all_input_masks = []
all_segment_ids = []
all_label_ids = []
for feature in features:
all_input_ids.append(feature.input_ids)
all_input_masks.append(feature.input_masks)
all_segment_ids.append(feature.segment_ids)
all_label_ids.append(feature.label_ids)
def input_fn(params,
input_context=None):
batch_size = params["batch_size"]
num_examples = len(features)
# This is for demo purposes and does NOT scale to large data sets. We do
# not use Dataset.from_generator() because that uses tf.py_func which is
# not TPU compatible. The right way to load data is with TFRecordReader.
d = tf.data.Dataset.from_tensor_slices({
"input_ids": tf.constant(all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32),
"input_masks": tf.constant(all_input_masks, shape=[num_examples, seq_length], dtype=tf.float32),
"segment_ids": tf.constant(all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32),
"label_ids": tf.constant(all_label_ids, shape=[num_examples, seq_length], dtype=tf.int32),
})
if input_context is not None:
tf.logging.info("Input pipeline id %d out of %d", input_context.input_pipeline_id,
input_context.num_replicas_in_sync)
d = d.shard(input_context.num_input_pipelines, input_context.input_pipeline_id)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100, seed=np.random.randint(10000))
d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)
return d
return input_fn
@staticmethod
def get_file_based_input_fn(input_file,
seq_length,
is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_masks": tf.FixedLenFeature([seq_length], tf.float32),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([seq_length], tf.int64),
}
def _decode_record(record,
name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32. So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params, input_context=None):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if input_context is not None:
tf.logging.info("Input pipeline id %d out of %d", input_context.input_pipeline_id,
input_context.num_replicas_in_sync)
d = d.shard(input_context.num_input_pipelines, input_context.input_pipeline_id)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100, seed=np.random.randint(10000))
d = d.apply(tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
@staticmethod
def get_serving_input_fn(seq_length):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def serving_input_fn():
with tf.variable_scope("serving"):
features = {
'input_ids': tf.placeholder(tf.int32, [None, seq_length], name='input_ids'),
'input_masks': tf.placeholder(tf.float32, [None, seq_length], name='input_masks'),
'segment_ids': tf.placeholder(tf.int32, [None, seq_length], name='segment_ids')
}
return tf.estimator.export.build_raw_serving_input_receiver_fn(features)()
return serving_input_fn
# xlnet 模型建立
class XLNetModelBuilder(object):
"""Default model builder for XLNet"""
def __init__(self,
model_config,
use_tpu=False):
"""Construct XLNet model builder"""
self.model_config = model_config
self.use_tpu = use_tpu
def _get_masked_data(self,
data_ids,
label_list):
label_map = {}
for (i, label) in enumerate(label_list):
label_map[label] = i
pad_id = tf.constant(label_map["<pad>"], shape=[], dtype=tf.int32)
out_id = tf.constant(label_map["O"], shape=[], dtype=tf.int32)
x_id = tf.constant(label_map["X"], shape=[], dtype=tf.int32)
cls_id = tf.constant(label_map["<cls>"], shape=[], dtype=tf.int32)
sep_id = tf.constant(label_map["<sep>"], shape=[], dtype=tf.int32)
masked_data_ids = (tf.cast(tf.not_equal(data_ids, pad_id), dtype=tf.int32) *
tf.cast(tf.not_equal(data_ids, out_id), dtype=tf.int32) *
tf.cast(tf.not_equal(data_ids, x_id), dtype=tf.int32) *
tf.cast(tf.not_equal(data_ids, cls_id), dtype=tf.int32) *
tf.cast(tf.not_equal(data_ids, sep_id), dtype=tf.int32))
return masked_data_ids
def _create_model(self,
input_ids,
input_masks,
segment_ids,
label_ids,
label_list,
mode):
# 写入label2id:
label_map = {}
# here start with zero this means that "[PAD]" is zero
for (i, label) in enumerate(label_list):
label_map[label] = i
with open(FLAGS.middle_output + "/label2id.pkl", 'wb') as w:
pickle.dump(label_map, w)
#print("shaple of inputid", input_ids.shape)
"""Creates XLNet-NER model"""
model = xlnet.XLNetModel(
xlnet_config=self.model_config,
run_config=xlnet.create_run_config(mode == tf.estimator.ModeKeys.TRAIN, True, FLAGS),
# input_ids=input_ids,
# input_mask=input_masks,
# seg_ids=segment_ids
input_ids = tf.transpose(input_ids, perm=[1, 0]),
input_mask = tf.transpose(input_masks, perm=[1, 0]),
seg_ids = tf.transpose(segment_ids, perm=[1, 0]))
# 不添加lstm
# output_layer = model.get_sequence_output()
# # output_layer shape is
# if is_training:
# output_layer = tf.keras.layers.Dropout(rate=0.1)(output_layer)
# logits = hidden2tag(output_layer, num_labels)
# # TODO test shape
# logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, num_labels])
# if FLAGS.crf:
# mask2len = tf.reduce_sum(mask, axis=1)
# loss, trans = crf_loss(logits, labels, mask, num_labels, mask2len)
# predict, viterbi_score = tf.contrib.crf.crf_decode(logits, trans, mask2len)
# return (loss, logits, predict)
#
# else:
# loss, predict = softmax_layer(logits, labels, num_labels, mask)
#
# return (loss, logits, predict)
#xlnet 不加BILSTM_CRF写法
# initializer = model.get_initializer()
#
# with tf.variable_scope("ner", reuse=tf.AUTO_REUSE):
# result = tf.transpose(model.get_sequence_output(), perm=[1, 0, 2])