-
Notifications
You must be signed in to change notification settings - Fork 4
/
ensembleModel.py
835 lines (696 loc) · 24.2 KB
/
ensembleModel.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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 09:10:48 2018
@author: Deep
"""
import dataProcess
import testReader
from gensim.models import KeyedVectors
import os
import numpy as np
from keras.models import Sequential
from keras.layers.embeddings import Embedding
from keras.layers.wrappers import Bidirectional
from keras.layers import Dense, Merge, Dropout, Flatten
from keras.layers.recurrent import LSTM
TRAIN_QA_DIR = "C:/Users/Deep/Desktop/SemEval t11/data/train_qa.txt"
TRAIN_INS_DIR = "C:/Users/Deep/Desktop/SemEval t11/data/train_ins.txt"
DEV_QA_DIR = "C:/Users/Deep/Desktop/SemEval t11/data/dev_qa.txt"
DEV_INS_DIR = "C:/Users/Deep/Desktop/SemEval t11/data/dev_ins.txt"
TEST_QA_DIR = "C:/Users/Deep/Desktop/gold_data/test_data_qa.txt"
TEST_INS_DIR = "C:/Users/Deep/Desktop/gold_data/test_data_ins.txt"
WORDVEC_DIR = "C:/Users/Deep/Desktop/SemEval t11/w2v"
#WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin"
WORD2VEC_BIN = "glove.840B.300d.txt"
WORD2VEC_EMBED_SIZE = 300
QA_EMBED_SIZE = 64
BATCH_SIZE = 512
EPOCHS = 6
seed = 7
np.random.seed(seed)
# 加载数据
print("Loading and formatting data...")
sqac_pairs_tokenizes = dataProcess.get_sqac_pairs_tokenizes(TRAIN_QA_DIR, TRAIN_INS_DIR)
dev_sqac_pairs_tokenizes = dataProcess.get_sqac_pairs_tokenizes(DEV_QA_DIR, DEV_INS_DIR)
test_sqac_pairs_tokenizes = testReader.get_sqac_pairs_tokenizes(TEST_QA_DIR, TEST_INS_DIR)
all_pairs_tokenizes = sqac_pairs_tokenizes + dev_sqac_pairs_tokenizes + test_sqac_pairs_tokenizes
story_maxlen = max([len(sqatriple[0]) for sqatriple in all_pairs_tokenizes])
question_maxlen = max([len(sqatriple[1]) for sqatriple in all_pairs_tokenizes])
answer_maxlen = max([len(sqatriple[2]) for sqatriple in all_pairs_tokenizes])
word2idx = dataProcess.build_vocab_from_sqac_pairs_tokenizes(all_pairs_tokenizes)
vocab_size = len(word2idx) + 1 # include mask character 0
# 训练集
Xs, Xq, Xa, Y = dataProcess.vectorize_sqac_pairs_tokenizes(sqac_pairs_tokenizes, word2idx, story_maxlen, question_maxlen, answer_maxlen)
# 开发集
Xs_dev, Xq_dev, Xa_dev, Y_dev = dataProcess.vectorize_sqac_pairs_tokenizes(dev_sqac_pairs_tokenizes, word2idx, story_maxlen, question_maxlen, answer_maxlen)
# 测试集
Xs_test, Xq_test, Xa_test, Y_test = testReader.vectorize_sqac_pairs_tokenizes(test_sqac_pairs_tokenizes, word2idx, story_maxlen, question_maxlen, answer_maxlen)
# 将训练集和开发集合并成为新的训练集,19674 + 2834 = 22508
#Xs_all = np.vstack((Xs, Xs_dev))
#Xq_all = np.vstack((Xq, Xq_dev))
#Xa_all = np.vstack((Xa, Xa_dev))
#Y_all = np.vstack((Y, Y_dev))
# get embeddings from word2vec
print("Loading Word2Vec model and generating embedding matrix...")
#word2vec = KeyedVectors.load_word2vec_format(os.path.join(WORDVEC_DIR, WORD2VEC_BIN), binary=True)
word2vec = KeyedVectors.load_word2vec_format(os.path.join(WORDVEC_DIR, WORD2VEC_BIN), binary=False, unicode_errors='ignore')
embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE))
num_unknownwords = 0
unknow_words = []
for word, index in word2idx.items():
try:
embedding_weights[index, :] = word2vec[word]
except KeyError:
num_unknownwords += 1
unknow_words.append(word)
embedding_weights[index, :] = np.random.uniform(-0.25, 0.25, WORD2VEC_EMBED_SIZE)
# print(word2vec.wv.vocab.__len__())
##########################################################################################################
print("Building model 1...")
# story encoder.
# output shape: (None, story_maxlen, QA_EMBED_SIZE)
senc = Sequential()
senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=story_maxlen,
weights=[embedding_weights], mask_zero=True))
#senc.add(LSTM(QA_EMBED_SIZE, return_sequences=True))
senc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
senc.add(Dropout(0.3))
# question encoder
# output shape: (None, question_maxlen, QA_EMBED_SIZE)
qenc = Sequential()
qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=question_maxlen,
weights=[embedding_weights], mask_zero=True))
#qenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True))
qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
qenc.add(Dropout(0.3))
# answer encoder
# output shape: (None, answer_maxlen, QA_EMBED_SIZE)
aenc = Sequential()
aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=answer_maxlen,
weights=[embedding_weights], mask_zero=True))
#aenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True))
aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
aenc.add(Dropout(0.3))
# merge story and question => facts
# output shape: (None, story_maxlen, question_maxlen)
facts = Sequential()
facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2]))
# merge question and answer => attention
# output shape: (None, answer_maxlen, question_maxlen)
attn = Sequential()
attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2]))
# merge facts and attention => model
# output shape: (None, story+answer_maxlen, question_maxlen)
model = Sequential()
model.add(Merge([facts, attn], mode="concat", concat_axis=1))
model.add(Flatten())
model.add(Dense(2, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
print("Training...")
model.fit([Xs, Xq, Xa], Y, batch_size=BATCH_SIZE, epochs=EPOCHS)
predict_Y = model.predict([Xs_dev, Xq_dev, Xa_dev])
# 第0个答案偏向正确的概率
a_0 = (predict_Y[::2])[:,0]
# 第1个答案偏向正确的概率
a_1 = (predict_Y[1::2])[:,0]
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(a_0, a_1):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
dev_qa = list(open(DEV_QA_DIR, 'r'))
for line in dev_qa:
line = line.strip()
line = line.split("\t")
del line[0:5]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
# 在测试集上的预测
predict_test_1 = model.predict([Xs_test, Xq_test, Xa_test])
# 第0个答案偏向正确的概率
test_a_0_1 = (predict_test_1[::2])[:,0]
# 第1个答案偏向正确的概率
test_a_1_1 = (predict_test_1[1::2])[:,0]
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(test_a_0_1, test_a_1_1):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
test_qa = list(open(TEST_QA_DIR, 'r'))
for line in test_qa:
line = line.strip()
line = line.split("\t")
del line[0:6]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
##########################################################################################################
print("Building model 2...")
# story encoder.
# output shape: (None, story_maxlen, QA_EMBED_SIZE)
senc = Sequential()
senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=story_maxlen,
weights=[embedding_weights], mask_zero=True))
senc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
senc.add(Dropout(0.5))
# question encoder
# output shape: (None, question_maxlen, QA_EMBED_SIZE)
qenc = Sequential()
qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=question_maxlen,
weights=[embedding_weights], mask_zero=True))
qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
qenc.add(Dropout(0.5))
# answer encoder
# output shape: (None, answer_maxlen, QA_EMBED_SIZE)
aenc = Sequential()
aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=answer_maxlen,
weights=[embedding_weights], mask_zero=True))
aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
aenc.add(Dropout(0.5))
# merge story and question => facts
# output shape: (None, story_maxlen, question_maxlen)
facts = Sequential()
facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2]))
# merge question and answer => attention
# output shape: (None, answer_maxlen, question_maxlen)
attn = Sequential()
attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2]))
# merge facts and attention => model
# output shape: (None, story+answer_maxlen, question_maxlen)
model = Sequential()
model.add(Merge([facts, attn], mode="concat", concat_axis=1))
model.add(Flatten())
model.add(Dense(2, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
print("Training...")
model.fit([Xs, Xq, Xa], Y, batch_size=BATCH_SIZE, epochs=EPOCHS)
predict_Y_1 = model.predict([Xs_dev, Xq_dev, Xa_dev])
a_0_1 = (predict_Y_1[::2])[:,0]
a_1_1 = (predict_Y_1[1::2])[:,0]
a_0_a = a_0 + a_0_1
a_1_a = a_1 + a_1_1
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
#for a in zip(a_0_1, a_1_1):
for a in zip(a_0_a, a_1_a):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
dev_qa = list(open(DEV_QA_DIR, 'r'))
for line in dev_qa:
line = line.strip()
line = line.split("\t")
del line[0:5]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
# 在测试集上的预测
predict_test_2 = model.predict([Xs_test, Xq_test, Xa_test])
# 第0个答案偏向正确的概率
test_a_0_2 = (predict_test_2[::2])[:,0]
# 第1个答案偏向正确的概率
test_a_1_2 = (predict_test_2[1::2])[:,0]
t1_1 = test_a_0_1 + test_a_0_2
t1_2 = test_a_1_1 + test_a_1_2
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(t1_1, t1_2):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
test_qa = list(open(TEST_QA_DIR, 'r'))
for line in test_qa:
line = line.strip()
line = line.split("\t")
del line[0:6]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
##########################################################################################################
print("Building model 3...")
# story encoder.
# output shape: (None, story_maxlen, QA_EMBED_SIZE)
senc = Sequential()
senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=story_maxlen,
weights=[embedding_weights], mask_zero=True))
senc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
senc.add(Dropout(0.4))
# question encoder
# output shape: (None, question_maxlen, QA_EMBED_SIZE)
qenc = Sequential()
qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=question_maxlen,
weights=[embedding_weights], mask_zero=True))
qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
qenc.add(Dropout(0.4))
# answer encoder
# output shape: (None, answer_maxlen, QA_EMBED_SIZE)
aenc = Sequential()
aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=answer_maxlen,
weights=[embedding_weights], mask_zero=True))
aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
aenc.add(Dropout(0.4))
# merge story and question => facts
# output shape: (None, story_maxlen, question_maxlen)
facts = Sequential()
facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2]))
# merge question and answer => attention
# output shape: (None, answer_maxlen, question_maxlen)
attn = Sequential()
attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2]))
# merge facts and attention => model
# output shape: (None, story+answer_maxlen, question_maxlen)
model = Sequential()
model.add(Merge([facts, attn], mode="concat", concat_axis=1))
model.add(Flatten())
model.add(Dense(2, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
print("Training...")
model.fit([Xs, Xq, Xa], Y, batch_size=BATCH_SIZE, epochs=6)
predict_Y_2 = model.predict([Xs_dev, Xq_dev, Xa_dev])
a_0_2 = (predict_Y_2[::2])[:,0]
a_1_2 = (predict_Y_2[1::2])[:,0]
a_0_b = a_0 + a_0_1 + a_0_2
a_1_b = a_1 + a_1_1 + a_1_2
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
#for a in zip(a_0_2, a_1_2):
for a in zip(a_0_b, a_1_b):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
dev_qa = list(open(DEV_QA_DIR, 'r'))
for line in dev_qa:
line = line.strip()
line = line.split("\t")
del line[0:5]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
# 在测试集上的预测
predict_test_3 = model.predict([Xs_test, Xq_test, Xa_test])
# 第0个答案偏向正确的概率
test_a_0_3 = (predict_test_3[::2])[:,0]
# 第1个答案偏向正确的概率
test_a_1_3 = (predict_test_3[1::2])[:,0]
t2_1 = test_a_0_1 + test_a_0_2 + test_a_0_3
t2_2 = test_a_1_1 + test_a_1_2 + test_a_1_3
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(t2_1, t2_2):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
test_qa = list(open(TEST_QA_DIR, 'r'))
for line in test_qa:
line = line.strip()
line = line.split("\t")
del line[0:6]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
##########################################################################################################
print("Building model 4...")
# story encoder.
# output shape: (None, story_maxlen, QA_EMBED_SIZE)
senc = Sequential()
senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=story_maxlen,
weights=[embedding_weights], mask_zero=True))
senc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
senc.add(Dropout(0.2))
# question encoder
# output shape: (None, question_maxlen, QA_EMBED_SIZE)
qenc = Sequential()
qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=question_maxlen,
weights=[embedding_weights], mask_zero=True))
qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
qenc.add(Dropout(0.2))
# answer encoder
# output shape: (None, answer_maxlen, QA_EMBED_SIZE)
aenc = Sequential()
aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=answer_maxlen,
weights=[embedding_weights], mask_zero=True))
aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
aenc.add(Dropout(0.2))
# merge story and question => facts
# output shape: (None, story_maxlen, question_maxlen)
facts = Sequential()
facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2]))
# merge question and answer => attention
# output shape: (None, answer_maxlen, question_maxlen)
attn = Sequential()
attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2]))
# merge facts and attention => model
# output shape: (None, story+answer_maxlen, question_maxlen)
model = Sequential()
model.add(Merge([facts, attn], mode="concat", concat_axis=1))
model.add(Flatten())
model.add(Dense(2, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
print("Training...")
model.fit([Xs, Xq, Xa], Y, batch_size=BATCH_SIZE, epochs=6)
predict_Y_3 = model.predict([Xs_dev, Xq_dev, Xa_dev])
a_0_3 = (predict_Y_3[::2])[:,0]
a_1_3 = (predict_Y_3[1::2])[:,0]
a_0_c = a_0 + a_0_1 + a_0_2 + a_0_3
a_1_c = a_1 + a_1_1 + a_1_2 + a_1_3
np.save("C:/Users/Deep/Desktop/a_0_c.npy", a_0_c)
np.save("C:/Users/Deep/Desktop/a_1_c.npy", a_1_c)
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(a_0_c, a_1_c):
#for a in zip(a_0_3, a_1_3):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
dev_qa = list(open(DEV_QA_DIR, 'r'))
for line in dev_qa:
line = line.strip()
line = line.split("\t")
del line[0:5]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
# 在测试集上的预测
predict_test_4 = model.predict([Xs_test, Xq_test, Xa_test])
# 第0个答案偏向正确的概率
test_a_0_4 = (predict_test_4[::2])[:,0]
# 第1个答案偏向正确的概率
test_a_1_4 = (predict_test_4[1::2])[:,0]
test_a_0_ens1234 = test_a_0_1 + test_a_0_2 + test_a_0_3 + test_a_0_4
test_a_1_ens1234 = test_a_1_1 + test_a_1_2 + test_a_1_3 + test_a_1_4
t3_1 = test_a_0_1 + test_a_0_2 + test_a_0_3 + test_a_0_4
t3_2 = test_a_1_1 + test_a_1_2 + test_a_1_3 + test_a_1_4
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(t3_1, t3_2):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
test_qa = list(open(TEST_QA_DIR, 'r'))
for line in test_qa:
line = line.strip()
line = line.split("\t")
del line[0:6]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
##########################################################################################################
print("Building model 5...")
# story encoder.
# output shape: (None, story_maxlen, QA_EMBED_SIZE)
senc = Sequential()
senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=story_maxlen,
weights=[embedding_weights], mask_zero=True))
senc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
senc.add(Dropout(0.6))
# question encoder
# output shape: (None, question_maxlen, QA_EMBED_SIZE)
qenc = Sequential()
qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=question_maxlen,
weights=[embedding_weights], mask_zero=True))
qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
qenc.add(Dropout(0.6))
# answer encoder
# output shape: (None, answer_maxlen, QA_EMBED_SIZE)
aenc = Sequential()
aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size,
input_length=answer_maxlen,
weights=[embedding_weights], mask_zero=True))
aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True),
merge_mode="sum"))
aenc.add(Dropout(0.6))
# merge story and question => facts
# output shape: (None, story_maxlen, question_maxlen)
facts = Sequential()
facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2]))
# merge question and answer => attention
# output shape: (None, answer_maxlen, question_maxlen)
attn = Sequential()
attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2]))
# merge facts and attention => model
# output shape: (None, story+answer_maxlen, question_maxlen)
model = Sequential()
model.add(Merge([facts, attn], mode="concat", concat_axis=1))
model.add(Flatten())
model.add(Dense(2, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
print("Training...")
model.fit([Xs, Xq, Xa], Y, batch_size=BATCH_SIZE, epochs=6)
predict_Y_4 = model.predict([Xs_dev, Xq_dev, Xa_dev])
a_0_4 = (predict_Y_4[::2])[:,0]
a_1_4 = (predict_Y_4[1::2])[:,0]
a_0_d = a_0 + a_0_1 + a_0_2 + a_0_3 + a_0_4
a_1_d = a_1 + a_1_1 + a_1_2 + a_1_3 + a_1_4
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(a_0_d, a_1_d):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
dev_qa = list(open(DEV_QA_DIR, 'r'))
for line in dev_qa:
line = line.strip()
line = line.split("\t")
del line[0:5]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
# 在测试集上的预测
predict_test_5 = model.predict([Xs_test, Xq_test, Xa_test])
# 第0个答案偏向正确的概率
test_a_0_5 = (predict_test_5[::2])[:,0]
# 第1个答案偏向正确的概率
test_a_1_5 = (predict_test_5[1::2])[:,0]
# ensemble with model1、model2、model3、 model4
test_a_0_ens12345 = test_a_0_1 + test_a_0_2 + test_a_0_3 + test_a_0_4 + test_a_0_5
test_a_1_ens12345 = test_a_1_1 + test_a_1_2 + test_a_1_3 + test_a_1_4 + test_a_1_5
# 自己动手计算准确率
# asw是提交文件的第三列
asw = []
for a in zip(t3_1, t3_2):
#print (i)
if a[0] > a[1]:
asw.append(0)
else:
asw.append(1)
aidx = []
test_qa = list(open(TEST_QA_DIR, 'r'))
for line in test_qa:
line = line.strip()
line = line.split("\t")
del line[0:6]
aidx.append(line)
selfEva = []
for t in zip(aidx, asw):
#print (t)
if int(t[0][0]) == t[1]:
selfEva.append(1)
else:
selfEva.append(0)
num_correct = 0
for i in selfEva:
if i == 1:
num_correct += 1
self_accuracy = num_correct/len(selfEva)
print (self_accuracy)
## asw是提交文件的第三列
#test_asw_ens12345 = []
#for a in zip(test_a_0_ens12345, test_a_1_ens12345):
# #print (i)
# if a[0] > a[1]:
# test_asw_ens12345.append(0)
# else:
# test_asw_ens12345.append(1)
#
#sidx_qidx_ens12345 = []
#test_qa = list(open(TEST_QA_DIR, 'r'))
#for line in test_qa:
# line = line.strip()
# line = line.split("\t")
# del line[2:]
# sidx_qidx_ens12345.append(line)
#
#file5 = open('C:/Users/Deep/Desktop/SemEval t11/results/answer_ens12345.txt','w',encoding='utf-8')
#
## 注意删除answer.txt文件最后一行的空行
#for i in zip(sidx_qidx_ens12345, test_asw_ens12345):
# #print (i)
# file5.write(i[0][0])
# file5.write(',')
# file5.write(i[0][1])
# file5.write(',')
# file5.write(str(i[1]))
# file5.write('\n')
#
#file5.close()