This repository has been archived by the owner on Jan 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
262 lines (204 loc) · 7.21 KB
/
main.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
def preprocessSick():
from Helpers.preprocess import SICK
SICK.get_final_input()
return
def train_dtrnn():
from Model_Trainer.dtrnnTrain import DT_RNN_Train
model = DT_RNN_Train(n=8000, epochs=10, hid_dim=50)
model.train_dtRNN()
def train_dtrnn_debug():
from Model_Trainer.dtrnnTrain import DT_RNN_Train
model = DT_RNN_Train("load", n=3, epochs=5, hid_dim=50)
x = model.toposort()
index = 189
print(x[index])
print(1000 * "-")
print(x[index].inputs)
print(1000 * "-")
print([inp.owner for inp in x[index].inputs])
print(1000 * "-")
print(x[index].outputs)
print(1000 * "-")
print([out.owner for out in x[index].outputs])
def train_dtrnn_graph():
from Model_Trainer.dtrnnTrain import DT_RNN_Train
import theano
model = DT_RNN_Train(n=8000, epochs=5, hid_dim=50)
print(theano.printing.debugprint(model.grad))
return
def preprocess_babi_ans_extract():
from Helpers import create_dataset
sources = ['qa1_single-supporting-fact_train',
'qa4_two-arg-relations_test', 'qa5_three-arg-relations_test',
'qa12_conjunction_test']
for source in sources:
create_dataset(source)
return
def get_babi_tree():
from Helpers import preprocess
preprocess.AnswerExtract.get_final_input_babi()
return
def create_config(state_file_name, config_file_name):
from Helpers.deployment_utils import create_config
import os
state_file_name = os.path.basename(state_file_name)
create_config(state_file_name, config_file_name)
return
def install_packages():
from subprocess import call
with open('requirements.txt','r') as f:
requirements = [line.strip() for line in f.readlines()]
for requirement in requirements:
return_code = call("pip install {} > /dev/null".format(requirement), shell=True)
if return_code:
if 'tensorflow-gpu' in requirement:
print("There was an error installing tensorflow-gpu!")
print("It is assumed that it was a MemoryError!")
print("The developers need to think of a better way to \
detect MemoryError")
print("Trying to solve MemoryError")
call("pip install --no-cache-dir " + requirement,
shell=True)
if 'Lasagne' in requirement:
print("Lasagne 0.2.dev1 could not be found on PyPI")
print("Installing from the GitHub repository...")
lasagne_req_link = "https://raw.githubusercontent.com/"\
"Lasagne/Lasagne/master/requirements.txt"
lasagne_link = \
"https://github.com/Lasagne/Lasagne/archive/master.zip"
call(
"pip install -r {0};pip install {1}".format(
lasagne_req_link,
lasagne_link
),
shell=True
)
else:
print("Installed: {}".format(requirement))
call("python -m spacy download en", shell=True)
print("The following packages could not be installed:")
call("pip freeze | diff requirements.txt - | grep '^<' | sed 's/^<\ //'", shell=True)
return
def create_ans_ext_input():
from Helpers.preprocess import AnswerExtract
AnswerExtract.get_ans_model_input_babi()
return
def train_ans_extract(inp_dim=50, hid_dim=200, epochs=10):
from Model_Trainer import train_extraction_module
train_extraction_module(
inp_dim=int(inp_dim),
hid_dim=int(hid_dim),
epochs=int(epochs),
)
return
def get_output():
print('System: Initializing...')
from Models import abcnn_model
from Helpers.deployment_utils import extract_answer_from_sentences
sents = [
'john went to the bathroom',
'mary went to the kitchen',
'john moved to the hallway',
'kim journeyed to the garden',
'sandra is in the bedroom',
]
print('\nSystem: The context is:')
for sentence in sents:
print(sentence)
query = 'where is john'
print('System: The question is:')
print(query)
# Select Ans Sents - ABCNN
print('\nSentence Selection Module: Initializing...')
abcnn = abcnn_model()
ans_sents = abcnn.ans_select(query, sents)
print('\nSystem: Sentences scored by Sentence Selection Module')
for sentence,score in ans_sents:
print('{0:50}\t{1}'.format(sentence, score[0]))
print('')
best_ans, score, answers = extract_answer_from_sentences(
ans_sents,
query,
verbose=True,
)
ans_list = []
for x in answers:
ans_list.append({'word':x[0], 'score': x[1]})
print('\nSystem: Candidate answers scored by Answer Extraction Module')
for answer in ans_list:
print('{0:10}\t{1}'.format(answer['word'], answer['score']))
def get_answer():
print('System: Initializing...')
import spacy
from Helpers import deployment_utils as deploy
sentence = 'john went to the bathroom'
question = 'where is john'
config = deploy.get_config('dtrnn.cfg')
print('System: Loading SpaCy...')
nlp = spacy.load('en')
print('System: SpaCy Loaded')
print('System: Sentence- ', sentence)
print('System: Question-', question)
scores = deploy._extract_answer_from_sentence(
sentence,
question,
nlp,
config,
verbose=True,
)
print(scores)
question = 'who is in the bathroom'
print('System: Sentence-', sentence)
print('System: Question-', question)
scores = deploy._extract_answer_from_sentence(
sentence,
question,
nlp,
config,
verbose=True,
)
print(scores)
return
def paper(task_num=1, history=None):
task_num = int(task_num)
assert task_num in [1, 4, 5, 12]
from paper import erudite
if not history:
erudite.EruditeX().get_babi_task_num(task_num)
else:
assert '/' in history
count, total = map(int, history.strip().split('/'))
erudite.EruditeX().get_babi_task_num(task_num, count, total)
def example(task, example):
from edx_server import EdXServer as EruditeX
from paper import babi
babi_list = babi.get_babi(task)
example = int(example) - 1
babi_dict = babi_list[example]
system = EruditeX()
print('Context:', babi_dict['context'])
print('Question:', babi_dict['question'])
system.context = babi_dict['context']
temp = system.get_query(babi_dict['question'])
print(temp)
return
def analyse(task, search='Predicted Answer'):
from paper import analysis
from paper import babi
if search == 'Predicted Answer':
vocab = babi.get_vocab(task)
else:
vocab = {}
if task == 'all':
for task in ['1', '4', '5', '12']:
analysis.task(task, vocab, search.title())
else:
assert task in ['1', '4', '5', '12']
analysis.task(task, vocab, search.title())
for key in vocab:
print(key)
for key in vocab:
print(vocab[key])
return
if __name__ == '__main__':
train_dtrnn()