forked from flairNLP/flair
-
Notifications
You must be signed in to change notification settings - Fork 327
/
data.py
502 lines (396 loc) · 16.2 KB
/
data.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
from typing import List, Dict
import torch
from collections import Counter
from collections import defaultdict
from segtok.segmenter import split_single
from segtok.tokenizer import split_contractions
from segtok.tokenizer import word_tokenizer
class Dictionary:
"""
This class holds a dictionary that maps strings to IDs, used to generate one-hot encodings of strings.
"""
def __init__(self, add_unk=True):
# init dictionaries
self.item2idx: Dict[str, int] = {}
self.idx2item: List[str] = []
# in order to deal with unknown tokens, add <unk>
if add_unk:
self.add_item('<unk>')
def add_item(self, item: str) -> int:
"""
add string - if already in dictionary returns its ID. if not in dictionary, it will get a new ID.
:param item: a string for which to assign an id
:return: ID of string
"""
item = item.encode('utf-8')
if item not in self.item2idx:
self.idx2item.append(item)
self.item2idx[item] = len(self.idx2item) - 1
return self.item2idx[item]
def get_idx_for_item(self, item: str) -> int:
"""
returns the ID of the string, otherwise 0
:param item: string for which ID is requested
:return: ID of string, otherwise 0
"""
item = item.encode('utf-8')
if item in self.item2idx.keys():
return self.item2idx[item]
else:
return 0
def get_items(self) -> List[str]:
items = []
for item in self.idx2item:
items.append(item.decode('UTF-8'))
return items
def __len__(self) -> int:
return len(self.idx2item)
def get_item_for_index(self, idx):
return self.idx2item[idx].decode('UTF-8')
def save(self, savefile):
import pickle
with open(savefile, 'wb') as f:
mappings = {
'idx2item': self.idx2item,
'item2idx': self.item2idx
}
pickle.dump(mappings, f)
@classmethod
def load_from_file(cls, filename: str):
import pickle
dictionary: Dictionary = Dictionary()
with open(filename, 'rb') as f:
mappings = pickle.load(f, encoding='latin1')
idx2item = mappings['idx2item']
item2idx = mappings['item2idx']
dictionary.item2idx = item2idx
dictionary.idx2item = idx2item
return dictionary
@classmethod
def load(cls, name: str):
from flair.file_utils import cached_path
if name == 'chars' or name == 'common-chars':
base_path = 'https://s3.eu-central-1.amazonaws.com/alan-nlp/resources/models/common_characters'
char_dict = cached_path(base_path, cache_dir='datasets')
return Dictionary.load_from_file(char_dict)
return Dictionary.load_from_file(name)
class Token:
"""
This class represents one word in a tokenized sentence. Each token may have any number of tags. It may also point
to its head in a dependency tree.
"""
def __init__(self,
text: str,
idx: int = None,
head_id: int = None
):
self.text: str = text
self.idx: int = idx
self.head_id: int = head_id
self.sentence: Sentence = None
self._embeddings: Dict = {}
self.tags: Dict[str, str] = {}
def add_tag(self, tag_type: str, tag_value: str):
self.tags[tag_type] = tag_value
def get_tag(self, tag_type: str) -> str:
if tag_type in self.tags: return self.tags[tag_type]
return ''
def get_head(self):
return self.sentence.get_token(self.head_id)
def __str__(self) -> str:
return 'Token: %d %s' % (self.idx, self.text)
def set_embedding(self, name: str, vector: torch.autograd.Variable):
self._embeddings[name] = vector.cpu()
def clear_embeddings(self):
self._embeddings: Dict = {}
def get_embedding(self) -> torch.autograd.Variable:
embeddings = []
for embed in sorted(self._embeddings.keys()):
embeddings.append(self._embeddings[embed])
if embeddings:
return torch.cat(embeddings, dim=0)
return torch.FloatTensor()
@property
def embedding(self):
return self.get_embedding()
class Sentence:
def __init__(self, text: str = None, use_tokenizer: bool = False, labels: List[str] = None):
super(Sentence, self).__init__()
self.tokens: List[Token] = []
self.labels: List[str] = labels
self._embeddings: Dict = {}
# optionally, directly instantiate with sentence tokens
if text is not None:
# tokenize the text first if option selected, otherwise assumes whitespace tokenized text
if use_tokenizer:
sentences = split_single(text)
tokens = []
for sentence in sentences:
contractions = split_contractions(word_tokenizer(sentence))
tokens.extend(contractions)
text = ' '.join(tokens)
# add each word in tokenized string as Token object to Sentence
for word in text.split(' '):
self.add_token(Token(word))
def __getitem__(self, token_id: int) -> Token:
return self.get_token(token_id)
def __iter__(self):
return iter(self.tokens)
def add_label(self, label: str):
if self.labels is None:
self.labels = [label]
else:
self.labels.append(label)
def add_labels(self, labels: List[str]):
if self.labels is None:
self.labels = labels
else:
self.labels.extend(labels)
def get_token(self, token_id: int) -> Token:
for token in self.tokens:
if token.idx == token_id: return token
def add_token(self, token: Token):
self.tokens.append(token)
# set token idx if not set
token.sentence = self
if token.idx is None:
token.idx = len(self.tokens)
def set_embedding(self, name: str, vector):
self._embeddings[name] = vector.cpu()
def clear_embeddings(self, also_clear_word_embeddings: bool = True):
self._embeddings: Dict = {}
if also_clear_word_embeddings:
for token in self:
token.clear_embeddings()
def cpu_embeddings(self):
for name, vector in self._embeddings.items():
self._embeddings[name] = vector.cpu()
def get_embedding(self) -> torch.autograd.Variable:
embeddings = []
for embed in sorted(self._embeddings.keys()):
embedding = self._embeddings[embed]
embeddings.append(embedding)
if embeddings:
return torch.cat(embeddings, dim=0)
return torch.FloatTensor()
@property
def embedding(self):
return self.get_embedding()
def to_tagged_string(self) -> str:
list = []
for token in self.tokens:
list.append(token.text)
tags = []
for tag_type in token.tags.keys():
if token.get_tag(tag_type) == '' or token.get_tag(tag_type) == 'O': continue
tags.append(token.get_tag(tag_type))
all_tags = '<' + '/'.join(tags) + '>'
if all_tags != '<>':
list.append(all_tags)
return ' '.join(list)
# def to_tag_string(self, tag_type: str = 'tag') -> str:
#
# list = []
# for token in self.tokens:
# list.append(token.text)
# if token.get_tag(tag_type) == '' or token.get_tag(tag_type) == 'O': continue
# list.append('<' + token.get_tag(tag_type) + '>')
# return ' '.join(list)
#
# def to_ner_string(self) -> str:
# list = []
# for token in self.tokens:
# if token.get_tag('ner') == 'O' or token.get_tag('ner') == '':
# list.append(token.text)
# else:
# list.append(token.text)
# list.append('<' + token.get_tag('ner') + '>')
# return ' '.join(list)
def convert_tag_scheme(self, tag_type: str = 'ner', target_scheme: str = 'iob'):
tags: List[str] = []
for token in self.tokens:
token: Token = token
tags.append(token.get_tag(tag_type))
if target_scheme == 'iob':
iob2(tags)
if target_scheme == 'iobes':
iob2(tags)
tags = iob_iobes(tags)
for index, tag in enumerate(tags):
self.tokens[index].add_tag(tag_type, tag)
def __repr__(self):
return 'Sentence: "' + ' '.join([t.text for t in self.tokens]) + '" - %d Tokens' % len(self)
def __copy__(self):
s = Sentence()
for token in self.tokens:
nt = Token(token.text)
for tag_type in token.tags:
nt.add_tag(tag_type, token.get_tag(tag_type))
s.add_token(nt)
return s
def __str__(self) -> str:
return 'Sentence: "' + ' '.join([t.text for t in self.tokens]) + '" - %d Tokens' % len(self)
def to_plain_string(self) -> str:
return ' '.join([t.text for t in self.tokens])
def __len__(self) -> int:
return len(self.tokens)
class TaggedCorpus:
def __init__(self, train: List[Sentence], dev: List[Sentence], test: List[Sentence]):
self.train: List[Sentence] = train
self.dev: List[Sentence] = dev
self.test: List[Sentence] = test
def downsample(self, percentage: float = 0.1, only_downsample_train=False):
self.train = self._downsample_to_proportion(self.train, percentage)
if not only_downsample_train:
self.dev = self._downsample_to_proportion(self.dev, percentage)
self.test = self._downsample_to_proportion(self.test, percentage)
return self
def clear_embeddings(self):
for sentence in self.get_all_sentences():
for token in sentence.tokens:
token.clear_embeddings()
def get_all_sentences(self) -> List[Sentence]:
all_sentences: List[Sentence] = []
all_sentences.extend(self.train)
all_sentences.extend(self.dev)
all_sentences.extend(self.test)
return all_sentences
def make_tag_dictionary(self, tag_type: str) -> Dictionary:
# Make the tag dictionary
tag_dictionary: Dictionary = Dictionary()
tag_dictionary.add_item('O')
for sentence in self.get_all_sentences():
for token in sentence.tokens:
token: Token = token
tag_dictionary.add_item(token.get_tag(tag_type))
tag_dictionary.add_item('<START>')
tag_dictionary.add_item('<STOP>')
return tag_dictionary
def make_label_dictionary(self) -> Dictionary:
"""
Creates a dictionary of all labels assigned to the sentences in the corpus.
:return: dictionary of labels
"""
labels = set(self._get_all_labels())
label_dictionary: Dictionary = Dictionary(add_unk=False)
for label in labels:
label_dictionary.add_item(label)
return label_dictionary
def make_vocab_dictionary(self, max_tokens=-1, min_freq=1) -> Dictionary:
"""
Creates a dictionary of all tokens contained in the corpus.
By defining `max_tokens` you can set the maximum number of tokens that should be contained in the dictionary.
If there are more than `max_tokens` tokens in the corpus, the most frequent tokens are added first.
If `min_freq` is set the a value greater than 1 only tokens occurring more than `min_freq` times are considered
to be added to the dictionary.
:param max_tokens: the maximum number of tokens that should be added to the dictionary (-1 = take all tokens)
:param min_freq: a token needs to occur at least `min_freq` times to be added to the dictionary (-1 = there is no limitation)
:return: dictionary of tokens
"""
tokens = self._get_most_common_tokens(max_tokens, min_freq)
vocab_dictionary: Dictionary = Dictionary()
for token in tokens:
vocab_dictionary.add_item(token)
return vocab_dictionary
def _get_most_common_tokens(self, max_tokens, min_freq) -> List[Token]:
tokens_and_frequencies = Counter(self._get_all_tokens())
tokens_and_frequencies = tokens_and_frequencies.most_common()
tokens = []
for token, freq in tokens_and_frequencies:
if (min_freq != -1 and freq < min_freq) or (max_tokens != -1 and len(tokens) == max_tokens):
break
tokens.append(token)
return tokens
def _get_all_labels(self) -> List[str]:
return [label for sent in self.train for label in sent.labels]
def _get_all_tokens(self) -> List[str]:
tokens = list(map((lambda s: s.tokens), self.train))
tokens = [token for sublist in tokens for token in sublist]
return list(map((lambda t: t.text), tokens))
def _downsample_to_proportion(self, list: List, proportion: float):
counter = 0.0
last_counter = None
downsampled: List = []
for item in list:
counter += proportion
if int(counter) != last_counter:
downsampled.append(item)
last_counter = int(counter)
return downsampled
def print_statistics(self):
"""
Print statistics about the class distribution (only labels of sentences are taken into account) and sentence
sizes.
"""
self._print_statistics_for(self.train, "TRAIN")
self._print_statistics_for(self.test, "TEST")
self._print_statistics_for(self.dev, "DEV")
@staticmethod
def _print_statistics_for(sentences, name):
if len(sentences) == 0:
return
classes_to_count = TaggedCorpus._get_classes_to_count(sentences)
tokens_per_sentence = TaggedCorpus._get_tokens_per_sentence(sentences)
print(name)
print("total size: " + str(len(sentences)))
for l, c in classes_to_count.items():
print("size of class {}: {}".format(l, c))
print("total # of tokens: " + str(sum(tokens_per_sentence)))
print("min # of tokens: " + str(min(tokens_per_sentence)))
print("max # of tokens: " + str(max(tokens_per_sentence)))
print("avg # of tokens: " + str(sum(tokens_per_sentence) / len(sentences)))
@staticmethod
def _get_tokens_per_sentence(sentences):
return list(map(lambda x: len(x.tokens), sentences))
@staticmethod
def _get_classes_to_count(sentences):
classes_to_count = defaultdict(lambda: 0)
for sent in sentences:
for label in sent.labels:
classes_to_count[label] += 1
return classes_to_count
def __str__(self) -> str:
return 'TaggedCorpus: %d train + %d dev + %d test sentences' % (len(self.train), len(self.dev), len(self.test))
def iob2(tags):
"""
Check that tags have a valid IOB format.
Tags in IOB1 format are converted to IOB2.
"""
for i, tag in enumerate(tags):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return False
if split[0] == 'B':
continue
elif i == 0 or tags[i - 1] == 'O': # conversion IOB1 to IOB2
tags[i] = 'B' + tag[1:]
elif tags[i - 1][1:] == tag[1:]:
continue
else: # conversion IOB1 to IOB2
tags[i] = 'B' + tag[1:]
return True
def iob_iobes(tags):
"""
IOB -> IOBES
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == 'O':
new_tags.append(tag)
elif tag.split('-')[0] == 'B':
if i + 1 != len(tags) and \
tags[i + 1].split('-')[0] == 'I':
new_tags.append(tag)
else:
new_tags.append(tag.replace('B-', 'S-'))
elif tag.split('-')[0] == 'I':
if i + 1 < len(tags) and \
tags[i + 1].split('-')[0] == 'I':
new_tags.append(tag)
else:
new_tags.append(tag.replace('I-', 'E-'))
else:
raise Exception('Invalid IOB format!')
return new_tags