-
Notifications
You must be signed in to change notification settings - Fork 14
/
data_utils.py
284 lines (235 loc) · 8.26 KB
/
data_utils.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
# encoding=utf-8
# Project: transfer_cws
# Author: xingjunjie
# Create Time: 17/08/2017 11:55 AM on PyCharm
import os
import numpy as np
UNK = 'UNK_WORD'
"""
Data utils for tf implement
"""
def _pad_sequences(sequences, pad_tok, max_length):
sequence_padded, sequence_length = [], []
for seq in sequences:
seq = list(seq)
seq_ = seq[:max_length] + [pad_tok] * max(max_length - len(seq), 0)
sequence_padded += [seq_]
sequence_length += [min(len(seq), max_length)]
return sequence_padded, sequence_length
def pad_sequences(sequences, pad_tok):
max_length = max(map(lambda x: len(x), sequences))
sequence_padded, sequence_length = _pad_sequences(sequences, pad_tok, max_length)
return sequence_padded, sequence_length
def minibatches(data, minibatch_size, circle=False):
"""
Args:
data: generator of (sentence, tags) tuples
minibatch_size: (int)
Returns:
list of tuples
"""
# if mini_padding:
# data.sort(key=lambda x: len(x[0]))
x_batch, y_batch, z_batch = [], [], []
while True:
for (x, y, z) in data:
if len(x_batch) == minibatch_size:
yield x_batch, y_batch, z_batch
x_batch, y_batch, z_batch = [], [], []
if type(x[0]) == tuple:
x = zip(*x)
x_batch += [x]
y_batch += [y]
z_batch += [z]
if not circle:
break
if len(x_batch) != 0:
yield x_batch, y_batch, z_batch
def minibatches_evaluate(data, minibatch_size, mini_padding=True):
"""
Args:
data: generator of (sentence, tags) tuples
minibatch_size: (int)
Returns:
list of tuples
"""
# if mini_padding:
# data.sort(key=lambda x: len(x[0]))
x_batch, y_batch, z_batch = [], [], []
for x, y, z in data:
if len(x_batch) == minibatch_size:
yield x_batch, y_batch, z_batch
x_batch, y_batch, z_batch = [], [], []
x_batch += [x]
y_batch += [y]
z_batch += [z]
if len(x_batch) != 0:
yield x_batch, y_batch, z_batch
def get_chunk_type(tok, idx_to_tag):
"""
Args:
tok: id of token, ex 4
idx_to_tag: dictionary {4: "B-PER", ...}
Returns:
tuple: "B", "PER"
"""
tag_name = idx_to_tag[tok]
tag_class = tag_name.split('-')[0]
tag_type = tag_name.split('-')[-1]
return tag_class, tag_type
def get_chunks(seq, tags):
"""
Args:
seq: [4, 4, 0, 0, ...] sequence of labels
tags: dict["O"] = 4
Returns:
list of (chunk_type, chunk_start, chunk_end)
Example:
seq = [4, 5, 0, 3]
tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3}
result = [("PER", 0, 2), ("LOC", 3, 4)]
"""
idx_to_tag = {idx: tag for tag, idx in tags.items()}
chunks = []
chunk_type, chunk_start = None, None
for i, tok in enumerate(seq):
# End of a chunk + start of a chunk!
tok_chunk_class, tok_chunk_type = get_chunk_type(tok, idx_to_tag)
if chunk_type is None:
chunk_type, chunk_start = tok_chunk_type, i
elif tok_chunk_type != chunk_type or tok_chunk_class == "B" or tok_chunk_class == "S":
chunk = (chunk_type, chunk_start, i)
chunks.append(chunk)
chunk_type, chunk_start = tok_chunk_type, i
# end condition
if chunk_type is not None:
chunk = (chunk_type, chunk_start, len(seq))
chunks.append(chunk)
return chunks
class EvaluateSet(object):
def __init__(self, filename, processing_word, processing_target_word=None):
self.filename = filename
self.processing_word = processing_word
self.processing_target_word = processing_target_word
self.length = None
def __iter__(self):
with open(self.filename, 'r') as infile:
for line in infile:
line = line[:-1]
if line:
idx = self.processing_word(line)
if self.processing_target_word is not None:
target_idx = self.processing_target_word(line)
yield (idx, target_idx, list(line))
else:
yield (idx, [], list(line))
def __len__(self):
if self.length is None:
self.length = 0
for _ in self:
self.length += 1
return self.length
class Dataset(object):
def __init__(self, filename, processing_word, processing_tag, processing_target_word=None,
transfer_flag=0):
self.filename = filename
self.processing_word = processing_word
self.processing_tag = processing_tag
self.processing_target_word = processing_target_word
self.transfer_flag = transfer_flag
self.length = None
def __iter__(self):
with open(self.filename, encoding='utf-8') as infile:
words, tags, target_words = [], [], []
for line in infile:
line = line[:-1]
if len(line) == 0:
if len(words):
yield words, tags, target_words
words, tags, target_words = [], [], []
else:
items = line.split('\t')
assert len(items) == 2
word, tag = items[0], items[1]
word_idx = self.processing_word(word)
tag_idx = self.processing_tag(tag)
words.append(word_idx)
tags.append(tag_idx)
if self.transfer_flag:
target_idx = self.processing_target_word(word)
target_words.append(target_idx)
def __len__(self):
if self.length is None:
self.length = 0
for _ in self:
self.length += 1
return self.length
def get_vocabs(datasets):
"""
Args:
datasets: a list of dataset objects
Return:
a set of all the words in the dataset
"""
print("Building vocab...")
vocab_words = set()
vocab_tags = set()
for dataset in datasets:
for words, tags in dataset:
vocab_words.update(words)
vocab_tags.update(tags)
print("- done. {} tokens".format(len(vocab_words)))
return vocab_words, vocab_tags
def load_pre_train(file_path):
pre_dictionary = dict()
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as infile:
lines = infile.readlines()
try:
num, embedding_size = lines[0].split()
num = int(num)
embedding_size = int(embedding_size)
except Exception as e:
return None, None
assert num == len(lines) - 1
embedding = np.zeros((num, embedding_size), dtype=float)
for index, line in enumerate(lines[1:]):
items = line.split()
assert len(items) == embedding_size + 1, print(index)
word = items[0]
pre_dictionary[word] = len(pre_dictionary)
embed = np.zeros((embedding_size,), dtype=float)
for i in range(0, embedding_size):
embed[i] = float(items[i + 1])
embedding[index] = embed
return pre_dictionary, embedding
def load_vocab(filename, base_dict=None):
if base_dict == None:
base_dict = dict()
if UNK not in base_dict:
base_dict[UNK] = len(base_dict)
word_dict = base_dict
tag_dict = dict()
# tag_dict[UNK] = len(tag_dict)
with open(filename, 'r', encoding='utf-8') as infile:
for line in infile:
line = line[:-1]
if len(line) > 0:
items = line.split('\t')
assert len(items) == 2
if items[0] not in word_dict:
word_dict[items[0]] = len(word_dict)
if items[1] not in tag_dict:
tag_dict[items[1]] = len(tag_dict)
return word_dict, tag_dict
def get_processing(vocab=None, default_key=UNK):
def f(item):
if len(item) > 1:
item = list(item)
return [f(i) for i in item]
if item in vocab:
item = vocab[item]
else:
item = vocab[default_key]
return item
return f