-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdata_loader.py
277 lines (222 loc) · 10.4 KB
/
data_loader.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
"""
bAbi data_loader
Original code : https://github.com/YerevaNN/Dynamic-memory-networks-in-Theano/blob/master/utils.py
"""
import os
from hbconfig import Config
import numpy as np
import tensorflow as tf
from tqdm import tqdm
class DataLoader:
def __init__(self, task_path, task_id, task_test_id, w2v_dim=100, input_mask_mode="sentence", use_pretrained=True):
self.base_path = "data/"
self.task_path = task_path
self.task_id = str(task_id)
self.task_test_id = str(task_test_id)
self.w2v_dim = w2v_dim
self.input_mask_mode = input_mask_mode
self.use_pretrained = use_pretrained
def make_train_and_test_set(self):
train_raw, test_raw = self.get_babi_raw(self.task_id, self.task_test_id)
self.max_facts_seq_len, self.max_fact_count, self.max_question_seq_len = self.get_max_seq_length(train_raw, test_raw)
if self.use_pretrained:
self.word2vec = self.load_glove(self.w2v_dim)
else:
self.word2vec = {}
self.vocab = {"unk": 0}
self.ivocab = {0: "unk"}
self.create_vector("unk")
train_input, train_question, train_answer = self.process_input(train_raw)
test_input, test_question, test_answer = self.process_input(test_raw)
return {
"train": (train_input, train_question, train_answer),
"test": (test_input, test_question, test_answer)
}
def get_max_seq_length(self, *datasets):
max_facts_length, max_fact_count, max_question_length = 0, 0, 0
def count_punctuation(facts):
return len(list(filter(lambda x: x == ".", facts)))
for dataset in datasets:
for d in dataset:
fact_lengths = [len(fact.split()) for fact in d['C'].split(".")]
max_facts_length = max(max_facts_length, max(fact_lengths))
fact_count = d['C'].split(".")
max_fact_count = max(max_fact_count, len(fact_count))
max_question_length = max(max_question_length, len(d['Q'].split()))
return max_facts_length, max_fact_count, max_question_length,
def init_babi(self, fname):
print("==> Loading test from %s" % fname)
tasks = []
task = None
for i, line in enumerate(open(fname)):
id = int(line[0:line.find(' ')])
if id == 1:
task = {"C": "", "Q": "", "A": ""}
line = line.strip()
line = line.replace('.', ' . ')
line = line[line.find(' ')+1:]
if line.find('?') == -1:
task["C"] += line
else:
idx = line.find('?')
tmp = line[idx+1:].split('\t')
task["Q"] = line[:idx]
task["A"] = tmp[1].strip()
tasks.append(task.copy())
return tasks
def get_babi_raw(self, id, test_id):
babi_map = {
"1": "qa1_single-supporting-fact",
"2": "qa2_two-supporting-facts",
"3": "qa3_three-supporting-facts",
"4": "qa4_two-arg-relations",
"5": "qa5_three-arg-relations",
"6": "qa6_yes-no-questions",
"7": "qa7_counting",
"8": "qa8_lists-sets",
"9": "qa9_simple-negation",
"10": "qa10_indefinite-knowledge",
"11": "qa11_basic-coreference",
"12": "qa12_conjunction",
"13": "qa13_compound-coreference",
"14": "qa14_time-reasoning",
"15": "qa15_basic-deduction",
"16": "qa16_basic-induction",
"17": "qa17_positional-reasoning",
"18": "qa18_size-reasoning",
"19": "qa19_path-finding",
"20": "qa20_agents-motivations",
"MCTest": "MCTest",
"19changed": "19changed",
"joint": "all_shuffled",
"sh1": "../shuffled/qa1_single-supporting-fact",
"sh2": "../shuffled/qa2_two-supporting-facts",
"sh3": "../shuffled/qa3_three-supporting-facts",
"sh4": "../shuffled/qa4_two-arg-relations",
"sh5": "../shuffled/qa5_three-arg-relations",
"sh6": "../shuffled/qa6_yes-no-questions",
"sh7": "../shuffled/qa7_counting",
"sh8": "../shuffled/qa8_lists-sets",
"sh9": "../shuffled/qa9_simple-negation",
"sh10": "../shuffled/qa10_indefinite-knowledge",
"sh11": "../shuffled/qa11_basic-coreference",
"sh12": "../shuffled/qa12_conjunction",
"sh13": "../shuffled/qa13_compound-coreference",
"sh14": "../shuffled/qa14_time-reasoning",
"sh15": "../shuffled/qa15_basic-deduction",
"sh16": "../shuffled/qa16_basic-induction",
"sh17": "../shuffled/qa17_positional-reasoning",
"sh18": "../shuffled/qa18_size-reasoning",
"sh19": "../shuffled/qa19_path-finding",
"sh20": "../shuffled/qa20_agents-motivations",
}
if (test_id == ""):
test_id = id
babi_name = babi_map[id]
babi_test_name = babi_map[test_id]
babi_train_raw = self.init_babi(os.path.join(self.base_path, self.task_path, '%s_train.txt' % babi_name))
babi_test_raw = self.init_babi(os.path.join(self.base_path, self.task_path, '%s_test.txt' % babi_test_name))
return babi_train_raw, babi_test_raw
def load_glove(self, dim):
word2vec = {}
print("==> loading glove")
with open(os.path.join(self.base_path, "glove/glove.6B." + str(dim) + "d.txt"), 'rb') as f:
for line in tqdm(f):
l = line.decode('utf-8').split()
word2vec[l[0]] = l[1:]
print("==> glove is loaded")
return word2vec
def create_vector(self, word, silent=False):
# if the word is missing from Glove, create some fake vector and store in glove!
vector = np.random.uniform(0.0, 1.0, (self.w2v_dim,))
self.word2vec[word] = vector
if (not silent):
print("data_loader.py::create_vector => %s is missing" % word)
return vector
def process_word(self, word, to_return="word2vec", silent=False):
if not word in self.word2vec:
self.create_vector(word, silent=silent)
if not word in self.vocab:
next_index = len(self.vocab)
self.vocab[word] = next_index
self.ivocab[next_index] = word
if to_return == "word2vec":
return self.word2vec[word]
elif to_return == "index":
return self.vocab[word]
else:
raise ValueError("return type is 'word2vec' or 'index'")
def get_norm(self, x):
x = np.array(x)
return np.sum(x * x)
def process_input(self, data_raw):
questions = []
inputs = []
answers = []
for x in data_raw:
facts = x["C"].lower().split('.')
facts = [fact.split() for fact in facts]
q = x["Q"].lower().split(' ')
q = [w for w in q if len(w) > 0]
facts_vector = []
for i in range(self.max_fact_count):
if i < len(facts):
fact_vector = [self.process_word(word=w, to_return="index") for w in facts[i]]
else:
fact_vector = [0]
fact_vector = self.pad_input(fact_vector, self.max_facts_seq_len, [0])
facts_vector.append(fact_vector)
q_vector = [self.process_word(word=w, to_return="index") for w in q]
q_vector = self.pad_input(q_vector, self.max_question_seq_len, [0])
inputs.append(facts_vector)
questions.append(q_vector)
answers.append(self.process_word(word=x["A"], to_return="index"))
return (np.array(inputs, dtype=np.int32),
np.array(questions, dtype=np.int32),
np.array(answers, dtype=np.int32).reshape(-1, 1))
def pad_input(self, input_, size, pad_item):
return input_ + pad_item * (size - len(input_))
def make_batch(self, data, buffer_size=10000, batch_size=64, scope="train"):
class IteratorInitializerHook(tf.train.SessionRunHook):
"""Hook to initialise data iterator after Session is created."""
def __init__(self):
super(IteratorInitializerHook, self).__init__()
self.iterator_initializer_func = None
def after_create_session(self, session, coord):
"""Initialise the iterator after the session has been created."""
self.iterator_initializer_func(session)
iterator_initializer_hook = IteratorInitializerHook()
def get_inputs():
with tf.name_scope(scope):
inputs, questions, answers = data
# Define placeholders
input_placeholder = tf.placeholder(
tf.int32, [None, Config.data.max_fact_count, Config.data.max_facts_seq_len])
question_placeholder = tf.placeholder(
tf.int32, [None, Config.data.max_question_seq_len])
answer_placeholder = tf.placeholder(
tf.int32, [None, 1])
# Build dataset iterator
dataset = tf.data.Dataset.from_tensor_slices(
(input_placeholder, question_placeholder, answer_placeholder))
if scope == "train":
dataset = dataset.repeat(None) # Infinite iterations
else:
dataset = dataset.repeat(1) # one Epoch
dataset = dataset.shuffle(buffer_size=buffer_size)
dataset = dataset.batch(batch_size)
iterator = dataset.make_initializable_iterator()
next_input, next_question, next_answer = iterator.get_next()
# Set runhook to initialize iterator
iterator_initializer_hook.iterator_initializer_func = \
lambda sess: sess.run(
iterator.initializer,
feed_dict={input_placeholder: inputs,
question_placeholder: questions,
answer_placeholder: answers})
# Return batched (features, labels)
features = {"input_data": next_input,
"question_data": next_question}
return (features, next_answer)
# Return function and hook
return get_inputs, iterator_initializer_hook