-
Notifications
You must be signed in to change notification settings - Fork 9
/
handler.py
282 lines (231 loc) · 9.27 KB
/
handler.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
import os
import numpy as np
import pickle
import re
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from gensim.models import Word2Vec
np.random.seed(0)
word2vec_filename = "word2vec.model"
special_tokens = {'<PAD>': 0, '<BOS>': 1, '<EOS>': 2, '<UNK>': 3}
special_tokens_to_word = ['<PAD>', '<BOS>', '<EOS>', '<UNK>']
class Batch:
def __init__(self, batch_size = 0):
self.batch_size = batch_size
self.encoder_inputs = []
self.encoder_inputs_length = []
self.decoder_targets = []
self.decoder_targets_length = []
def printBatch(self): # debug
for i in range(self.batch_size):
print(self.encoder_inputs[i])
print(self.encoder_inputs_length[i])
print(self.decoder_targets[i])
print(self.decoder_targets_length[i])
print("-----")
class DatasetBase:
def __init__(self):
self.vocab_num = 0
self.word2idx = {}
self.idx2word = {}
self.data = []
self.perm = []
self.ptr = 0
def sentence_to_idx(self, sent, is_test=False):
l = []
unk_num = 0.0
for word in sent:
if word in self.word2idx:
l.append(self.word2idx[word])
else:
l.append(special_tokens['<UNK>'])
unk_num += 1
if not is_test and unk_num / float(len(sent)) > 0.1:#0.15:
emp = []
return emp
return l
def prep(self, data):
init = True
for i in range(len(data)):
reg = re.findall(r"[\w']+", data[i])
if len(reg) == 0: # +++$+++
init = True
continue
sent = text_to_word_sequence(data[i], lower=True, split=' ')
if len(sent) > 15 or len(sent) < 2: # too long
init = True
continue
idx_list = self.sentence_to_idx(sent)
if len(idx_list) == 0: # <UNK> too many
init = True
continue
if init:
_in = idx_list
init = False
else:
_out = idx_list
#_rev_in = list(reversed(_in))
# (the first EOS is part of the loss)
self.data.append([_in , _out + [special_tokens['<EOS>']]])
_in = idx_list
if i % 100000 == 0:
print("building data list: " + str(i) + "/" + str(len(data)) + " done.")
print('original line num:', len(data))
print('prep data num: ', len(self.data))
self.data = np.array(self.data)
self.perm = np.arange( len(self.data), dtype=np.int )
self.shuffle_perm()
def shuffle_perm(self):
np.random.shuffle(self.perm)
def next_batch(self, batch_size, shuffle = True):
ptr = self.ptr
max_size = len(self.data)
if ptr + batch_size <= max_size:
if shuffle:
d_list = self.data[self.perm[ptr:(ptr + batch_size)]]
else:
d_list = self.data[ptr:(ptr + batch_size)]
self.ptr += batch_size
else:
self.shuffle_perm()
print('shuffle perm...')
right = batch_size - (max_size - ptr)
if shuffle:
d_list = np.concatenate((self.data[self.perm[ptr:max_size]] , self.data[self.perm[0:right]]), axis=0)
else:
d_list = np.concatenate((self.data[ptr:max_size] , self.data[0:right]), axis=0)
self.ptr = right
return self.create_batch(d_list, batch_size)
def create_batch(self, samples, batch_size):
batch = Batch(batch_size)
batch.encoder_inputs_length = [len(sample[0]) for sample in samples]
batch.decoder_targets_length = [len(sample[1]) for sample in samples]
max_source_length = max(batch.encoder_inputs_length)
max_target_length = max(batch.decoder_targets_length)
for sample in samples:
source = sample[0]
pad = [special_tokens['<PAD>']] * (max_source_length - len(source))
#batch.encoder_inputs.append(pad + source)
batch.encoder_inputs.append(source + pad)
target = sample[1]
pad = [special_tokens['<PAD>']] * (max_target_length - len(target))
batch.decoder_targets.append(target + pad)
return batch
def load_dict(self): # for datasetEval
with open('word2idx.pkl', 'rb') as handle:
self.word2idx = pickle.load(handle)
with open('idx2word.pkl', 'rb') as handle:
self.idx2word = pickle.load(handle)
model = Word2Vec.load(word2vec_filename)
self.model = model
print('load word2vec model...done!')
self.vocab_num = len(self.word2idx)
print('self.vocab_num: ', self.vocab_num)
class DatasetTrain(DatasetBase):
def __init__(self):
super().__init__()
self.model = None
def build_dict(self, data_dir, filename, min_count,
train_line_num, eval_line_num, emb_size, PKL_EXIST=False):
# for datasetTrain
file_path = data_dir + filename
file = open(file_path, 'r')
raw_line = []
raw_line.append(['<PAD>'] * 3999999) #299999
raw_line.append(['<BOS>'] * 100)
raw_line.append(['<EOS>'] * 50)
raw_line.append(['<UNK>'] * 2999999) #39999
train_data = []
eval_data = []
cnt = 0
for line in file:
if cnt < train_line_num:
train_data.append(line)
else:
eval_data.append(line)
cnt += 1
reg = re.findall(r"[\w']+", line)
if len(reg) == 0:
continue
line = text_to_word_sequence(line, lower=True, split=" ")
line.insert(0, '<BOS>')
line.append('<EOS>')
raw_line.append(line)
assert len(train_data) == train_line_num
assert len(eval_data) == eval_line_num
if PKL_EXIST: # still need model!!
print('dict already exists, loading...')
print('Word2Vec model exists, loading...')
self.load_dict()
return train_data, eval_data
print('start building Word2Vec model...')
self.model = Word2Vec(raw_line, size=emb_size, sorted_vocab=1, min_count=min_count, workers=4)
self.model.save(word2vec_filename)
print('done building Word2Vec model!')
print('save model...')
cnt = 0
for word in self.model.wv.vocab:
ind = self.model.wv.vocab[word].index
self.word2idx[word] = ind
self.idx2word[ind] = word
cnt += 1
self.vocab_num = cnt
assert self.vocab_num == len(self.word2idx)
assert self.vocab_num == len(self.idx2word)
print('self.vocab_num: ', self.vocab_num)
with open('word2idx.pkl', 'wb') as handle:
pickle.dump(self.word2idx, handle)
with open('idx2word.pkl', 'wb') as handle:
pickle.dump(self.idx2word, handle)
return train_data, eval_data
class DatasetEval(DatasetBase):
def __init__(self):
super().__init__()
class DatasetTest(DatasetBase):
def __init__(self):
super().__init__()
self.test_data = []
def load_test_line(self, data_dir, filename):
file_path = data_dir + filename
file = open(file_path, 'r')
test_data = []
for line in file:
test_data.append(line)
return test_data
def next_batch(self, batch_size):
ptr = self.ptr
max_size = len(self.test_data)
if ptr + batch_size <= max_size:
d_list = self.test_data[ptr:(ptr + batch_size)]
self.ptr += batch_size
else:
print('warning!! over boundary')
right = batch_size - (max_size - ptr)
d_list = np.concatenate((self.test_data[ptr:max_size] , self.test_data[0:right]), axis=0)
self.ptr = right
return self.create_batch(d_list, batch_size)
def create_batch(self, samples, batch_size):
batch = Batch(batch_size)
batch.encoder_inputs_length = [len(sample) for sample in samples]
#batch.decoder_targets_length = [len(sample[1]) for sample in samples]
max_source_length = max(batch.encoder_inputs_length)
#max_target_length = max(batch.decoder_targets_length)
for sample in samples:
source = sample
pad = [special_tokens['<PAD>']] * (max_source_length - len(source))
#batch.encoder_inputs.append(pad + source)
batch.encoder_inputs.append(source + pad)
#target = sample[1]
#pad = [special_tokens['<PAD>']] * (max_target_length - len(target))
#batch.decoder_targets.append(target + pad)
return batch
def prep(self, data):
for i in range(len(data)):
line = data[i]
reg = re.findall(r"[\w']+", line)
if len(reg) == 0:
continue
sent = text_to_word_sequence(line, lower=True, split=" ")
_in = self.sentence_to_idx(sent, is_test=True)
#self.test_data.append(list(reversed(_in)))
self.test_data.append(_in)
print('test data num: ', len(self.test_data))