-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
347 lines (239 loc) · 8.67 KB
/
train.py
File metadata and controls
347 lines (239 loc) · 8.67 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import json
import re
import numpy
import torch.nn as nn
import torch.nn.functional as F
import torch
from copy import copy
from torch.autograd import Variable
from torch.nn import functional as F
import sys
w2v = {}
labels = None
premises = None
hypotheses = None
batch_size = 64
original_representation_lengths = []
longest_representation = 0
class Unidirectional(nn.Module):
def __init__(self):
super(Unidirectional, self).__init__()
self.lstm_premise = nn.LSTM(300, 2048, 1)
self.lstm_hypothesis = nn.LSTM(300, 2048, 1)
def forward(self, x1, x2):
x1 = self.lstm_premise(x1)
x2 = self.lstm_hypothesis(x2)
x = torch.mul((x1, x2))
x = nn.Linear(300, 512)
x = nn.Linear(512, 3)
x = nn.Softmax()
return x
class Bidirectional(nn.Module):
def __init__(self):
super(Bidirectional, self).__init__()
self.lstm_premise = nn.LSTM(300, 2048, 1)
self.lstm_hypothesis = nn.LSTM(300, 2048, 1)
def forward(self, x1, x2):
x1 = self.lstm_premise(x1)
x1 = self.lstm_premise(x1[::-1])
x2 = self.lstm_hypothesis(x2)
x2 = self.lstm_premise(x2[::-1])
x = torch.cat((x1, x2))
x = nn.Linear(300 * 2, 512)
x = nn.Linear(512, 3)
x = nn.Softmax()
return x
class BidirectionalMaxPool(nn.Module):
def __init__(self):
super(BidirectionalMaxPool, self).__init__()
self.lstm_premise = nn.LSTM(300, 2048, 1)
self.lstm_hypothesis = nn.LSTM(300, 2048, 1)
self.pool_factor = 3
def forward(self, x1, x2):
x1 = self.lstm_premise(x1)
x1 = self.lstm_premise(x1[::-1])
x2 = self.lstm_hypothesis(x2)
x2 = self.lstm_premise(x2[::-1])
x = torch.cat((x1, x2))
x = nn.MaxPool1d(self.pool_factor),
x = nn.Linear(300 * 2 / self.pool_factor, 512)
x = nn.Linear(512, 3)
x = nn.Softmax()
return x
#### Support functions ####
def load_data(path, cutoff=False, to_json=False):
ticker = 0
data = []
with open(path) as f:
for line in f:
if to_json:
line = json.loads(line)
data.append(line)
ticker += 1
if cutoff and ticker >= cutoff:
f.close()
break
return data
def process_glove_embeddings(num_words=1000):
glove_path = "./glove.840B.300d.txt"
words = {}
data = load_data(glove_path, num_words)
for d in data:
word_index = d.find(" ")
word = d[:word_index]
embedding = d[word_index + 1:].split(" ")
words[word] = embedding
return words
def sentence_to_list(sentence):
return re.findall(r"[A-Za-z@#]+|\S", sentence)
def load_snli_corpus(path, num_examples=1000, to_numbers=False):
global w2v
ticker = 0
snli_corpus = load_data(path, num_examples, True)
labels = [e['annotator_labels'][0] for e in snli_corpus]
premises = [sentence_to_list(e['sentence1']) for e in snli_corpus]
hypotheses = [sentence_to_list(e['sentence2']) for e in snli_corpus]
for l in range(len(labels)):
if labels[l] == "-":
del labels[l]
del premises[l]
del hypotheses[l]
l -= 1
elif labels[l] == "entailment":
labels[l] = [1, 0, 0]
elif labels[l] == "neutral":
labels[l] = [0, 1, 0]
elif labels[l] == "contradiction":
labels[l] = [0, 0, 1]
for word in premises[l]:
if word not in w2v:
w2v[word] = ticker
ticker += 1
for word in hypotheses[l]:
if word not in w2v:
w2v[word] = ticker
ticker += 1
return labels, premises, hypotheses
def extract_relations_multiply(a, b):
return a*b
def extract_relations_diff(a, b):
return abs(a-b)
def extract_relations_concat(a, b):
return a+b
#### end Support functions ####
#### Representations ####
def get_baseline_representation(path, num_examples=10000):
glove_path = "./glove.840B.300d.txt"
labels, premises, hypotheses = load_snli_corpus(path, num_examples)
glove_embeddings = {}
premises_embeddings = []
hypotheses_embeddings = []
premise_embedding = None
hypotheses_embedding = None
readlines = 0
with open(glove_path) as f:
for i in range(len(labels)):
premise_embedding = []
hypotheses_embedding = []
for word in premises[i]:
while word not in glove_embeddings:
glove_embedding = f.readline()
readlines += 1
word_index = glove_embedding.find(" ")
word = glove_embedding[:word_index]
embedding = list(
map(float, glove_embedding[word_index + 1:].split(" ")))
glove_embeddings[word] = embedding
premise_embedding.append(glove_embeddings[word])
premise_embedding = [sum(x)/len(premise_embedding)
for x in zip(*premise_embedding)]
premises_embeddings.append(premise_embedding)
for word in hypotheses[i]:
while word not in glove_embeddings:
glove_embedding = f.readline()
readlines += 1
word_index = glove_embedding.find(" ")
word = glove_embedding[:word_index]
embedding = list(
map(float, glove_embedding[word_index + 1:].split(" ")))
glove_embeddings[word] = embedding
hypotheses_embedding.append(glove_embeddings[word])
hypotheses_embedding = [sum(x)/len(hypotheses_embedding)
for x in zip(*hypotheses_embedding)]
hypotheses_embeddings.append(hypotheses_embedding)
f.close()
premises_hypotheses_relations = extract_relations(
premises_embeddings, hypotheses_embeddings)
return (labels, premises_hypotheses_relations)
def get_lstm_representation(path, num_examples=10000):
global w2v
global longest_representation
global original_representation_lengths
pad_token = 0
labels, premises, hypotheses = load_snli_corpus(path, num_examples)
longest_representation = max(
len(max(premises, key=len)), len(max(hypotheses, key=len)))
for i in range(len(premises)):
len_p = len(premises[i])
encoded_p = [pad_token] * longest_representation
encoded_p[:len_p] = [w2v[premises[i][j]]
for j in range(len_p)]
premises[i] = encoded_p
len_h = len(hypotheses[i])
encoded_h = [pad_token] * longest_representation
encoded_h[:len_h] = [w2v[hypotheses[i][k]]
for k in range(len_h)]
hypotheses[i] = encoded_h
original_representation_lengths.append((len_p, len_h))
return (labels, premises, hypotheses)
#### end Representations ####
def get_corpus_representation(encoder, path, num_examples=10000):
if encoder == "baseline":
return get_baseline_representation(path, num_examples)
else:
return get_lstm_representation(path, num_examples)
def extract_relations(premises, hypotheses, method="multiply"):
relations = []
for i in range(len(premises)):
result = None
if method == "multiply":
result = [extract_relations_multiply(
a, b) for a, b in zip(premises[i], hypotheses[i])]
elif method == "diff":
result = [extract_relations_diff(
a, b) for a, b in zip(premises[i], hypotheses[i])]
else:
result = [extract_relations_concat(
a, b) for a, b in zip(premises[i], hypotheses[i])]
relations.append(result)
return relations
def get_model(encoder):
n_in, n_h, n_out = 300, 512, 3
if encoder == "baseline":
return nn.Sequential(
nn.Linear(n_in, n_h),
nn.Linear(n_h, n_out),
nn.Softmax()
)
elif encoder == "unidirectional":
return Unidirectional()
elif encoder == "bidirectional":
return Bidirectional()
elif encoder == "bidirectionalmaxpool":
return BidirectionalMaxPool()
def main():
arguments = sys.argv[1:]
encoder = None
path = None
if len(arguments) > 0:
encoder = arguments[0]
else:
encoder = "baseline"
if len(arguments) > 1:
path = arguments[1]
else:
path = "./snli_1.0/snli_1.0_train.jsonl"
data = get_corpus_representation(encoder, path)
model = get_model(encoder)
if __name__ == "__main__":
main()