-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdatasets.py
254 lines (181 loc) · 8.84 KB
/
datasets.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
from os.path import dirname, abspath, join, exists
from os import makedirs
from dictionaries import START_TOKEN, END_TOKEN
UNK_INDEX = 1
BASE_DIR = dirname(abspath(__file__))
class TranslationDatasetOnTheFly:
def __init__(self, phase, limit=None):
assert phase in ('train', 'val'), "Dataset phase must be either 'train' or 'val'"
self.limit = limit
if phase == 'train':
source_filepath = join(BASE_DIR, 'data', 'example', 'raw', 'src-train.txt')
target_filepath = join(BASE_DIR, 'data', 'example', 'raw', 'tgt-train.txt')
elif phase == 'val':
source_filepath = join(BASE_DIR, 'data', 'example', 'raw', 'src-val.txt')
target_filepath = join(BASE_DIR, 'data', 'example', 'raw', 'tgt-val.txt')
else:
raise NotImplementedError()
with open(source_filepath) as source_file:
self.source_data = source_file.readlines()
with open(target_filepath) as target_filepath:
self.target_data = target_filepath.readlines()
def __getitem__(self, item):
if self.limit is not None and item >= self.limit:
raise IndexError()
source = self.source_data[item].strip()
target = self.target_data[item].strip()
return source, target
def __len__(self):
if self.limit is None:
return len(self.source_data)
else:
return self.limit
class TranslationDataset:
def __init__(self, data_dir, phase, limit=None):
assert phase in ('train', 'val'), "Dataset phase must be either 'train' or 'val'"
self.limit = limit
self.data = []
with open(join(data_dir, f'raw-{phase}.txt')) as file:
for line in file:
source, target = line.strip().split('\t')
self.data.append((source, target))
def __getitem__(self, item):
if self.limit is not None and item >= self.limit:
raise IndexError()
return self.data[item]
def __len__(self):
if self.limit is None:
return len(self.data)
else:
return self.limit
@staticmethod
def prepare(train_source, train_target, val_source, val_target, save_data_dir):
if not exists(save_data_dir):
makedirs(save_data_dir)
for phase in ('train', 'val'):
if phase == 'train':
source_filepath = train_source
target_filepath = train_target
else:
source_filepath = val_source
target_filepath = val_target
with open(source_filepath) as source_file:
source_data = source_file.readlines()
with open(target_filepath) as target_filepath:
target_data = target_filepath.readlines()
with open(join(save_data_dir, f'raw-{phase}.txt'), 'w') as file:
for source_line, target_line in zip(source_data, target_data):
source_line = source_line.strip()
target_line = target_line.strip()
line = f'{source_line}\t{target_line}\n'
file.write(line)
class TokenizedTranslationDatasetOnTheFly:
def __init__(self, phase, limit=None):
self.raw_dataset = TranslationDatasetOnTheFly(phase, limit)
def __getitem__(self, item):
raw_source, raw_target = self.raw_dataset[item]
tokenized_source = raw_source.split()
tokenized_target = raw_target.split()
return tokenized_source, tokenized_target
def __len__(self):
return len(self.raw_dataset)
class TokenizedTranslationDataset:
def __init__(self, data_dir, phase, limit=None):
self.raw_dataset = TranslationDataset(data_dir, phase, limit)
def __getitem__(self, item):
raw_source, raw_target = self.raw_dataset[item]
tokenized_source = raw_source.split()
tokenized_target = raw_target.split()
return tokenized_source, tokenized_target
def __len__(self):
return len(self.raw_dataset)
class InputTargetTranslationDatasetOnTheFly:
def __init__(self, phase, limit=None):
self.tokenized_dataset = TokenizedTranslationDatasetOnTheFly(phase, limit)
def __getitem__(self, item):
tokenized_source, tokenized_target = self.tokenized_dataset[item]
full_target = [START_TOKEN] + tokenized_target + [END_TOKEN]
inputs = full_target[:-1]
targets = full_target[1:]
return tokenized_source, inputs, targets
def __len__(self):
return len(self.tokenized_dataset)
class InputTargetTranslationDataset:
def __init__(self, data_dir, phase, limit=None):
self.tokenized_dataset = TokenizedTranslationDataset(data_dir, phase, limit)
def __getitem__(self, item):
tokenized_source, tokenized_target = self.tokenized_dataset[item]
full_target = [START_TOKEN] + tokenized_target + [END_TOKEN]
inputs = full_target[:-1]
targets = full_target[1:]
return tokenized_source, inputs, targets
def __len__(self):
return len(self.tokenized_dataset)
class IndexedInputTargetTranslationDatasetOnTheFly:
def __init__(self, phase, source_dictionary, target_dictionary, limit=None):
self.input_target_dataset = InputTargetTranslationDatasetOnTheFly(phase, limit)
self.source_dictionary = source_dictionary
self.target_dictionary = target_dictionary
def __getitem__(self, item):
source, inputs, targets = self.input_target_dataset[item]
indexed_source = self.source_dictionary.index_sentence(source)
indexed_inputs = self.target_dictionary.index_sentence(inputs)
indexed_targets = self.target_dictionary.index_sentence(targets)
return indexed_source, indexed_inputs, indexed_targets
def __len__(self):
return len(self.input_target_dataset)
@staticmethod
def preprocess(source_dictionary):
def preprocess_function(source):
source_tokens = source.strip().split()
indexed_source = source_dictionary.index_sentence(source_tokens)
return indexed_source
return preprocess_function
class IndexedInputTargetTranslationDataset:
def __init__(self, data_dir, phase, vocabulary_size=None, limit=None):
self.data = []
unknownify = lambda index: index if index < vocabulary_size else UNK_INDEX
with open(join(data_dir, f'indexed-{phase}.txt')) as file:
for line in file:
sources, inputs, targets = line.strip().split('\t')
if vocabulary_size is not None:
indexed_sources = [unknownify(int(index)) for index in sources.strip().split(' ')]
indexed_inputs = [unknownify(int(index)) for index in inputs.strip().split(' ')]
indexed_targets = [unknownify(int(index)) for index in targets.strip().split(' ')]
else:
indexed_sources = [int(index) for index in sources.strip().split(' ')]
indexed_inputs = [int(index) for index in inputs.strip().split(' ')]
indexed_targets = [int(index) for index in targets.strip().split(' ')]
self.data.append((indexed_sources, indexed_inputs, indexed_targets))
if limit is not None and len(self.data) >= limit:
break
self.vocabulary_size = vocabulary_size
self.limit = limit
def __getitem__(self, item):
if self.limit is not None and item >= self.limit:
raise IndexError()
indexed_sources, indexed_inputs, indexed_targets = self.data[item]
return indexed_sources, indexed_inputs, indexed_targets
def __len__(self):
if self.limit is None:
return len(self.data)
else:
return self.limit
@staticmethod
def preprocess(source_dictionary):
def preprocess_function(source):
source_tokens = source.strip().split()
indexed_source = source_dictionary.index_sentence(source_tokens)
return indexed_source
return preprocess_function
@staticmethod
def prepare(data_dir, source_dictionary, target_dictionary):
join_indexes = lambda indexes: ' '.join(str(index) for index in indexes)
for phase in ('train', 'val'):
input_target_dataset = InputTargetTranslationDataset(data_dir, phase)
with open(join(data_dir, f'indexed-{phase}.txt'), 'w') as file:
for sources, inputs, targets in input_target_dataset:
indexed_sources = join_indexes(source_dictionary.index_sentence(sources))
indexed_inputs = join_indexes(target_dictionary.index_sentence(inputs))
indexed_targets = join_indexes(target_dictionary.index_sentence(targets))
file.write(f'{indexed_sources}\t{indexed_inputs}\t{indexed_targets}\n')