-
Notifications
You must be signed in to change notification settings - Fork 5
/
data.py
230 lines (198 loc) · 7.82 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
import os
import re
import logging
import torch
import constant as C
from torch.utils.data import Dataset
from collections import Counter
logger = logging.getLogger()
def bio_to_bioes(labels):
label_len = len(labels)
labels_bioes = []
for idx, label in enumerate(labels):
next_label = labels[idx + 1] if idx < label_len - 1 else 'O'
if label == 'O':
labels_bioes.append('O')
elif label.startswith('B-'):
if next_label.startswith('I-'):
labels_bioes.append(label)
else:
labels_bioes.append('S-' + label[2:])
else:
if next_label.startswith('I-'):
labels_bioes.append(label)
else:
labels_bioes.append('E-' + label[2:])
return labels_bioes
def _apply_processor(inst, processor):
for i, p in processor.items():
inst[i] = p(inst[i])
return inst
class ConllParser(object):
def __init__(self,
fields, separator='\t',
skip_comment=False,
processor=None):
self.fields = fields
self.separator = separator
self.skip_comment = skip_comment
self.processor = processor
def parse(self, path, *args, **kwargs):
fields = kwargs.get('fields', self.fields)
field_num = len(fields)
separator = kwargs.get('separator', self.separator)
skip_comment = kwargs.get('skip_comment', self.skip_comment)
files = []
if type(path) is list:
files = path
elif os.path.isdir(path):
files = [f for f in os.listdir(path) if os.path.isfile((f))]
elif os.path.isfile(path):
files = [path]
for file in files:
with open(file, 'r', encoding='utf-8') as r:
inst = [[] for _ in range(field_num)]
for line in r:
if skip_comment and line.startswith('#'):
continue
line = line.rstrip('\n')
if line:
segs = line.split(separator)
for field_idx, field in enumerate(fields):
inst[field_idx].append(segs[field])
elif inst[0]:
if self.processor:
inst = _apply_processor(inst, self.processor)
yield inst
inst = [[] for _ in range(field_num)]
if inst[0]:
if self.processor:
inst = _apply_processor(inst, self.processor)
yield inst
class NameTaggingDataset(Dataset):
def __init__(self, path, parser, max_seq_len=-1, gpu=True, min_char_len=4, to_bioes=False):
"""
:param path: Path to the data file.
:param parser: A parser that read and process the data file.
:param max_seq_len: Max sequence length (default=-1).
"""
self.path = path
self.parser = parser
self.max_seq_len = max_seq_len
self.data = []
self.gpu = gpu
self.min_char_len = min_char_len
self.to_bioes = to_bioes
self.load()
def __getitem__(self, idx):
return self.data[idx]
def __len__(self):
return len(self.data)
def load(self):
"""Load data from the file"""
# logger.info('Loading data from {}'.format(self.path))
self.data = [inst for inst in self.parser.parse(self.path)]
@property
def counters(self):
"""Get token, char, and label counters."""
token_counter = Counter()
char_counter = Counter()
label_counter = Counter()
for inst in self.data:
tokens, labels = inst[0], inst[1]
for token in tokens:
for c in token:
char_counter[c] += 1
token_counter.update(tokens)
label_counter.update(labels)
return token_counter, char_counter, label_counter
@property
def token_counter(self):
token_counter = Counter()
for inst in self.data:
token_counter.update(inst[0])
return token_counter
def numberize(self, vocabs):
"""Numberize the data set.
:param vocabs: A dictionary of vocabularies.
:param form_map: A mapping table from tokens in the data set to tokens
in pre-trained word embeddings.
"""
digit_pattern = re.compile('\d')
token_vocab = vocabs['token']
label_vocab = vocabs['label']
char_vocab = vocabs['char']
form_map = vocabs['form']
data = []
for inst in self.data:
tokens, labels = inst[0], inst[1]
if self.to_bioes:
labels = bio_to_bioes(labels)
# numberize tokens
tokens_ids = []
for token in tokens:
if token in token_vocab:
tokens_ids.append(token_vocab[token])
else:
token_lower = token.lower()
token_zero = re.sub(digit_pattern, '0', token_lower)
if token_lower in form_map:
tokens_ids.append(token_vocab[form_map[token_lower]])
elif token_zero in form_map:
tokens_ids.append(token_vocab[form_map[token_zero]])
else:
tokens_ids.append(C.UNK_INDEX)
# numberize characters and labels
label_ids = [label_vocab[l] for l in labels]
char_ids = [[char_vocab.get(c, C.UNK_INDEX) for c in t]
for t in tokens]
if self.max_seq_len > 0:
tokens_ids = tokens_ids[:self.max_seq_len]
label_ids = label_ids[:self.max_seq_len]
char_ids = char_ids[:self.max_seq_len]
data.append((tokens_ids, char_ids, label_ids, tokens, labels))
self.data = data
def batch_processor(self, batch):
pad = C.PAD_INDEX
# sort instances in decreasing order of sequence lengths
batch.sort(key=lambda x: len(x[0]), reverse=True)
# sequence lengths
seq_lens = [len(x[0]) for x in batch]
max_seq_len = max(seq_lens)
# character lengths
max_char_len = self.min_char_len
for seq in batch:
for chars in seq[1]:
if len(chars) > max_char_len:
max_char_len = len(chars)
# padding instances
batch_token_ids = []
batch_char_ids = []
batch_label_ids = []
batch_tokens = []
batch_labels = []
for token_ids, char_ids, label_ids, tokens, labels in batch:
seq_len = len(token_ids)
pad_num = max_seq_len - seq_len
batch_token_ids.append(token_ids + [pad] * pad_num)
batch_char_ids.extend(
# pad each word
[x + [pad] * (max_char_len - len(x)) for x in char_ids] +
# pad each sequence
[[pad] * max_char_len for _ in range(pad_num)]
)
batch_label_ids.append(label_ids + [pad] * pad_num)
batch_tokens.append(tokens)
batch_labels.append(labels)
if self.gpu:
batch_token_ids = torch.cuda.LongTensor(batch_token_ids)
batch_char_ids = torch.cuda.LongTensor(batch_char_ids)
batch_label_ids = torch.cuda.LongTensor(batch_label_ids)
seq_lens = torch.cuda.LongTensor(seq_lens)
else:
batch_token_ids = torch.LongTensor(batch_token_ids)
batch_char_ids = torch.LongTensor(batch_char_ids)
batch_label_ids = torch.LongTensor(batch_label_ids)
seq_lens = torch.LongTensor(seq_lens)
return (batch_token_ids, batch_char_ids, batch_label_ids, seq_lens,
batch_tokens, batch_labels)