-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
1441 lines (1299 loc) · 39.4 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
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
Copyright 2018, 2019, 2020 Rui Antunes, Sérgio Matos
https://github.com/ruiantunes/biocreative-vi-track-5-chemprot
BioCreative VI - Track 5 (CHEMPROT). Multiclass classification problem.
This script follows a supervised learning strategy using deep learning
algorithms in the BioCreative VI - Track 5 (CHEMPROT task). Its goal is
to extract Chemical-Protein (CHEMPROT) Relations (CPRs) from PubMed
abstracts (title and abstracts in English) from scientific papers
published between 2005 and 2014 (see CHEMPROT guidelines PDF:
"Annotation manual of CHEMPROT interactions between CEM and GPRO" [1]_).
References
----------
.. [1] http://www.biocreative.org/tasks/biocreative-vi/track-5/
.. [2] https://github.com/fchollet/keras/issues/2607
.. [3] https://github.com/fchollet/keras/blob/53e541f7bf55de036f4f5641bd2947b96dd8c4c3/keras/metrics.py
.. [4] https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html
.. [5] https://www.kaggle.com/lystdo/lb-0-18-lstm-with-glove-and-magic-features
.. [6] https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development
.. [7] https://stackoverflow.com/questions/39263002/calling-fit-multiple-times-in-keras
.. [8] https://stackoverflow.com/questions/34673396/what-does-the-standard-keras-model-output-mean-what-is-epoch-and-loss-in-keras#37979686
.. [9] https://machinelearningmastery.com/grid-search-hyperparameters-deep-learning-models-python-keras/
"""
# read script file
with open('main.py') as f:
main = f.read()
# input arguments
# seed number
# parse command line arguments to obtain SEED integer value
import sys
import os
args = sys.argv[1:]
n = len(args)
if n >= 1:
SEED = int(args[0])
else:
SEED = 0
# DNN model to use (choose between 'lstm' or 'cnn')
MODEL = 'lstm'
#EXTERNAL_GROUPS = ['biogrid']
EXTERNAL_GROUPS = []
#TRAINING_GROUPS = ['training', 'development']
TRAINING_GROUPS = ['training']
#TEST_GROUPS = ['development', 'test_gs']
TEST_GROUPS = ['development']
# use Shortest Dependency Path (features)
SDP = True
# use Left/Right text chemical/gene (features)
LR = False
# use words as features
WRD = True
# use Part-of-Speech (features)
POS = False
# use dependency incoming edges (features)
DEP = False
if 1:
# word2vec size [100, 300]
W2V_SIZE = 100
# word2vec window [5, 20, 50]
W2V_WINDOW = 50
# gensim Word2Vec model file path
W2V_PUBMED_FPATH = os.path.join(
'word2vec',
'pubmed_full_umlsstop_word2vec_model_{}_{}'.format(
W2V_SIZE, W2V_WINDOW),
)
else:
W2V_SIZE = 200
W2V_WINDOW = 20
W2V_PUBMED_FPATH = os.path.join(
'word2vec',
'BioWordVec_PubMed_MIMICIII_d200.vec.bin',
)
# Pos2Vec word2vec model filepath (None to use random embeddings)
#P2V_FPATH = None
P2V_FPATH = os.path.join(
'word2vec',
'pos-size20-window3-iter100.kv',
)
# pos2vec size (only applicable when using random embeddings)
P2V_SIZE = 20
# Dep2Vec word2vec model filepath (None to use random embeddings)
#D2V_FPATH = None
D2V_FPATH = os.path.join(
'word2vec',
'dep-size20-window3-iter100.kv',
)
# dependency2vec size (only applicable when using random embeddings)
D2V_SIZE = 20
assert MODEL in ('lstm', 'cnn'), 'Invalid model!'
assert len(TRAINING_GROUPS) > 0
assert len(TEST_GROUPS) > 0
assert SDP or LR, 'SDP and LR are False!'
assert WRD or POS or DEP, 'WRD, POS, and DEP are False!'
# built-in modules (sys.builtin_module_names)
import time
# third-party modules
import datetime
from gensim.models import Word2Vec
#from keras import regularizers
#from keras import backend as K
#from keras.callbacks import EarlyStopping
#from keras.callbacks import ModelCheckpoint
#from keras.layers import Activation
#from keras.layers import AveragePooling1D
from keras.layers import Bidirectional
from keras.layers import concatenate
from keras.layers import Conv1D
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Embedding
#from keras.layers import Flatten
from keras.layers import GaussianNoise
from keras.layers import GlobalMaxPooling1D
from keras.layers import Input
from keras.layers import LSTM
#from keras.layers import MaxPooling1D
#from keras.layers.normalization import BatchNormalization
#from keras.models import load_model
from keras.models import Model
#from keras.preprocessing.text import text_to_word_sequence
#from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
#from keras.wrappers.scikit_learn import KerasClassifier
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import random as rn
#from scipy.linalg import norm
#from sklearn.metrics import make_scorer
#from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import normalize
from sklearn.utils.class_weight import compute_class_weight
import tensorflow as tf
# own modules
from mfuncs import load_keyedvectors
from mfuncs import load_word2vec
from mfuncs import normalized_rand
from mfuncs import normalized_sum
from mfuncs import tokenize
from mfuncs import tokseqs2intseqs
from mfuncs import to_uncategorical
from support import CPR_EVAL_GROUPS
from support import DATA
from support import INDEX2LABEL
from support import LABEL2INDEX
from support import chemprot_eval
from support import chemprot_eval_arrays
#from support import get_pmids
from support import load_data_from_zips
from utils import create_directory
from utils import Printer
# to remove tensorflow warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# to ensure determinism/reproducibility [6]
os.environ['PYTHONHASHSEED'] = '0'
np.random.seed(SEED)
rn.seed(SEED)
tf.set_random_seed(SEED)
# other constants
# the directory for saving the output files (logs, ...)
OUT = 'out'
create_directory(OUT)
# output files: logs, predictions, probabilities, best model, history
# PNG image, main python script (this script)
FN = '{}'.format(datetime.datetime.now().strftime('%Y-%m-%d-%H%M%S-%f'))
LOGS_FPATH = os.path.join(OUT, FN + '-logs.txt')
PREDICTIONS_FPATH = os.path.join(OUT, FN + '-predictions.tsv')
PROBABILITIES_FPATH = os.path.join(OUT, FN + '-probabilities.tsv')
BEST_MODEL_FPATH = os.path.join(OUT, FN + '-best-model.h5')
HISTORY_FPATH = os.path.join(OUT, FN + '-history.png')
MAIN_FPATH = os.path.join(OUT, FN + '-main.py')
with open(MAIN_FPATH, 'w') as f:
_ = f.write(main)
# external datasets
EXTERNAL_ZIPS = [
os.path.join(
DATA,
'chemprot_{}'.format(group),
'support',
'processed_corpus.zip',
) for group in EXTERNAL_GROUPS
]
# training datasets
TRAINING_ZIPS = [
os.path.join(
DATA,
'chemprot_{}'.format(group),
'support',
'processed_corpus.zip',
) for group in TRAINING_GROUPS
]
# test datasets
TEST_ZIPS = [
os.path.join(
DATA,
'chemprot_{}'.format(group),
'support',
'processed_corpus.zip',
) for group in TEST_GROUPS
]
# test gold standard relations
TEST_GS_FPATHS = [
os.path.join(
DATA,
'chemprot_{}'.format(group),
'chemprot_{}_gold_standard.tsv'.format(group),
)
for group in TEST_GROUPS
]
# number of unique classes
NUM_CLASSES = len(INDEX2LABEL)
# load datasets BUT ONLY for creating the dataset vocabulary (this is
# important because the TEES tokenizer produces very different results
# compared to the gensim `simple_preprocess` tokenizer, which was used
# to create the W2V PubMed-based models)
EXTERNAL_DATA = load_data_from_zips(
zips=EXTERNAL_ZIPS,
label2index=LABEL2INDEX,
)
TRAINING_DATA = load_data_from_zips(
zips=TRAINING_ZIPS,
label2index=LABEL2INDEX,
)
TEST_DATA = load_data_from_zips(
zips=TEST_ZIPS,
label2index=LABEL2INDEX,
)
# dataset vocabulary
DATASET_VOCABULARY = set()
data = EXTERNAL_DATA['data'] + TRAINING_DATA['data'] + TEST_DATA['data']
for features in data:
for f in features:
# take advantage of this dataset vocabulary building and check
# that indeed there are not empty strings (sanity check)
for s in f:
assert '' not in s, 'Empty strings not expected!'
DATASET_VOCABULARY.update(f[0])
# free memory (delete temporary dataset)
del EXTERNAL_DATA
del TRAINING_DATA
del TEST_DATA
# load w2v PubMed-based model (normalized vectors)
W2V_PUBMED = load_word2vec(W2V_PUBMED_FPATH)
key = next(iter(W2V_PUBMED))
W2V_DTYPE = W2V_PUBMED[key].dtype
W2V_PUBMED_VOCABULARY = set(W2V_PUBMED)
# w2v model (only with the non-zero-embedding words from the dataset)
W2V = dict()
# create word embeddings only from the dataset vocabulary
for word in DATASET_VOCABULARY:
tokens = tokenize(word, W2V_PUBMED_VOCABULARY)
if len(tokens) > 0:
W2V[word] = normalized_sum(
embeddings=[W2V_PUBMED[t] for t in tokens],
size=W2V_SIZE,
dtype=W2V_DTYPE,
)
# free memory (delete word2vec PubMed-based model)
del W2V_PUBMED
del W2V_PUBMED_VOCABULARY
# W2V dataset-vocabulary (vocabulary only from the dataset)
W2V_VOCABULARY = set(W2V)
UNIQUE_WRD = sorted(W2V_VOCABULARY)
NUM_WRD = len(W2V_VOCABULARY)
W2V_TRAINABLE = False
# filter words (pos/dep) by the W2V vocabulary
WORDS = W2V_VOCABULARY
# load training dataset(s)
EXTERNAL_DATA = load_data_from_zips(
zips=EXTERNAL_ZIPS,
label2index=LABEL2INDEX,
shuffle=True,
random_state=SEED,
words=WORDS,
)
# load training dataset(s)
TRAINING_DATA = load_data_from_zips(
zips=TRAINING_ZIPS,
label2index=LABEL2INDEX,
shuffle=True,
random_state=SEED,
words=WORDS,
)
# load test dataset(s)
TEST_DATA = load_data_from_zips(
zips=TEST_ZIPS,
label2index=LABEL2INDEX,
shuffle=True,
random_state=SEED,
words=WORDS,
)
data = EXTERNAL_DATA['data'] + TRAINING_DATA['data'] + TEST_DATA['data']
# calculate unique POS and unique dependencies from the datasets
UNIQUE_POS = set()
UNIQUE_DEP = set()
for features in data:
for f in features:
UNIQUE_POS.update(f[1])
UNIQUE_DEP.update(f[2])
UNIQUE_POS = sorted(UNIQUE_POS)
NUM_POS = len(UNIQUE_POS)
UNIQUE_DEP = sorted(UNIQUE_DEP)
NUM_DEP = len(UNIQUE_DEP)
if P2V_FPATH is None:
# use Pos2Vec word2vec random embeddings
P2V = {
pos: normalized_rand(P2V_SIZE, dtype=W2V_DTYPE) for pos in UNIQUE_POS
}
P2V_TRAINABLE = True
else:
# use pre-trained Pos2Vec word2vec embeddings
P2V = load_keyedvectors(P2V_FPATH)
# find embeddings size
key = next(iter(P2V))
P2V_SIZE = P2V[key].size
# discard unused words
P2V = {w: v for w, v in P2V.items() if w in UNIQUE_POS}
# add unknown words (full zeros: non-informative)
for w in UNIQUE_POS:
if w not in P2V:
P2V[w] = np.zeros(P2V_SIZE, dtype=W2V_DTYPE)
# pre-trained embeddings (fixed)
P2V_TRAINABLE = False
if D2V_FPATH is None:
# use Dep2Vec word2vec random embeddings
D2V = {
dep: normalized_rand(D2V_SIZE, dtype=W2V_DTYPE) for dep in UNIQUE_DEP
}
# attention: the empty incoming edge is represented by the `#none`
# tag and it was randomly initialized on purpose (maybe
# it is relevant to know that a word does not have
# incoming edges)
D2V_TRAINABLE = True
else:
# use pre-trained Dep2Vec word2vec embeddings
D2V = load_keyedvectors(D2V_FPATH)
# find embeddings size
key = next(iter(D2V))
D2V_SIZE = D2V[key].size
# discard unused words
D2V = {w: v for w, v in D2V.items() if w in UNIQUE_DEP}
# add unknown words (full zeros: non-informative)
for w in UNIQUE_DEP:
if w not in D2V:
D2V[w] = np.zeros(D2V_SIZE, dtype=W2V_DTYPE)
# pre-trained embeddings (fixed)
D2V_TRAINABLE = False
# wrd/pos/dep vectorizers (index 0 is used for padding)
WRD2INT = {w: i for i, w in enumerate(UNIQUE_WRD, start=1)}
POS2INT = {p: i for i, p in enumerate(UNIQUE_POS, start=1)}
DEP2INT = {d: i for i, d in enumerate(UNIQUE_DEP, start=1)}
# embedding matrixes:
# +1 is added because the index 0 is used for padding (non-informative)
# W2V embedding matrix
W2V_MATRIX = np.zeros((NUM_WRD + 1, W2V_SIZE), dtype=W2V_DTYPE)
for index, word in enumerate(UNIQUE_WRD, start=1):
W2V_MATRIX[index] = W2V[word]
# P2V embedding matrix
P2V_MATRIX = np.zeros((NUM_POS + 1, P2V_SIZE), dtype=W2V_DTYPE)
for index, pos in enumerate(UNIQUE_POS, start=1):
P2V_MATRIX[index] = P2V[pos]
# D2V embedding matrix
D2V_MATRIX = np.zeros((NUM_DEP + 1, D2V_SIZE), dtype=W2V_DTYPE)
for index, dep in enumerate(UNIQUE_DEP, start=1):
D2V_MATRIX[index] = D2V[dep]
# SDP and L/R CHEM/GENE maximum lengths
if 0:
# automatically choose maximum values (requires more processing)
SDP_MAXLEN = -1
LR_MAXLEN = -1
for features in data:
sdp, lch, rch, lge, rge = features
SDP_MAXLEN = max(SDP_MAXLEN, len(sdp[0]))
LR_MAXLEN = max(
LR_MAXLEN,
len(lch[0]),
len(rch[0]),
len(lge[0]),
len(rge[0]),
)
else:
# manually chosen
SDP_MAXLEN = 10
LR_MAXLEN = 20
# to "plot" a histogram of SDP and LR lengths
# to help to manually choose values for SDP_MAXLEN and LR_MAXLEN doing
# a compromise between system performance (time of execution) and system
# quality (ability to correctly predict)
if 0:
n = len(data)
sdp_lens = np.zeros(shape=n, dtype='uint32')
lch_lens = np.zeros(shape=n, dtype='uint32')
rch_lens = np.zeros(shape=n, dtype='uint32')
lge_lens = np.zeros(shape=n, dtype='uint32')
rge_lens = np.zeros(shape=n, dtype='uint32')
for i, features in enumerate(data):
sdp, lch, rch, lge, rge = features
sdp_lens[i] = len(sdp[0])
lch_lens[i] = len(lch[0])
rch_lens[i] = len(rch[0])
lge_lens[i] = len(lge[0])
rge_lens[i] = len(rge[0])
lens = [sdp_lens, lch_lens, rch_lens, lge_lens, rge_lens]
seqs = ['SDP', 'LCH', 'RCH', 'LGE', 'RGE']
for s, l in zip(seqs, lens):
print('{} lengths'.format(s))
for v in set(l):
percentage = (np.sum(l <= v) / n) * 100
print('up to {:2d}: {:6.2f}%'.format(v, percentage))
print()
# Keras-related constants
# batch size [16, 32, 64, 128, 256, 512]
BATCH_SIZE = 128
# patience [10, 20, 30, 50]
PATIENCE = 30
# epochs [100, 200, 300, 500, 1000]
EPOCHS = 500
# validation split [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]
VALIDATION_SPLIT = 0.3
def get_features(data):
n_features = 5
x = [list() for i in range(n_features*3)]
# go through all data
for features in data:
# sanity check: all data must have the same number of features
assert len(features) == n_features
# sdp, lch, rch, lge, rge
for i, f in enumerate(features):
# wrd, pos, dep
for j, s in enumerate(f):
x[i*3+j].append(s)
return x
def convert_features(x):
TOK2INT = [WRD2INT, POS2INT, DEP2INT]
MAXLEN = [SDP_MAXLEN] * 3 + [LR_MAXLEN] * 12
PADDING = ['post']*3 + ['pre']*3 + ['post']*3 + ['pre']*3 + ['post']*3
TRUNCATING = PADDING
n_features = 5 * 3
assert len(x) == n_features
y = [list() for i in range(n_features)]
for i, tokseqs in enumerate(x):
y[i] = tokseqs2intseqs(
tokseqs=tokseqs,
tok2int=TOK2INT[i%3],
maxlen=MAXLEN[i],
padding=PADDING[i],
truncating=TRUNCATING[i],
)
return y
def build_model(
dropout_rate=0.4,
gaussiannoise_stddev=0.01,
conv1d_filters=64,
conv1d_kernel_sizes=[3, 4, 5],
lstm_units=128,
lstm_dropout=0.4,
lstm_recurrent_dropout=0.4,
):
# for reproducibility
np.random.seed(SEED)
rn.seed(SEED)
tf.set_random_seed(SEED)
# Input
sdp_wrd_input = Input(shape=(SDP_MAXLEN,), dtype='int32')
sdp_pos_input = Input(shape=(SDP_MAXLEN,), dtype='int32')
sdp_dep_input = Input(shape=(SDP_MAXLEN,), dtype='int32')
lch_wrd_input = Input(shape=(LR_MAXLEN,), dtype='int32')
lch_pos_input = Input(shape=(LR_MAXLEN,), dtype='int32')
lch_dep_input = Input(shape=(LR_MAXLEN,), dtype='int32')
rch_wrd_input = Input(shape=(LR_MAXLEN,), dtype='int32')
rch_pos_input = Input(shape=(LR_MAXLEN,), dtype='int32')
rch_dep_input = Input(shape=(LR_MAXLEN,), dtype='int32')
lge_wrd_input = Input(shape=(LR_MAXLEN,), dtype='int32')
lge_pos_input = Input(shape=(LR_MAXLEN,), dtype='int32')
lge_dep_input = Input(shape=(LR_MAXLEN,), dtype='int32')
rge_wrd_input = Input(shape=(LR_MAXLEN,), dtype='int32')
rge_pos_input = Input(shape=(LR_MAXLEN,), dtype='int32')
rge_dep_input = Input(shape=(LR_MAXLEN,), dtype='int32')
# Embedding
wrd_emb = Embedding(input_dim=NUM_WRD+1, output_dim=W2V_SIZE, weights=[W2V_MATRIX], trainable=W2V_TRAINABLE)
pos_emb = Embedding(input_dim=NUM_POS+1, output_dim=P2V_SIZE, weights=[P2V_MATRIX], trainable=P2V_TRAINABLE)
dep_emb = Embedding(input_dim=NUM_DEP+1, output_dim=D2V_SIZE, weights=[D2V_MATRIX], trainable=D2V_TRAINABLE)
# convert integer indexes to embeddings
sdp_wrd = wrd_emb(sdp_wrd_input)
sdp_pos = pos_emb(sdp_pos_input)
sdp_dep = dep_emb(sdp_dep_input)
lch_wrd = wrd_emb(lch_wrd_input)
lch_pos = pos_emb(lch_pos_input)
lch_dep = dep_emb(lch_dep_input)
rch_wrd = wrd_emb(rch_wrd_input)
rch_pos = pos_emb(rch_pos_input)
rch_dep = dep_emb(rch_dep_input)
lge_wrd = wrd_emb(lge_wrd_input)
lge_pos = pos_emb(lge_pos_input)
lge_dep = dep_emb(lge_dep_input)
rge_wrd = wrd_emb(rge_wrd_input)
rge_pos = pos_emb(rge_pos_input)
rge_dep = dep_emb(rge_dep_input)
# concatenate
if WRD and POS and DEP:
sdp = concatenate([sdp_wrd, sdp_pos, sdp_dep])
lr = concatenate([
lch_wrd, lch_pos, lch_dep,
rch_wrd, rch_pos, rch_dep,
lge_wrd, lge_pos, lge_dep,
rge_wrd, rge_pos, rge_dep,
])
elif WRD and POS:
sdp = concatenate([sdp_wrd, sdp_pos])
lr = concatenate([
lch_wrd, lch_pos,
rch_wrd, rch_pos,
lge_wrd, lge_pos,
rge_wrd, rge_pos,
])
elif WRD and DEP:
sdp = concatenate([sdp_wrd, sdp_dep])
lr = concatenate([
lch_wrd, lch_dep,
rch_wrd, rch_dep,
lge_wrd, lge_dep,
rge_wrd, rge_dep,
])
elif POS and DEP:
sdp = concatenate([sdp_pos, sdp_dep])
lr = concatenate([
lch_pos, lch_dep,
rch_pos, rch_dep,
lge_pos, lge_dep,
rge_pos, rge_dep,
])
elif WRD:
sdp = sdp_wrd
lr = concatenate([
lch_wrd,
rch_wrd,
lge_wrd,
rge_wrd,
])
elif POS:
sdp = sdp_pos
lr = concatenate([
lch_pos,
rch_pos,
lge_pos,
rge_pos,
])
elif DEP:
sdp = sdp_dep
lr = concatenate([
lch_dep,
rch_dep,
lge_dep,
rge_dep,
])
else:
assert False, 'WRD, POS, and DEP are False!'
# GaussianNoise
sdp = GaussianNoise(stddev=gaussiannoise_stddev)(sdp)
lr = GaussianNoise(stddev=gaussiannoise_stddev)(lr)
if MODEL == 'cnn':
sdps = list()
lrs = list()
for kernel_size in conv1d_kernel_sizes:
# Conv1D
c = Conv1D(filters=conv1d_filters, kernel_size=kernel_size, activation='relu')(sdp)
# GlobalMaxPooling1D
g = GlobalMaxPooling1D()(c)
sdps.append(g)
# Conv1D
c = Conv1D(filters=conv1d_filters, kernel_size=kernel_size, activation='relu')(lr)
# GlobalMaxPooling1D
g = GlobalMaxPooling1D()(c)
lrs.append(g)
if len(conv1d_kernel_sizes) > 1:
# concatenate
sdp = concatenate(sdps)
lr = concatenate(lrs)
else:
sdp = sdps[0]
lr = lrs[0]
elif MODEL == 'lstm':
# LSTM, Bidirectional
sdp = Bidirectional(LSTM(units=lstm_units, dropout=lstm_dropout, recurrent_dropout=lstm_recurrent_dropout))(sdp)
lr = Bidirectional(LSTM(units=lstm_units, dropout=lstm_dropout, recurrent_dropout=lstm_recurrent_dropout))(lr)
else:
assert False, 'Invalid model!'
# concatenate
if SDP and LR:
merged = concatenate([sdp, lr])
elif SDP:
merged = sdp
elif LR:
merged = lr
else:
assert False, 'SDP and LR are False!'
# Dropout
merged = Dropout(rate=dropout_rate, seed=0)(merged)
# Dense
preds = Dense(units=NUM_CLASSES, activation='softmax')(merged)
# Model
model = Model(
inputs=[
sdp_wrd_input, sdp_pos_input, sdp_dep_input,
lch_wrd_input, lch_pos_input, lch_dep_input,
rch_wrd_input, rch_pos_input, rch_dep_input,
lge_wrd_input, lge_pos_input, lge_dep_input,
rge_wrd_input, rge_pos_input, rge_dep_input,
],
outputs=preds,
)
# for reproducibility
np.random.seed(SEED)
rn.seed(SEED)
tf.set_random_seed(SEED)
# Model.compile
model.compile(
optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['acc'],
)
return model
# main code
printer = Printer(filepath=LOGS_FPATH)
D = printer.date
P = printer.print
D('Start!')
P(
'--------------------------------\n'
'--- BioCreative VI -------------\n'
'------- Track 5 (CHEMPROT) -----\n'
'--------------------------------\n'
)
P(
'See the Keras Model consulting the \'build_model\' function '
'in the \'-main.py\' saved script.\n'
)
P('main input arguments\n')
P(
'\tSEED\n'
'\t\t{}\n'.format(SEED)
)
P(
'\tMODEL\n'
'\t\t{}\n'.format(MODEL)
)
P(
'\tEXTERNAL_GROUPS\n'
'\t\t{}\n'.format(EXTERNAL_GROUPS)
)
P(
'\tTRAINING_GROUPS\n'
'\t\t{}\n'.format(TRAINING_GROUPS)
)
P(
'\tTEST_GROUPS\n'
'\t\t{}\n'.format(TEST_GROUPS)
)
P(
'\tSDP\n'
'\t\t{}\n'.format(SDP)
)
P(
'\tLR\n'
'\t\t{}\n'.format(LR)
)
P(
'\tWRD\n'
'\t\t{}\n'.format(WRD)
)
P(
'\tPOS\n'
'\t\t{}\n'.format(POS)
)
P(
'\tDEP\n'
'\t\t{}\n'.format(DEP)
)
P(
'\tW2V_SIZE\n'
'\t\t{}\n'.format(W2V_SIZE)
)
P(
'\tW2V_WINDOW\n'
'\t\t{}\n'.format(W2V_WINDOW)
)
P(
'\tW2V_PUBMED_FPATH\n'
'\t\t{}\n'.format(W2V_PUBMED_FPATH)
)
P(
'\tP2V_FPATH\n'
'\t\t{}\n'.format(P2V_FPATH)
)
P(
'\tP2V_SIZE\n'
'\t\t{}\n'.format(P2V_SIZE)
)
P(
'\tD2V_FPATH\n'
'\t\t{}\n'.format(D2V_FPATH)
)
P(
'\tD2V_SIZE\n'
'\t\t{}\n'.format(D2V_SIZE)
)
P('output directory\n')
P(
'\tOUT\n'
'\t\t{}\n'.format(OUT)
)
P('output files\n')
P(
'\tLOGS_FPATH\n'
'\t\t{}\n'.format(LOGS_FPATH)
)
P(
'\tPREDICTIONS_FPATH\n'
'\t\t{}\n'.format(PREDICTIONS_FPATH)
)
P(
'\tPROBABILITIES_FPATH\n'
'\t\t{}\n'.format(PROBABILITIES_FPATH)
)
P(
'\tBEST_MODEL_FPATH\n'
'\t\t{}\n'.format(BEST_MODEL_FPATH)
)
P(
'\tHISTORY_FPATH\n'
'\t\t{}\n'.format(HISTORY_FPATH)
)
P(
'\tMAIN_FPATH\n'
'\t\t{}\n'.format(MAIN_FPATH)
)
P('other variables\n')
P(
'\tEXTERNAL_ZIPS\n'
'\t\t{}\n'.format(EXTERNAL_ZIPS)
)
P(
'\tTRAINING_ZIPS\n'
'\t\t{}\n'.format(TRAINING_ZIPS)
)
P(
'\tTEST_ZIPS\n'
'\t\t{}\n'.format(TEST_ZIPS)
)
P(
'\tTEST_GS_FPATHS\n'
'\t\t{}\n'.format(TEST_GS_FPATHS)
)
P(
'\tNUM_CLASSES\n'
'\t\t{}\n'.format(NUM_CLASSES)
)
P(
'\tW2V_DTYPE\n'
'\t\t{}\n'.format(W2V_DTYPE)
)
P(
'\tUNIQUE_WRD[:20]\n'
'\t\t{}\n'.format(UNIQUE_WRD[:20])
)
P(
'\tNUM_WRD\n'
'\t\t{}\n'.format(NUM_WRD)
)
P(
'\tUNIQUE_POS\n'
'\t\t{}\n'.format(UNIQUE_POS)
)
P(
'\tNUM_POS\n'
'\t\t{}\n'.format(NUM_POS)
)
P(
'\tUNIQUE_DEP\n'
'\t\t{}\n'.format(UNIQUE_DEP)
)
P(
'\tNUM_DEP\n'
'\t\t{}\n'.format(NUM_DEP)
)
P(
'\tW2V_TRAINABLE\n'
'\t\t{}\n'.format(W2V_TRAINABLE)
)
P(
'\tP2V_TRAINABLE\n'
'\t\t{}\n'.format(P2V_TRAINABLE)
)
P(
'\tD2V_TRAINABLE\n'
'\t\t{}\n'.format(D2V_TRAINABLE)
)
P(
'\tW2V_MATRIX.shape\n'
'\t\t{}\n'.format(W2V_MATRIX.shape)
)
P(
'\tP2V_MATRIX.shape\n'
'\t\t{}\n'.format(P2V_MATRIX.shape)
)
P(
'\tD2V_MATRIX.shape\n'
'\t\t{}\n'.format(D2V_MATRIX.shape)
)
P(
'\tSDP_MAXLEN\n'
'\t\t{}\n'.format(SDP_MAXLEN)
)
P(
'\tLR_MAXLEN\n'
'\t\t{}\n'.format(LR_MAXLEN)
)
P('keras-related constants\n')
P(
'\tBATCH_SIZE\n'
'\t\t{}\n'.format(BATCH_SIZE)
)
P(
'\tPATIENCE\n'
'\t\t{}\n'.format(PATIENCE)
)
P(
'\tEPOCHS\n'
'\t\t{}\n'.format(EPOCHS)
)
P(
'\tVALIDATION_SPLIT\n'
'\t\t{}\n'.format(VALIDATION_SPLIT)
)
P('sanity check\n')
P(
'\tlen(EXTERNAL_DATA[\'data\'])\n'
'\t\t{}\n'.format(len(EXTERNAL_DATA['data']))
)
P(
'\tlen(set(EXTERNAL_DATA[\'target\']))\n'
'\t\t{}\n'.format(len(set(EXTERNAL_DATA['target'])))
)
P(
'\tlen(TRAINING_DATA[\'data\'])\n'
'\t\t{}\n'.format(len(TRAINING_DATA['data']))
)
P(
'\tlen(set(TRAINING_DATA[\'target\']))\n'
'\t\t{}\n'.format(len(set(TRAINING_DATA['target'])))
)
P(
'\tlen(TEST_DATA[\'data\'])\n'
'\t\t{}\n'.format(len(TEST_DATA['data']))
)
P(
'\tlen(set(TEST_DATA[\'target\']))\n'
'\t\t{}\n'.format(len(set(TEST_DATA['target'])))
)
# wrd/pos/dep features (lists of lists of lists of strings)
# lists of samples:
# each sample is a list of five features:
# SDP, LCH, RCH, LGE, RGE
# each feature has three kinds of information:
# WRD, POS, DEP
# each type of information is represented by a list of strings
external = get_features(EXTERNAL_DATA['data'])
train = get_features(TRAINING_DATA['data'])
test = get_features(TEST_DATA['data'])
# wrd/pos/dep features (lists of numpy arrays)
x_external = convert_features(external)
x_train = convert_features(train)
x_test = convert_features(test)
# y_external, y_train and y_test (labels)
y_external_int = np.array(EXTERNAL_DATA['target'], dtype='int32')
y_train_int = np.array(TRAINING_DATA['target'], dtype='int32')
y_test_int = np.array(TEST_DATA['target'], dtype='int32')
# convert integer labels to binary vectors (one-hot encoding)
y_external = to_categorical(
y=y_external_int,
num_classes=NUM_CLASSES,
)
y_train = to_categorical(
y=y_train_int,
num_classes=NUM_CLASSES,
)
y_test = to_categorical(
y=y_test_int,
num_classes=NUM_CLASSES,
)
P('len(x_external)')
P('\t{}\n'.format(len(x_external)))
P('len(x_train)')
P('\t{}\n'.format(len(x_train)))
P('len(x_test)')
P('\t{}\n'.format(len(x_test)))
for i, v in enumerate(x_external):
P('x_external[{}].shape'.format(i))
P('\t{}\n'.format(v.shape))
for i, v in enumerate(x_train):
P('x_train[{}].shape'.format(i))
P('\t{}\n'.format(v.shape))
for i, v in enumerate(x_test):
P('x_test[{}].shape'.format(i))
P('\t{}\n'.format(v.shape))
P('y_external.shape')