-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmodels.py
320 lines (219 loc) · 10.9 KB
/
models.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
# Copyright 2020, 37.78 Tecnologia Ltda.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, Embedding, Dense, Conv1D, GlobalAveragePooling1D, BatchNormalization, GRU
from tensorflow.keras.layers import Layer, Attention
from tensorflow.keras.optimizers import Adam
import pandas as pd
import numpy as np
import utils
# Try to import CuDNNGRU, otherwise use regular GRU
try:
from tensorflow.keras.layers import CuDNNGRU as GRU
except ImportError:
no_requests = True
class CTE_Model:
def __init__(self, args, load_path=None):
self.args = args
def cte_model(self):
pass
def fit(self, most_occ_train=None): # CTE_Model does not use X data
# Select most occuring ICDs in train set
self.most_occ_train = most_occ_train[:self.args.k]
def predict(self, X, mlb):
y_pred = np.repeat([self.most_occ_train[:self.args.k]],repeats=len(X),axis=0)
y_pred = mlb.transform(y_pred)
return y_pred
class LR_Model:
def __init__(self, args=None, load_path=None):
# You could load from path but also get args, in order to continue training.
self.args = args
self.model = None
if load_path:
self.load_path = load_path
self.load_from_path()
def load_from_path(self):
self.model = load_model(self.load_path)
def lr_model(self, input_shape, output_shape):
if not self.args.lr: ### check how to instantiate default values
self.args.lr = 0.1
# Create LR
inputs = Input(shape=(input_shape,))
outputs = Dense(output_shape, activation='sigmoid')(inputs)
model = Model(inputs, outputs)
model.compile(loss='binary_crossentropy',optimizer=Adam(self.args.lr))
return model
def fit(self, X, y, validation_data=None, callbacks=None):
if not self.model:
self.model = self.lr_model(X[0].shape[0], y[0].shape[0])
if self.args.verbose: self.model.summary()
self.model.fit(X, y, validation_data=validation_data,
epochs=self.args.epochs, batch_size=self.args.batch_size,
callbacks=callbacks, verbose=self.args.verbose)
def predict(self, X):
return self.model.predict(X)
def save_model(self, path):
# No need to save model if f1_callback is used, as it already saved model at best epoch
self.model.save(path)
class CNN_Model:
def __init__(self, args=None, load_path=None):
self.args = args
self.model = None
if load_path:
self.load_path = load_path
self.load_from_path()
def load_from_path(self):
self.model = load_model(self.load_path)
def cnn_model(self, input_shape, output_shape, embedding_matrix):
if not self.args.lr:
self.args.lr = 0.001
# Define model
sequence_input = Input(shape=(input_shape,),) #dtype='int32'
embedding_layer = Embedding(input_dim = embedding_matrix.shape[0],
output_dim = embedding_matrix.shape[1],
weights = [embedding_matrix],
input_length = input_shape,
trainable = True) (sequence_input)
H = Conv1D(self.args.units, self.args.kernel_size, activation=self.args.activation, padding='same')(embedding_layer)
H = BatchNormalization() (H)
x = GlobalAveragePooling1D()(H)
preds = Dense(output_shape, activation='sigmoid')(x)
model = Model(sequence_input, preds)
model.compile(loss='binary_crossentropy',optimizer=Adam(self.args.lr))
return model
def fit(self, X, y, embedding_matrix, validation_data=None, callbacks=None):
if not self.model:
self.model = self.cnn_model(X[0].shape[0], y[0].shape[0], embedding_matrix)
if self.args.verbose: self.model.summary()
self.model.fit(X, y, validation_data=validation_data,
epochs=self.args.epochs, batch_size=self.args.batch_size,
callbacks=callbacks, verbose=self.args.verbose)
def predict(self, X):
return self.model.predict(X)
def save_model(self, path):
# No need to save model if f1_callback is used, as it already saved model at best epoch
self.model.save(path)
class GRU_Model:
def __init__(self,args=None, load_path=None):
self.args = args
self.model = None
if load_path:
self.load_path = load_path
self.load_from_path()
def load_from_path(self):
self.model = load_model(self.load_path)
def gru_model(self, input_shape, output_shape, embedding_matrix):
if not self.args.lr:
self.args.lr = 8e-4
# Build model
sequence_input = Input(shape=(input_shape,), dtype='int32')
embedding_layer = Embedding(input_dim = embedding_matrix.shape[0],
output_dim = embedding_matrix.shape[1],
weights = [embedding_matrix],
input_length = input_shape,
trainable = True) (sequence_input)
# Note that if cudnn is available CuDNNGRU will be used for faster training
x = GRU(self.args.units, return_sequences=True) (embedding_layer)
x = BatchNormalization() (x)
x = GlobalAveragePooling1D() (x)
outputs = Dense(output_shape, activation='sigmoid') (x)
model = Model(sequence_input, outputs)
model.compile(loss='binary_crossentropy',optimizer=Adam(self.args.lr))
return model
def fit(self, X, y, embedding_matrix, validation_data=None, callbacks=None):
if not self.model:
# self.model = self.gru_model(X.shape[1], y.shape[1], embedding_matrix)
self.model = self.gru_model(X[0].shape[0], y[0].shape[0], embedding_matrix)
if self.args.verbose: self.model.summary()
self.model.fit(X, y, validation_data=validation_data,
epochs=self.args.epochs, batch_size=self.args.batch_size,
callbacks=callbacks, verbose=self.args.verbose)
def predict(self, X):
return self.model.predict(X)
def save_model(self, path):
# No need to save model if f1_callback is used, as it already saved model at best epoch
self.model.save(path)
class CNNAtt_Model:
def __init__(self,args=None, load_path=None):
self.args = args
self.model = None
if load_path:
self.load_path = load_path
self.load_from_path()
def load_from_path(self):
self.model = load_model(self.load_path)
#Custom layer to generate per-label weights
class TrainableMatrix(Layer):
def __init__(self, n_rows, n_cols, **kwargs):
super().__init__(**kwargs)
self.n_rows = n_rows
self.n_cols = n_cols
def build(self, input_shape):
self.U = self.add_weight(name='trainmat', shape=(self.n_rows, self.n_cols), initializer='glorot_uniform', trainable=True)
# super(self.TrainableMatrix, self).build(input_shape)
super().build(input_shape)
def call(self, inputs):
return self.U
# Custom layer to apply a LR for each label and then concatenate predictions
class Hadamard(Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight(name='kernel',
shape=(1,) + tuple([int(a) for a in input_shape[1:]]),
initializer='glorot_uniform',
trainable=True)
self.bias = self.add_weight(name='bias',
shape=(1,) + tuple([int(a) for a in input_shape[1:]]),
initializer='zeros',
trainable=True)
# super(self.Hadamard, self).build(input_shape)
super().build(input_shape)
def call(self, x):
return tf.keras.activations.sigmoid(tf.reduce_sum(x*self.kernel + self.bias, axis=-1))
def compute_output_shape(self, input_shape):
return input_shape
# Main model
def cnn_att_model(self, input_shape, output_shape, embedding_matrix):
if not self.args.lr:
self.args.lr = 0.001
# Define model
sequence_input = Input(shape=(input_shape,), dtype='int32')
embedding_layer = Embedding(input_dim = embedding_matrix.shape[0],
output_dim = embedding_matrix.shape[1],
weights = [embedding_matrix],
input_length = input_shape,
trainable = True) (sequence_input)
H = Conv1D(self.args.units, self.args.kernel_size, activation=self.args.activation, padding='same')(embedding_layer)
H = BatchNormalization() (H)
U = self.TrainableMatrix(output_shape,self.args.units)([])
att = Attention(use_scale=True) ([U, H])
preds = self.Hadamard() (att)
model = Model(sequence_input, preds)
model.compile(loss='binary_crossentropy',optimizer=Adam(self.args.lr))
return model
def fit(self, X, y, embedding_matrix, validation_data=None, callbacks=None):
if not self.model:
# self.model = self.cnn_att_model(X.shape[1], y.shape[1], embedding_matrix)
self.model = self.cnn_att_model(X[0].shape[0], y[0].shape[0], embedding_matrix)
if self.args.verbose: self.model.summary()
self.model.fit(X, y, validation_data=validation_data,
epochs=self.args.epochs, batch_size=self.args.batch_size,
callbacks=callbacks, verbose=self.args.verbose)
def predict(self, X):
return self.model.predict(X)
def save_model(self, path):
# No need to save model if f1_callback is used, as it already saved model at best epoch
self.model.save(path)