-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmain_api_automl.py
319 lines (255 loc) · 11.5 KB
/
main_api_automl.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
"""Main function for AutoML in time-series predictions.
Pipeline
Step 1: Load dataset
- data_name: mimic, ward, cf
Step 2: Preprocess dataset
(0) NegativeFilter: Replace negative values to NaN
(1) OneHotEncoder: One hot encoding certain features
(2) Normalization (3 options): MinMax, Standard, None
Step 3: Define problem
- problem: one-shot or online
- label_name: the column name for the label(s)
- max_seq_len: maximum sequence length after padding
- treatment: the column name for treatments
Step 4: Impute dataset
(0) Static imputation (6 options): mean, median, mice, missforest, knn, gain
(1) Temporal imputation (8 options): mean, median, linear, quadratic, cubic, spline, mrnn, tgain
Step 5: Feature selection
- feature selection method (5 options): greedy-addition, greedy-deletion, recursive-addition, recursive-deletion, None
Step 6: Fit and Predict AutoML
- possible predictive models (6 options): lstm, gru, rnn, attention, tcn, transformer
Step 7: Visualize Results
- metric_name (4 options): auc, apr, mse, mae
(1) Visualize the performance
(2) Visualize the predictions
"""
# Necessary packages
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import warnings
warnings.filterwarnings("ignore")
import sys
sys.path.append("../")
from datasets import CSVLoader
from preprocessing import FilterNegative, OneHotEncoder, Normalizer, ProblemMaker
from imputation import Imputation
from feature_selection import FeatureSelection
from prediction import GeneralRNN, TemporalCNN, TransformerPredictor, Attention
from prediction import AutoEnsemble, StackingEnsemble
import automl
from evaluation import Metrics, BOMetric
from evaluation import print_performance, print_prediction
from utils import PipelineComposer
def main(args):
"""Main function for AutoML in time-series predictions.
Args:
- data loading parameters:
- data_names: mimic, ward, cf
- preprocess parameters:
- normalization: minmax, standard, None
- one_hot_encoding: input features that need to be one-hot encoded
- problem: 'one-shot' or 'online'
- 'one-shot': one time prediction at the end of the time-series
- 'online': preditcion at every time stamps of the time-series
- max_seq_len: maximum sequence length after padding
- label_name: the column name for the label(s)
- treatment: the column name for treatments
- imputation parameters:
- static_imputation_model: mean, median, mice, missforest, knn, gain
- temporal_imputation_model: mean, median, linear, quadratic, cubic, spline, mrnn, tgain
- feature selection parameters:
- feature_selection_model: greedy-addition, greedy-deletion, recursive-addition, recursive-deletion, None
- feature_number: selected featuer number
- predictor_parameters:
- epochs: number of epochs
- bo_itr: bayesian optimization iterations
- static_mode: how to utilize static features (concatenate or None)
- time_mode: how to utilize time information (concatenate or None)
- task: classification or regression
- metric_name: auc, apr, mae, mse
"""
#%% Step 0: Set basic parameters
metric_sets = [args.metric_name]
metric_parameters = {"problem": args.problem, "label_name": [args.label_name]}
#%% Step 1: Upload Dataset
# File names
data_directory = "../datasets/data/" + args.data_name + "/" + args.data_name + "_"
data_loader_training = CSVLoader(
static_file=data_directory + "static_train_data.csv.gz",
temporal_file=data_directory + "temporal_train_data_eav.csv.gz",
)
data_loader_testing = CSVLoader(
static_file=data_directory + "static_test_data.csv.gz",
temporal_file=data_directory + "temporal_test_data_eav.csv.gz",
)
dataset_training = data_loader_training.load()
dataset_testing = data_loader_testing.load()
print("Finish data loading.")
#%% Step 2: Preprocess Dataset
# (0) filter out negative values (Automatically)
negative_filter = FilterNegative()
# (1) one-hot encode categorical features
onehot_encoder = OneHotEncoder(one_hot_encoding_features=[args.one_hot_encoding])
# (2) Normalize features: 3 options (minmax, standard, none)
normalizer = Normalizer(args.normalization)
filter_pipeline = PipelineComposer(negative_filter, onehot_encoder, normalizer)
dataset_training = filter_pipeline.fit_transform(dataset_training)
dataset_testing = filter_pipeline.transform(dataset_testing)
print("Finish preprocessing.")
#%% Step 3: Define Problem
problem_maker = ProblemMaker(
problem=args.problem, label=[args.label_name], max_seq_len=args.max_seq_len, treatment=args.treatment
)
dataset_training = problem_maker.fit_transform(dataset_training)
dataset_testing = problem_maker.fit_transform(dataset_testing)
print("Finish defining problem.")
#%% Step 4: Impute Dataset
static_imputation = Imputation(imputation_model_name=args.static_imputation_model, data_type="static")
temporal_imputation = Imputation(imputation_model_name=args.temporal_imputation_model, data_type="temporal")
imputation_pipeline = PipelineComposer(static_imputation, temporal_imputation)
dataset_training = imputation_pipeline.fit_transform(dataset_training)
dataset_testing = imputation_pipeline.transform(dataset_testing)
print("Finish imputation.")
#%% Step 5: Feature selection (4 options)
static_feature_selection = FeatureSelection(
feature_selection_model_name=args.static_feature_selection_model,
feature_type="static",
feature_number=args.static_feature_selection_number,
task=args.task,
metric_name=args.metric_name,
metric_parameters=metric_parameters,
)
temporal_feature_selection = FeatureSelection(
feature_selection_model_name=args.temporal_feature_selection_model,
feature_type="temporal",
feature_number=args.temporal_feature_selection_number,
task=args.task,
metric_name=args.metric_name,
metric_parameters=metric_parameters,
)
feature_selection_pipeline = PipelineComposer(static_feature_selection, temporal_feature_selection)
dataset_training = feature_selection_pipeline.fit_transform(dataset_training)
dataset_testing = feature_selection_pipeline.transform(dataset_testing)
print("Finish feature selection.")
#%% Step 6: Bayesian Optimization
## Model define
# RNN model
rnn_parameters = {
"model_type": "lstm",
"epoch": args.epochs,
"static_mode": args.static_mode,
"time_mode": args.time_mode,
"verbose": False,
}
general_rnn = GeneralRNN(task=args.task)
general_rnn.set_params(**rnn_parameters)
# CNN model
cnn_parameters = {
"epoch": args.epochs,
"static_mode": args.static_mode,
"time_mode": args.time_mode,
"verbose": False,
}
temp_cnn = TemporalCNN(task=args.task)
temp_cnn.set_params(**cnn_parameters)
# Transformer
transformer = TransformerPredictor(
task=args.task, epoch=args.epochs, static_mode=args.static_mode, time_mode=args.time_mode
)
# Attention model
attn_parameters = {
"model_type": "lstm",
"epoch": args.epochs,
"static_mode": args.static_mode,
"time_mode": args.time_mode,
"verbose": False,
}
attn = Attention(task=args.task)
attn.set_params(**attn_parameters)
# model_class_list = [general_rnn, attn, temp_cnn, transformer]
model_class_list = [general_rnn, attn]
# train_validate split
dataset_training.train_val_test_split(prob_val=0.2, prob_test=0.1)
# Bayesian Optimization Start
metric = BOMetric(metric="auc", fold=0, split="test")
ens_model_list = []
# Run BO for each model class
for m in model_class_list:
BO_model = automl.model.AutoTS(dataset_training, m, metric, model_path="tmp/")
models, bo_score = BO_model.training_loop(num_iter=args.bo_itr)
auto_ens_model = AutoEnsemble(models, bo_score)
ens_model_list.append(auto_ens_model)
# Load all ensemble models
for ens in ens_model_list:
for m in ens.models:
m.load_model(BO_model.model_path + "/" + m.model_id + ".h5")
# Stacking algorithm
stacking_ens_model = StackingEnsemble(ens_model_list)
stacking_ens_model.fit(dataset_training, fold=0, train_split="val")
# Prediction
assert not dataset_testing.is_validation_defined
test_y_hat = stacking_ens_model.predict(dataset_testing, test_split="test")
test_y = dataset_testing.label
print("Finish AutoML model training and testing.")
#%% Step 7: Visualize Results
idx = np.random.permutation(len(test_y_hat))[:2]
# Evaluate predictor model
result = Metrics(metric_sets, metric_parameters).evaluate(test_y, test_y_hat)
print("Finish predictor model evaluation.")
# Visualize the output
# (1) Performance
print("Overall performance")
print_performance(result, metric_sets, metric_parameters)
# (2) Predictions
print("Each prediction")
print_prediction(test_y_hat[idx], metric_parameters)
return
#%%
if __name__ == "__main__":
# Inputs for the main function
parser = argparse.ArgumentParser()
parser.add_argument("--data_name", choices=["mimic", "ward", "cf"], default="cf", type=str)
parser.add_argument("--normalization", choices=["minmax", "standard", None], default="minmax", type=str)
parser.add_argument("--one_hot_encoding", default="admission_type", type=str)
parser.add_argument("--problem", choices=["online", "one-shot"], default="one-shot", type=str)
parser.add_argument("--max_seq_len", help="maximum sequence length", default=24, type=int)
parser.add_argument("--label_name", default="death", type=str)
parser.add_argument("--treatment", default=None, type=str)
parser.add_argument(
"--static_imputation_model",
choices=["mean", "median", "mice", "missforest", "knn", "gain"],
default="median",
type=str,
)
parser.add_argument(
"--temporal_imputation_model",
choices=["mean", "median", "linear", "quadratic", "cubic", "spline", "mrnn", "tgain"],
default="median",
type=str,
)
parser.add_argument(
"--static_feature_selection_model",
choices=["greedy-addition", "greedy-deletion", "recursive-addition", "recursive-deletion", None],
default=None,
type=str,
)
parser.add_argument("--static_feature_selection_number", default=10, type=int)
parser.add_argument(
"--temporal_feature_selection_model",
choices=["greedy-addition", "greedy-deletion", "recursive-addition", "recursive-deletion", None],
default=None,
type=str,
)
parser.add_argument("--temporal_feature_selection_number", default=10, type=int)
parser.add_argument("--epochs", default=20, type=int)
parser.add_argument("--bo_itr", default=20, type=int)
parser.add_argument("--static_mode", choices=["concatenate", None], default="concatenate", type=str)
parser.add_argument("--time_mode", choices=["concatenate", None], default="concatenate", type=str)
parser.add_argument("--task", choices=["classification", "regression"], default="classification", type=str)
parser.add_argument("--metric_name", choices=["auc", "apr", "mse", "mae"], default="auc", type=str)
args = parser.parse_args()
# Call main function
main(args)