-
Notifications
You must be signed in to change notification settings - Fork 389
/
tuner.py
278 lines (257 loc) · 9.34 KB
/
tuner.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
import os
import json
import joblib
import optuna
from supervised.utils.metric import Metric
from supervised.tuner.optuna.lightgbm import LightgbmObjective
from supervised.tuner.optuna.xgboost import XgboostObjective
from supervised.tuner.optuna.catboost import CatBoostObjective
from supervised.tuner.optuna.random_forest import RandomForestObjective
from supervised.tuner.optuna.extra_trees import ExtraTreesObjective
from supervised.tuner.optuna.knn import KNNObjective
from supervised.tuner.optuna.nn import NeuralNetworkObjective
from supervised.exceptions import AutoMLException
class OptunaTuner:
def __init__(
self,
results_path,
ml_task,
eval_metric,
time_budget=3600,
init_params={},
verbose=True,
n_jobs=-1,
random_state=42,
):
if eval_metric.name not in [
"auc",
"logloss",
"rmse",
"mae",
"mape",
"r2",
"spearman",
"pearson",
"f1",
"average_precision",
"accuracy"
]:
raise AutoMLException(f"Metric {eval_metric.name} is not supported")
self.study_dir = os.path.join(results_path, "optuna")
if not os.path.exists(self.study_dir):
try:
os.mkdir(self.study_dir)
except Exception as e:
print("Problem while creating directory for optuna studies.", str(e))
self.tuning_fname = os.path.join(self.study_dir, "optuna.json")
self.tuning = init_params
self.eval_metric = eval_metric
self.direction = (
"maximize" if Metric.optimize_negative(eval_metric.name) else "minimize"
)
self.n_warmup_steps = (
500 # set large enough to give small learning rates a chance
)
self.time_budget = time_budget
self.verbose = verbose
self.ml_task = ml_task
self.n_jobs = n_jobs
self.random_state = random_state
self.cat_features_indices = []
data_info_fname = os.path.join(results_path, "data_info.json")
if os.path.exists(data_info_fname):
data_info = json.loads(open(data_info_fname).read())
for i, (k, v) in enumerate(data_info["columns_info"].items()):
if "categorical" in v:
self.cat_features_indices += [i]
self.load()
if not self.verbose:
optuna.logging.set_verbosity(optuna.logging.CRITICAL)
@staticmethod
def is_optimizable(algorithm_name):
return algorithm_name in [
"Extra Trees",
"Random Forest",
"CatBoost",
"Xgboost",
"LightGBM",
"Nearest Neighbors",
"Neural Network",
]
def optimize(
self,
algorithm,
data_type,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
learner_params,
):
# only tune models with original data type
if data_type != "original":
return learner_params
key = f"{data_type}_{algorithm}"
if key in self.tuning:
return self.update_learner_params(learner_params, self.tuning[key])
if self.verbose:
print(
f"Optuna optimizes {algorithm} with time budget {self.time_budget} seconds "
f"eval_metric {self.eval_metric.name} ({self.direction})"
)
study = optuna.create_study(
direction=self.direction,
sampler=optuna.samplers.TPESampler(seed=self.random_state),
pruner=optuna.pruners.MedianPruner(n_warmup_steps=self.n_warmup_steps),
)
obejctive = None
if algorithm == "LightGBM":
objective = LightgbmObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.cat_features_indices,
self.n_jobs,
self.random_state,
)
elif algorithm == "Xgboost":
objective = XgboostObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.n_jobs,
self.random_state,
)
elif algorithm == "CatBoost":
objective = CatBoostObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.cat_features_indices,
self.n_jobs,
self.random_state,
)
elif algorithm == "Random Forest":
objective = RandomForestObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.n_jobs,
self.random_state,
)
elif algorithm == "Extra Trees":
objective = ExtraTreesObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.n_jobs,
self.random_state,
)
elif algorithm == "Nearest Neighbors":
objective = KNNObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.n_jobs,
self.random_state,
)
elif algorithm == "Neural Network":
objective = NeuralNetworkObjective(
self.ml_task,
X_train,
y_train,
sample_weight,
X_validation,
y_validation,
sample_weight_validation,
self.eval_metric,
self.n_jobs,
self.random_state,
)
study.optimize(objective, n_trials=5000, timeout=self.time_budget)
joblib.dump(study, os.path.join(self.study_dir, key + ".joblib"))
best = study.best_params
if algorithm == "LightGBM":
best["metric"] = objective.eval_metric_name
best["custom_eval_metric_name"] = objective.custom_eval_metric_name
best["num_boost_round"] = objective.rounds
best["early_stopping_rounds"] = objective.early_stopping_rounds
# best["learning_rate"] = objective.learning_rate
best["cat_feature"] = self.cat_features_indices
best["feature_pre_filter"] = False
best["seed"] = objective.seed
elif algorithm == "CatBoost":
best["eval_metric"] = objective.eval_metric_name
best["num_boost_round"] = objective.rounds
best["early_stopping_rounds"] = objective.early_stopping_rounds
# best["bootstrap_type"] = "Bernoulli"
# best["learning_rate"] = objective.learning_rate
best["seed"] = objective.seed
elif algorithm == "Xgboost":
best["objective"] = objective.objective
best["eval_metric"] = objective.eval_metric_name
# best["eta"] = objective.learning_rate
best["max_rounds"] = objective.rounds
best["early_stopping_rounds"] = objective.early_stopping_rounds
best["seed"] = objective.seed
elif algorithm == "Extra Trees":
# Extra Trees are not using early stopping
best["max_steps"] = objective.max_steps # each step has 100 trees
best["seed"] = objective.seed
best["eval_metric_name"] = self.eval_metric.name
elif algorithm == "Random Forest":
# Random Forest is not using early stopping
best["max_steps"] = objective.max_steps # each step has 100 trees
best["seed"] = objective.seed
best["eval_metric_name"] = self.eval_metric.name
elif algorithm == "Nearest Neighbors":
best["rows_limit"] = 100000
elif algorithm == "Neural Network":
pass
self.tuning[key] = best
self.save()
return self.update_learner_params(learner_params, best)
def update_learner_params(self, learner_params, best):
for k, v in best.items():
learner_params[k] = v
return learner_params
def save(self):
with open(self.tuning_fname, "w") as fout:
fout.write(json.dumps(self.tuning, indent=4))
def load(self):
if os.path.exists(self.tuning_fname):
params = json.loads(open(self.tuning_fname).read())
for k, v in params.items():
self.tuning[k] = v