-
Notifications
You must be signed in to change notification settings - Fork 84
/
script_hyperparam_opt.py
231 lines (185 loc) · 7.83 KB
/
script_hyperparam_opt.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
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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
#
# http://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.
# Lint as: python3
"""Main hyperparameter optimisation script.
Performs random search to optimize hyperparameters on a single machine. For new
datasets, inputs to the main(...) should be customised.
"""
import argparse
import datetime as dte
import os
import data_formatters.base
import expt_settings.configs
import libs.hyperparam_opt
import libs.tft_model
import libs.utils as utils
import numpy as np
import pandas as pd
import tensorflow.compat.v1 as tf
ExperimentConfig = expt_settings.configs.ExperimentConfig
HyperparamOptManager = libs.hyperparam_opt.HyperparamOptManager
ModelClass = libs.tft_model.TemporalFusionTransformer
tf.experimental.output_all_intermediates(True)
def main(expt_name, use_gpu, restart_opt, model_folder, hyperparam_iterations,
data_csv_path, data_formatter):
"""Runs main hyperparameter optimization routine.
Args:
expt_name: Name of experiment
use_gpu: Whether to run tensorflow with GPU operations
restart_opt: Whether to run hyperparameter optimization from scratch
model_folder: Folder path where models are serialized
hyperparam_iterations: Number of iterations of random search
data_csv_path: Path to csv file containing data
data_formatter: Dataset-specific data fromatter (see
expt_settings.dataformatter.GenericDataFormatter)
"""
if not isinstance(data_formatter, data_formatters.base.GenericDataFormatter):
raise ValueError(
"Data formatters should inherit from" +
"AbstractDataFormatter! Type={}".format(type(data_formatter)))
default_keras_session = tf.compat.v1.keras.backend.get_session()
if use_gpu:
tf_config = utils.get_default_tensorflow_config(tf_device="gpu", gpu_id=0)
else:
tf_config = utils.get_default_tensorflow_config(tf_device="cpu")
print("### Running hyperparameter optimization for {} ###".format(expt_name))
print("Loading & splitting data...")
raw_data = pd.read_csv(data_csv_path, index_col=0)
train, valid, test = data_formatter.split_data(raw_data)
train_samples, valid_samples = data_formatter.get_num_samples_for_calibration(
)
# Sets up default params
fixed_params = data_formatter.get_experiment_params()
param_ranges = ModelClass.get_hyperparm_choices()
fixed_params["model_folder"] = model_folder
print("*** Loading hyperparm manager ***")
opt_manager = HyperparamOptManager(param_ranges, fixed_params, model_folder)
success = opt_manager.load_results()
if success and not restart_opt:
print("Loaded results from previous training")
else:
print("Creating new hyperparameter optimisation")
opt_manager.clear()
print("*** Running calibration ***")
while len(opt_manager.results.columns) < hyperparam_iterations:
print("# Running hyperparam optimisation {} of {} for {}".format(
len(opt_manager.results.columns) + 1, hyperparam_iterations, "TFT"))
tf.compat.v1.reset_default_graph()
with tf.Graph().as_default(), tf.compat.v1.Session(config=tf_config) as sess:
tf.compat.v1.keras.backend.set_session(sess)
params = opt_manager.get_next_parameters()
model = ModelClass(params, use_cudnn=use_gpu)
if not model.training_data_cached():
model.cache_batched_data(train, "train", num_samples=train_samples)
model.cache_batched_data(valid, "valid", num_samples=valid_samples)
sess.run(tf.compat.v1.global_variables_initializer())
model.fit()
val_loss = model.evaluate()
if np.allclose(val_loss, 0.) or np.isnan(val_loss):
# Set all invalid losses to infintiy.
# N.b. val_loss only becomes 0. when the weights are nan.
print("Skipping bad configuration....")
val_loss = np.inf
opt_manager.update_score(params, val_loss, model)
tf.compat.v1.keras.backend.set_session(default_keras_session)
print("*** Running tests ***")
tf.compat.v1.reset_default_graph()
with tf.Graph().as_default(), tf.compat.v1.Session(config=tf_config) as sess:
tf.compat.v1.keras.backend.set_session(sess)
best_params = opt_manager.get_best_params()
model = ModelClass(best_params, use_cudnn=use_gpu)
model.load(opt_manager.hyperparam_folder)
print("Computing best validation loss")
val_loss = model.evaluate(valid)
print("Computing test loss")
output_map = model.predict(test, return_targets=True)
targets = data_formatter.format_predictions(output_map["targets"])
p50_forecast = data_formatter.format_predictions(output_map["p50"])
p90_forecast = data_formatter.format_predictions(output_map["p90"])
def extract_numerical_data(data):
"""Strips out forecast time and identifier columns."""
return data[[
col for col in data.columns
if col not in {"forecast_time", "identifier"}
]]
p50_loss = utils.numpy_normalised_quantile_loss(
extract_numerical_data(targets), extract_numerical_data(p50_forecast),
0.5)
p90_loss = utils.numpy_normalised_quantile_loss(
extract_numerical_data(targets), extract_numerical_data(p90_forecast),
0.9)
tf.compat.v1.keras.backend.set_session(default_keras_session)
print("Hyperparam optimisation completed @ {}".format(dte.datetime.now()))
print("Best validation loss = {}".format(val_loss))
print("Params:")
for k in best_params:
print(k, " = ", best_params[k])
print()
print("Normalised Quantile Loss for Test Data: P50={}, P90={}".format(
p50_loss.mean(), p90_loss.mean()))
if __name__ == "__main__":
def get_args():
"""Returns settings from command line."""
experiment_names = ExperimentConfig.default_experiments
parser = argparse.ArgumentParser(description="Data download configs")
parser.add_argument(
"expt_name",
metavar="e",
type=str,
nargs="?",
default="volatility",
choices=experiment_names,
help="Experiment Name. Default={}".format(",".join(experiment_names)))
parser.add_argument(
"output_folder",
metavar="f",
type=str,
nargs="?",
default=".",
help="Path to folder for data download")
parser.add_argument(
"use_gpu",
metavar="g",
type=str,
nargs="?",
choices=["yes", "no"],
default="no",
help="Whether to use gpu for training.")
parser.add_argument(
"restart_hyperparam_opt",
metavar="o",
type=str,
nargs="?",
choices=["yes", "no"],
default="yes",
help="Whether to re-run hyperparameter optimisation from scratch.")
args = parser.parse_known_args()[0]
root_folder = None if args.output_folder == "." else args.output_folder
return args.expt_name, root_folder, args.use_gpu == "yes", \
args.restart_hyperparam_opt == "yes"
# Load settings for default experiments
name, folder, use_tensorflow_with_gpu, restart = get_args()
print("Using output folder {}".format(folder))
config = ExperimentConfig(name, folder)
formatter = config.make_data_formatter()
# Customise inputs to main() for new datasets.
main(
expt_name=name,
use_gpu=use_tensorflow_with_gpu,
restart_opt=restart,
model_folder=os.path.join(config.model_folder, "main"),
hyperparam_iterations=config.hyperparam_iterations,
data_csv_path=config.data_csv_path,
data_formatter=formatter)