-
Notifications
You must be signed in to change notification settings - Fork 0
/
hpo_baseline_experiment.py
220 lines (187 loc) · 5.53 KB
/
hpo_baseline_experiment.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
import argparse
import json
import os
from typing import Dict
import optuna
import numpy as np
import pandas as pd
from baseline_experiment import main
from search_spaces import (
hpo_space_logistic,
hpo_space_dtree,
hpo_space_random_forest,
hpo_space_catboost,
hpo_space_tabnet,
)
from utils import get_dataset
ENCODE_CATEGORICAL_VARIABLES = {
'random_forest': True,
'catboost': True,
'decision_tree': True,
'logistic_regression': True,
'tabnet': False,
}
def objective(
trial: optuna.trial.Trial,
args: argparse.Namespace,
X_train: np.ndarray,
y_train: np.ndarray,
X_valid: np.ndarray,
y_valid: np.ndarray,
categorical_indicator: np.ndarray,
attribute_names: np.ndarray,
dataset_name: str,
) -> float:
"""The objective function for hyperparameter optimization.
Args:
trial: The optuna trial object.
args: The arguments for the experiment.
X_train: The training examples.
y_train: The training labels.
X_valid: The validation examples.
y_valid: The validation labels.
categorical_indicator: The categorical indicator for the features.
attribute_names: The feature names.
dataset_name: The name of the dataset.
Returns:
The test AUROC.
"""
if args.model_name == 'logistic_regression':
hp_config = hpo_space_logistic(trial)
elif args.model_name == 'decision_tree':
hp_config = hpo_space_dtree(trial)
elif args.model_name == 'catboost':
hp_config = hpo_space_catboost(trial)
elif args.model_name == 'random_forest':
hp_config = hpo_space_random_forest(trial)
elif args.model_name == 'tabnet':
hp_config = hpo_space_tabnet(trial)
output_info = main(
args,
hp_config,
X_train,
y_train,
X_valid,
y_valid,
categorical_indicator,
attribute_names,
dataset_name,
)
return output_info['test_auroc']
def hpo_main(args):
"""The main function for hyperparameter optimization."""
info = get_dataset(
args.dataset_id,
test_split_size=args.test_split_size,
seed=args.seed,
encode_categorical=ENCODE_CATEGORICAL_VARIABLES[args.model_name],
hpo_tuning=args.hpo_tuning,
)
dataset_name = info['dataset_name']
attribute_names = info['attribute_names']
X_train = info['X_train']
X_test = info['X_test']
y_train = info['y_train']
y_test = info['y_test']
if args.hpo_tuning:
X_valid = info['X_valid']
y_valid = info['y_valid']
categorical_indicator = info['categorical_indicator']
output_directory = os.path.join(args.output_dir, f'{args.model_name}', f'{args.dataset_id}', f'{args.seed}')
os.makedirs(output_directory, exist_ok=True)
if args.hpo_tuning:
time_limit = 60 * 60
study = optuna.create_study(
direction='maximize',
sampler=optuna.samplers.TPESampler(seed=args.seed),
)
try:
study.optimize(
lambda trial: objective(
trial,
args,
X_train,
y_train,
X_valid,
y_valid,
categorical_indicator,
attribute_names,
dataset_name,
),
n_trials=args.n_trials,
timeout=time_limit,
)
except Exception as e:
print(f'Optimization stopped: {e}')
try:
best_params = study.best_params
except ValueError:
best_params = None
trial_df = study.trials_dataframe(attrs=('number', 'value', 'params', 'state'))
trial_df.to_csv(os.path.join(output_directory, 'trials.csv'), index=False)
# concatenate train and validation as pandas
X_train = pd.concat([X_train, X_valid], axis=0)
y_train = np.concatenate([y_train, y_valid], axis=0)
output_info = main(
args,
best_params if args.hpo_tuning else None,
X_train,
y_train,
X_test,
y_test,
categorical_indicator,
attribute_names,
dataset_name,
)
with open(os.path.join(output_directory, 'output_info.json'), 'w') as f:
json.dump(output_info, f)
if __name__ == "__main__":
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--seed',
type=int,
default=0,
help='Random seed'
)
parser.add_argument(
'--dataset_id',
type=int,
default=1590,
help='Dataset id'
)
parser.add_argument(
'--test_split_size',
type=float,
default=0.2,
help='Test size'
)
parser.add_argument(
'--model_name',
type=str,
default='tabnet',
help='The name of the baseline model to use',
)
parser.add_argument(
'--output_dir',
type=str,
default='.',
help='Directory to save the results',
)
parser.add_argument(
'--hpo_tuning',
action='store_true',
help='Whether to perform hyperparameter tuning',
)
parser.add_argument(
'--n_trials',
type=int,
default=100,
help='Number of trials for hyperparameter tuning',
)
parser.add_argument(
'--disable_wandb',
action='store_true',
help='Whether to disable wandb logging',
)
args = parser.parse_args()
hpo_main(args)