-
Notifications
You must be signed in to change notification settings - Fork 40
/
preprocess-qa.py
278 lines (219 loc) · 9.1 KB
/
preprocess-qa.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
#!/usr/bin/env python
""" Create data for QA bAbI tasks """
import numpy as np
import h5py
import argparse
import sys
import re
import codecs
import copy
import operator
import json
import glob, os
import csv
import re
START_TOKEN = "<s>"
END_TOKEN = "</s>"
PAD_TOKEN = "PADDING"
RARE_TOKEN = "RARE"
MAX_QUESTION = 0
MAX_FACT = 0
NUM_TASKS = 20
args = {}
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def init_vocab():
return { RARE_TOKEN : 1, PAD_TOKEN : 2, START_TOKEN: 3, END_TOKEN: 4 }
def write_dict(file, dict):
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))
writer = csv.writer(open(file, 'wb'))
for key, value in sorted_dict:
writer.writerow([key, value])
def get_vocab(folder, word_to_idx = {}):
if len(word_to_idx) == 0:
word_to_idx = init_vocab()
idx = len(word_to_idx) + 1
owd = os.getcwd()
os.chdir(folder)
for infile in glob.glob("*.txt"):
with open(infile) as inf:
for line in inf:
parts = line.lower().replace('.','').strip().split('?')
tokens = parts[0].split(' ')
for i in np.arange(1, len(tokens)):
if tokens[i] not in word_to_idx and not is_number(tokens[i]):
word_to_idx[tokens[i]] = idx
idx += 1
if len(parts) > 1:
answer = parts[1].strip().split('\t')[0]
if answer not in word_to_idx:
word_to_idx[answer.lower()] = idx
idx += 1
os.chdir(owd)
return word_to_idx
def normalize(data, word_to_idx):
for t in np.arange(NUM_TASKS) + 1:
questions = data[t]['questions']
answers = data[t]['answers']
facts = data[t]['facts']
pad_idx = word_to_idx[PAD_TOKEN]
norm_questions = np.ones((len(questions), MAX_QUESTION)) * pad_idx
norm_answers = np.array(answers)
norm_facts = np.zeros((len(facts), MAX_FACT))
for i in range(len(questions)):
norm_questions[i, : len(questions[i])] = questions[i]
for i in range(len(facts)):
norm_facts[i, : len(facts[i])] = facts[i]
data[t]['questions'] = norm_questions
data[t]['answers'] = norm_answers
data[t]['facts'] = norm_facts
def process_answer(label, task_no, word_to_idx):
'''
Process output label for each sentence depending on the task number.
'''
parts = label.strip().split('\t')
# TODO: ignore caps in answer?
return word_to_idx[parts[0].lower()], parts[1].split(' ')
def process_task_max(file, task_no, task_to_max, word_to_idx):
pad_idx = word_to_idx[PAD_TOKEN]
# first loop to get max number of sentences for each story
if task_no not in task_to_max:
task_to_max[task_no] = {}
task_to_max[task_no]['max_line_num'] = 0
task_to_max[task_no]['max_line_len'] = 0
with open(file) as inf:
num_story_line = 0
for line in inf:
line_info = re.match('([0-9].*?)\ (.*)', line)
line_no = int(line_info.group(1)) # line number
if line_no == 1:
task_to_max[task_no]['max_line_num'] = max(task_to_max[task_no]['max_line_num'], num_story_line)
num_story_line = 0
line_length = len(line_info.group(2).strip().split(' ')) # rest of line
if line_length > task_to_max[task_no]['max_line_len']:
task_to_max[task_no]['max_line_len'] = line_length
if '?' not in line:
num_story_line += 1
task_to_max[task_no]['max_line_num'] = max(task_to_max[task_no]['max_line_num'], num_story_line)
def process(file, task_no, task_to_max, word_to_idx):
'''
Process one single QA file (either train or test).
'''
global MAX_QUESTION
global MAX_FACT
pad_idx = word_to_idx[PAD_TOKEN]
# first loop to get max number of sentences for each story
MAX_LINE_NUM = task_to_max[task_no]['max_line_num']
MAX_LINE_LEN = task_to_max[task_no]['max_line_len']
NUM_QUESTION = 0
with open(file) as inf:
for line in inf:
if '?' in line:
NUM_QUESTION += 1
all_stories = np.ones((NUM_QUESTION, MAX_LINE_NUM, MAX_LINE_LEN + 2)) * pad_idx
all_line_nos = np.zeros((NUM_QUESTION, MAX_LINE_NUM))
all_questions = []
all_answers = []
all_facts = []
current_story = []
current_line_nos = []
with open(file) as inf:
for line in inf:
line_info = re.match('([0-9].*?)\ (.*)', line)
line_no = int(line_info.group(1)) # line number
line_data = line_info.group(2) # rest of line
question_no = len(all_questions)
parts = line_data.split('?')
# parse the first part, either statement or question
statement = parts[0].strip().replace('.', '').split(' ')
words = [START_TOKEN] + [w.lower() for w in statement] + [END_TOKEN]
if line_no == 1:
current_story = []
current_line_nos = []
if len(parts) > 1: # is a question
all_stories[question_no][
MAX_LINE_NUM - len(current_story) : MAX_LINE_NUM] = current_story
all_line_nos[question_no][
MAX_LINE_NUM - len(current_line_nos) : MAX_LINE_NUM] = current_line_nos
MAX_QUESTION = max(MAX_QUESTION, len(words))
all_questions.append([word_to_idx[w] for w in words]) # append to question list
answer, facts = process_answer(parts[1], task_no, word_to_idx)
all_answers.append(answer)
MAX_FACT = max(MAX_FACT, len(facts))
all_facts.append(facts)
else: # is not a question
current_story.append([word_to_idx[words[i]] if i < len(words) else pad_idx
for i in range(MAX_LINE_LEN + 2)])
current_line_nos.append(line_no)
return {
'stories': all_stories, 'questions': all_questions,
'answers': all_answers, 'facts': all_facts,
'linenos': all_line_nos }
def process_files(folder, word_to_idx):
'''
Process all QA files in specified folder.
'''
trains = {}
tests = {}
tasks = ['' for t in range(NUM_TASKS)] # task names
owd = os.getcwd()
os.chdir(folder)
task_to_max = {} # keep track of max sent length, sentence count etc... for each task
for infile in glob.glob("*.txt"):
file_info = re.match('qa(.*)_(.*)_(.*).txt', infile)
task_no = int(file_info.group(1)) # from 1 to 20
process_task_max(infile, task_no, task_to_max, word_to_idx)
for infile in glob.glob("*.txt"):
file_info = re.match('qa(.*)_(.*)_(.*).txt', infile)
task_no = int(file_info.group(1)) # from 1 to 20
task_name = file_info.group(2) # e.g. yes-no-questions, basic-induction
task_data_type = file_info.group(3) # train or test
# process data
processed_data = process(infile, task_no, task_to_max, word_to_idx)
if task_data_type == 'train':
trains[task_no] = processed_data
else:
tests[task_no] = processed_data
# add the task name
tasks[task_no - 1] = task_name
os.chdir(owd)
return trains, tests, tasks
def main(arguments):
global args
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-vocabsize', help="vocabsize",
type=long,default=500000,required=False)
parser.add_argument('-dir', help="data directory",
type=str,default='babi_data/en/',required=False)
args = parser.parse_args(arguments)
word_to_idx = get_vocab(args.dir)
write_dict('word_to_idx.csv', word_to_idx) # for debugging purposes
trains, tests, tasks = process_files(args.dir, word_to_idx)
normalize(trains, word_to_idx)
normalize(tests, word_to_idx)
for t in np.arange(NUM_TASKS) + 1:
filename = 'qa{0:02d}.hdf5'.format(t)
with h5py.File(filename, "w") as f:
f['train_stories'] = trains[t]['stories']
f['train_linenos'] = trains[t]['linenos']
f['train_questions'] = trains[t]['questions']
f['train_answers'] = trains[t]['answers']
f['train_facts'] = trains[t]['facts']
f['test_stories'] = tests[t]['stories']
f['test_linenos'] = tests[t]['linenos']
f['test_questions'] = tests[t]['questions']
f['test_answers'] = tests[t]['answers']
f['test_facts'] = tests[t]['facts']
f['nwords'] = np.array([len(word_to_idx)], dtype=np.int32)
f['idx_pad'] = np.array([word_to_idx[PAD_TOKEN]], dtype=np.int32)
f['idx_rare'] = np.array([word_to_idx[RARE_TOKEN]], dtype=np.int32)
f['idx_start'] = np.array([word_to_idx[START_TOKEN]], dtype=np.int32)
f['idx_end'] = np.array([word_to_idx[END_TOKEN]], dtype=np.int32)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))