This repository was archived by the owner on Aug 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdata_iterator.py
More file actions
283 lines (222 loc) · 8.59 KB
/
data_iterator.py
File metadata and controls
283 lines (222 loc) · 8.59 KB
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
import torch
import numpy as np
import shuffle
import data_utils
from util import fopen
from util import load_dict
'''
Majority of this code is borrowed from the data_iterator.py of
nematus project (https://github.com/rsennrich/nematus)
'''
class TextIterator:
"""Simple Text iterator."""
def __init__(self, source, source_dict,
batch_size=128, maxlen=None,
n_words_source=-1,
skip_empty=False,
shuffle_each_epoch=False,
sort_by_length=False,
maxibatch_size=20,):
if shuffle_each_epoch:
self.source_orig = source
self.source = shuffle.main([self.source_orig], temporary=True)
else:
self.source = fopen(source, 'r')
self.source_dict = load_dict(source_dict)
self.batch_size = batch_size
self.maxlen = maxlen
self.skip_empty = skip_empty
self.n_words_source = n_words_source
if self.n_words_source > 0:
for key, idx in self.source_dict.items():
if idx >= self.n_words_source:
del self.source_dict[key]
self.shuffle = shuffle_each_epoch
self.sort_by_length = sort_by_length
self.shuffle = shuffle_each_epoch
self.sort_by_length = sort_by_length
self.source_buffer = []
self.k = batch_size * maxibatch_size
self.end_of_data = False
def __iter__(self):
return self
def __len__(self):
return sum([1 for _ in self])
def reset(self):
if self.shuffle:
self.source = shuffle.main([self.source_orig], temporary=True)
else:
self.source.seek(0)
def next(self):
if self.end_of_data:
self.end_of_data = False
self.reset()
raise StopIteration
source = []
# fill buffer, if it's empty
if len(self.source_buffer) == 0:
for k_ in xrange(self.k):
chars = []
map(chars.extend, ss)
self.source_buffer.append(ss[:-1])
if not ss:
break
self.source_buffer.append(ss.strip().split())
# sort by buffer
if self.sort_by_length:
slen = np.array([len(s) for s in self.source_buffer])
sidx = slen.argsort()
_sbuf = [self.source_buffer[i] for i in sidx]
self.source_buffer = _sbuf
else:
self.source_buffer.reverse()
if len(self.source_buffer) == 0:
self.end_of_data = False
self.reset()
raise StopIteration
try:
# actual work here
while True:
# read from source file and map to word index
try:
ss = self.source_buffer.pop()
except IndexError:
break
if self.maxlen and len(ss) > self.maxlen:
continue
if self.skip_empty and (not ss):
continue
ss = [self.source_dict[w] if w in self.source_dict
else data_utils.unk_token for w in ss]
source.append(ss)
if len(source) >= self.batch_size:
break
except IOError:
self.end_of_data = True
# all sentence pairs in maxibatch filtered out because of length
if len(source) == 0:
source = self.next()
return source
class BiTextIterator:
"""Simple Bitext iterator."""
def __init__(self, source, target,
source_dict, target_dict,
batch_size=128,
maxlen=None,
n_words_source=-1,
n_words_target=-1,
skip_empty=False,
shuffle_each_epoch=False,
sort_by_length=True,
maxibatch_size=20):
if shuffle_each_epoch:
self.source_orig = source
self.target_orig = target
self.source, self.target = shuffle.main([self.source_orig, self.target_orig], temporary=True)
else:
self.source = fopen(source, 'r')
self.target = fopen(target, 'r')
self.source_dict = load_dict(source_dict)
self.target_dict = load_dict(target_dict)
self.batch_size = batch_size
self.maxlen = maxlen
self.skip_empty = skip_empty
self.n_words_source = n_words_source
self.n_words_target = n_words_target
if self.n_words_source > 0:
for key, idx in self.source_dict.items():
if idx >= self.n_words_source:
del self.source_dict[key]
if self.n_words_target > 0:
for key, idx in self.target_dict.items():
if idx >= self.n_words_target:
del self.target_dict[key]
self.shuffle = shuffle_each_epoch
self.sort_by_length = sort_by_length
self.source_buffer = []
self.target_buffer = []
self.k = batch_size * maxibatch_size
self.end_of_data = False
def __iter__(self):
return self
def __len__(self):
return sum([1 for _ in self])
def reset(self):
if self.shuffle:
self.source, self.target = shuffle.main([self.source_orig, self.target_orig], temporary=True)
else:
self.source.seek(0)
self.target.seek(0)
def next(self):
if self.end_of_data:
self.end_of_data = False
self.reset()
raise StopIteration
source = []
target = []
# fill buffer, if it's empty
assert len(self.source_buffer) == len(self.target_buffer), 'Buffer size mismatch!'
if len(self.source_buffer) == 0:
for k_ in xrange(self.k):
ss = self.source.readline()
if not ss:
break
tt = self.target.readline()
if not tt:
break
#changed this part to make it character level and omit the newline
chars = []
map(chars.extend, ss)
self.source_buffer.append(ss[:-1])
chars = []
map(chars.extend, tt)
self.target_buffer.append(tt[:-1])
# sort by target buffer
if self.sort_by_length:
tlen = np.array([len(t) for t in self.target_buffer])
tidx = tlen.argsort()
_sbuf = [self.source_buffer[i] for i in tidx]
_tbuf = [self.target_buffer[i] for i in tidx]
self.source_buffer = _sbuf
self.target_buffer = _tbuf
else:
self.source_buffer.reverse()
self.target_buffer.reverse()
if len(self.source_buffer) == 0 or len(self.target_buffer) == 0:
self.end_of_data = False
self.reset()
raise StopIteration
try:
# actual work here
while True:
# read from source file and map to word index
try:
#print ("ss before pop", ss)
ss = self.source_buffer.pop()
except IndexError:
break
# read from target file and map to word index
tt = self.target_buffer.pop()
if self.maxlen:
if len(ss) > self.maxlen and len(tt) > self.maxlen:
continue
if self.skip_empty and (not ss or not tt):
continue
ss = [self.source_dict[w] if w in self.source_dict
else data_utils.unk_token for w in ss]
tt = [self.target_dict[w] if w in self.target_dict
else data_utils.unk_token for w in tt]
if self.n_words_target > 0:
tt = [w if w < self.n_words_target
else data_utils.unk_token for w in tt]
source.append(ss)
target.append(tt)
if len(source) >= self.batch_size or \
len(target) >= self.batch_size:
break
except IOError:
self.end_of_data = True
# all sentence pairs in maxibatch filtered out because of length
if len(source) == 0 or len(target) == 0:
source, target = self.next()
return source, target