This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
experiment_GPsamples.py
419 lines (363 loc) · 21.1 KB
/
experiment_GPsamples.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
"""
// Copyright (c) 2022 Robert Bosch GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import gpflow
import numpy as np
import pandas as pd
import os
import sys
import pickle
import datetime
import argparse
import matplotlib.pyplot as plt
from pathlib import Path
import functools
print = functools.partial(print, flush=True)
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(".")
sys.path.append(os.path.join(".","toolkits"))
from default_parameters import default_parameters_GPsamples, create_optimizer_args
from my_ALGP_models import ALMOGPR, SafetyMOGPR
from my_plot import *
from my_toolkit import str2bool, raw_wise_compare, return_unused_args, data_selection,\
noise_function, save_model, savefile
from my_data_factory import data_manager_GPsamples
from my_model_factory import model_manager
from gpflow.ci_utils import ci_niter
from gpflow.utilities import deepcopy, print_summary
gpflow.config.set_default_summary_fmt("notebook")
tz = datetime.datetime.now().astimezone().tzinfo
def infer(model, safety_model, BI, best_training=False, **optimizer_args):
if BI:
model.set_training_args(**optimizer_args)
timer = model.HMC_sampling()
safety_model.set_training_args(**optimizer_args)
timer_s = safety_model.HMC_sampling()
elif best_training:
timer = model.best_training(repetition=10, **optimizer_args)
timer_s = safety_model.best_training(repetition=5, **optimizer_args)
else:
timer = model.training(**optimizer_args)
timer_s = safety_model.training(**optimizer_args)
model.history['training_time'].append(timer)
safety_model.history['training_time'].append(timer_s)
return True
#np.random.seed(123)
def experiment_pipeline(i_epoch, iter_num_AL, data_manager, POO
, model_names, model_configs, optimizer_args, query_num, Z_threshold, prob_threshold
, display_figs, save_figs, output_dir):
#######################################################################
########################## Generate datasets ##########################
########################## Generate datasets ##########################
########################## Generate datasets ##########################
########################## Generate datasets ##########################
#######################################################################
np.random.seed(2000 + i_epoch)
data_manager.create_tuples()
X, U, Y, Z = data_manager.create_sample(num=data_manager.num_init_data, safe=False)
_, D, P, T = data_manager.return_dimensions()
X_eval, U_eval, Y_eval, Z_eval = data_manager.true_safe_tuple(Z_threshold, dataset='training')
X_te_eval, U_te_eval, Y_te_eval, Z_te_eval = data_manager.true_safe_tuple(Z_threshold, dataset='test')
# create place holders for experimental result
pred_ref = {'X': X_eval, 'True_Y': Y_eval,
'X_test': X_te_eval, 'True_Y_test': Y_te_eval}
pred_mean = dict()
pred_mean_training = dict()
RMSE_mean = dict()
RMSE_mean_training = dict()
training_log_density = dict()
test_log_density = dict()
safety_summary = { name: pd.DataFrame(np.zeros([0,4], dtype=int),
columns=['num_all_safe_return', 'num_really_safe', 'query_z', 'query_safe_bool']
) for name in model_names
}
for name in model_names:
pred_mean[name] = np.zeros([iter_num_AL, *Y_te_eval.shape])
pred_mean_training[name] = np.zeros([iter_num_AL, *Y_eval.shape])
RMSE_mean[name] = np.zeros([iter_num_AL, P])
RMSE_mean_training[name] = np.zeros([iter_num_AL, P])
test_log_density[name] = np.zeros([iter_num_AL, P])
training_log_density[name] = np.zeros([iter_num_AL, P])
#######################################################################
########################### Build our model ###########################
########################### Build our model ###########################
########################### Build our model ###########################
########################### Build our model ###########################
#######################################################################
mm = model_manager(
model_names,
BI=model_configs['BI'], ML=model_configs['ML'], M=model_configs['M']
)
m = mm.create_main_models(
data = (U, Y), MO = model_configs['MO'],
input_dim = D, y_dim = P,
training_data_args = None,#np.zeros([2, data_manager.num_init_data], dtype=int),
N_init = data_manager.num_init_data
)
m_safety = mm.create_safety_models(
data = (U, Z), training_data_args = None,#np.zeros([2, data_manager.num_init_data], dtype=int),
N_init = data_manager.num_init_data,
safety_threshold = Z_threshold, safety_prob_threshold = prob_threshold,
input_dim = D, z_dim=T
)
m_safety[model_names[3]].assign_safety_threshold(Z_threshold, -1) # this is a baseline without safety constraint
"""
I noticed that the very first training always need more than actual time
"""
warmup_m = ALMOGPR(
(U,Y),
gpflow.kernels.LinearCoregionalization([gpflow.kernels.Matern52() for _ in range(P)], W=np.eye(P)),
np.array([1.0 for _ in range(P)]),
num_latent_gps = P,
history_initialize = True
)
_ = warmup_m.training(**optimizer_args)
del warmup_m
#######################################################################
########################### ACTIVE LEARNING ###########################
########################### ACTIVE LEARNING ###########################
########################### ACTIVE LEARNING ###########################
########################### ACTIVE LEARNING ###########################
#######################################################################
for i in range(iter_num_AL):
if not display_figs:
plt.clf()
##### training
for name in model_names:
infer(m[name], m_safety[name], BI=model_configs['BI'], best_training=(i<=-5), **optimizer_args)
##### caculate the RMSE for all models
for name in model_names:
# test data
mu, _ = m[name].predict_f(U_te_eval)
pred_mean[name][i, :, :] = mu.numpy()
RMSE_mean[name][i, :] = np.sqrt(np.mean(
np.power(Y_te_eval - pred_mean[name][i, :, :], 2),
axis=0
))
# training data
mu, _ = m[name].predict_f(U_eval)
pred_mean_training[name][i, :, :] = mu.numpy()
RMSE_mean_training[name][i, :] = np.sqrt(np.mean(
np.power(Y_eval - mu.numpy(), 2),
axis=0
))
##### caculate the log_density of (U_eval, Y_eval) for all models
training_log_density[name][i, :] = m[name].predict_log_density_full_output((U_eval, Y_eval)).numpy().sum(axis=0)
test_log_density[name][i, :] = m[name].predict_log_density_full_output((U_te_eval, Y_te_eval)).numpy().sum(axis=0)
##### dertermine safe points
D_safe = {}
_, U_explor, _, _ = data_manager.training_pool
for name in model_names:
_, args_safe = m_safety[name].return_safe_points(U_explor, return_index=True)
D_safe[name] = data_selection(data_manager.training_pool, args_safe)
##### plot & save models
"""
not implemented yet
"""
##### print training info
if i==iter_num_AL-1:
# save models
for name in model_names:
save_model(os.path.join(output_dir, "models", f"model_exp_{i_epoch}_{name}_iter{i}.txt"), m[name])
save_model(os.path.join(output_dir, "models", f"model_safety_exp_{i_epoch}_{name}_iter{i}.txt"), m_safety[name])
print("##############################################"+\
"\n###### ######"+\
"\n###### experiment %7d ######"%(i_epoch)+\
"\n###### iteration %4d/%4d ######"%(i+1, iter_num_AL)+\
"\n###### ######"+\
"\n###### Training ######")
for ind in range(len(model_names)):
print("###### %-20s: %7.3f(s) ######"%(model_names[ind], m[model_names[ind]].history["training_time"][-1]))
print("###### safety_model: %7.3f(s) ######"%(m_safety[model_names[ind]].history["training_time"][-1]))
print("###### ######"+\
"\n###### Done Training ######"+\
"\n###### ######"+\
"\n##############################################\n")
break
##### update datasets for next iteration
# determine the most uncertain point(s) among safe points
for j, name in enumerate(model_names):
_, U_pool, Y_pool, Z_safe = D_safe[name]
unused_idx = return_unused_args(m[name].data, (U_pool, Y_pool))
D_pool = data_selection(D_safe[name], unused_idx)
if j == 1:
_, args_new = m[name].query_points(
D_pool[1:3],
num_return = query_num,
acquition_function='random',
full_task_query=not POO,
return_index=True
)
else:
_, args_new = m[name].query_points(
D_pool[1:3],
full_output_cov = True,
num_return = query_num,
acquition_function = 'entropy',
full_task_query = not POO,
return_index=True
)
_, U_new, Y_new, Z_new = data_selection(D_pool, args_new)
m[name].update_dataset((U_new, Y_new))
m_safety[name].update_dataset((U_new, Z_new))
safety_summary[name] = safety_summary[name].append(
pd.DataFrame([[
Z_safe.shape[0], # the total points returned by model as safe
np.sum(Z_safe > m_safety[name].Z_threshold), # how many are actually safe
Z_new,
Z_new > m_safety[name].Z_threshold
]], index=pd.RangeIndex(i, i+1), columns=safety_summary[name].columns.values
)
)
print("##############################################"+\
"\n###### ######"+\
"\n###### experiment %7d ######"%(i_epoch)+\
"\n###### iteration %4d/%4d ######"%(i+1, iter_num_AL)+\
"\n###### ######"+\
"\n###### Training ######")
for ind in range(len(model_names)):
print("###### %-20s: %7.3f(s) ######"%(model_names[ind], m[model_names[ind]].history["training_time"][-1]))
print("###### safety_model: %7.3f(s) ######"%(m_safety[model_names[ind]].history["training_time"][-1]))
print("###### ######"+\
"\n###### Datapoints query ######")
for ind in range(len(model_names)):
print("###### %-20s: %7.3f(s) ######"%(model_names[ind], m[model_names[ind]].history["point_selection_time"][-1]))
print("###### ######"+\
"\n##############################################\n")
return m, m_safety, pred_ref, pred_mean, pred_mean_training, RMSE_mean, RMSE_mean_training, test_log_density, training_log_density, safety_summary
if __name__ == "__main__":
pars = default_parameters_GPsamples()
parser = argparse.ArgumentParser(description='Run ALSVGPvsOthers, toy dataset.')
# experiment settings
parser.add_argument('--POO', default= pars.POO, type=str2bool, nargs='?', const=True, help=f"defauls={pars.POO}, whether the outputs are partially observed or not")
parser.add_argument('--experiment_index', default= pars.experiment_index, type=int, help=f"defauls={pars.experiment_index}, if we run this script in parallel, we would need indices to distinguish different trials")
parser.add_argument('--repetition', default= pars.repetition, type=int, help=f"default={pars.repetition}, number of run experiments, notice that the experiments are NOT run in parallel")
parser.add_argument('--iteration_num', default= pars.iteration_num, type=int, help=f"default={pars.iteration_num}, number of active learning iteration")
# experiment settings, data & models & functions
parser.add_argument('--num_init_data', default=pars.num_init_data, type=int, help=f"default={pars.num_init_data}, number initial data points")
parser.add_argument('--fullGP', default=pars.fullGP, type=str2bool, nargs='?', const=True, help=f"default={pars.fullGP}, whether we want full GP or (S)VGP, when True, M is useless")
parser.add_argument('--bayesian', default=pars.bayesian, type=str2bool, nargs='?', const=True, help=f"default={pars.bayesian}, whether we run Bayesian inference or not, only for full GP")
parser.add_argument('--M', default= pars.M, type=int, help=f"default={pars.M}, number of inducing points")
parser.add_argument('--query_num', default= pars.query_num, type=int, help=f"default={pars.query_num}, number of query points in each active learning iteration")
parser.add_argument('--optimizer', default=pars.optimizer, type=str, help=f"default={pars.optimizer}, optimizer (currently 'scipy', 'natgrad_adam', or 'adam', case-insensitive)")
parser.add_argument('--data_noise_std', default= pars.data_noise_std, nargs=2, type=float, help=f"default={pars.data_noise_std}, standard deviation of observations, 2 output dims")
parser.add_argument('--data_noise_std_safety', default= pars.data_noise_std_safety, type=float, help=f"default={pars.data_noise_std_safety}, standard deviation of safety label observations")
# experiment settings, safety constraint
parser.add_argument('--safety_threshold', default= pars.safety_threshold, type=float, help=f"default={pars.safety_threshold}, safe when safety label is above this threshold")
parser.add_argument('--safety_prob_threshold', default= pars.safety_prob_threshold, type=float, help=f"default={pars.safety_prob_threshold}, safe when p(safety label above safety_threshold) >= this prob_threshold")
# save result
parser.add_argument('--display_figs', default= pars.display_figs, type=str2bool, nargs='?', const=True, help=f"default={pars.display_figs}, whether the figures are shown")
parser.add_argument('--save_figs', default= pars.save_figs, type=str2bool, nargs='?', const=True, help=f"default={pars.save_figs}, whether the figures are saved")
parser.add_argument('--input_dir', default= pars.input_dir, type=str, help=f"default={pars.input_dir}, where to load the data")
parser.add_argument('--output_dir', default= pars.output_dir, type=str, help=f"default={pars.output_dir}, where to save the results")
args = parser.parse_args()
optimizer_args = create_optimizer_args(args.optimizer)
exp_idx = args.experiment_index
iter_num_AL = args.iteration_num
Z_threshold = args.safety_threshold
prob_threshold = args.safety_prob_threshold
data_noise_std = np.array(args.data_noise_std)
data_noise_std_safety = args.data_noise_std_safety
num_init_data = args.num_init_data if args.POO else int(args.num_init_data / len(data_noise_std))
query_num = args.query_num
model_names = ["AL_MOGP", "RS_MOGP", "AL_indGPs", "AL_MOGP_nosafe"]
MO = [True, True, False, True]
ML = args.fullGP # if False, then variational inference
BI = args.bayesian and ML
M = args.M
model_configs = {'MO':MO, 'ML':ML, 'BI':BI, 'M':M}
output_dir = args.output_dir
if BI:
folder_key = 'BGP'
elif ML:
folder_key = 'fullGP'
else:
folder_key = f'M{M}'
if args.POO:
output_dir += f"_POO"
output_dir = os.path.join(output_dir, folder_key)
else:
output_dir = os.path.join(output_dir, folder_key)
Path(os.path.join(output_dir, "pkl_files", "individual_trials")).mkdir(parents=True, exist_ok=True)
Path(os.path.join(output_dir, "models")).mkdir(parents=True, exist_ok=True)
exp_data_manager = data_manager_GPsamples(
exp_idx=exp_idx,
data_dir=args.input_dir,
noise_function = noise_function,
noise_std=data_noise_std,
noise_std_safety=data_noise_std_safety,
num_init_data=num_init_data,
POO=args.POO
)
def run(i):
with open(os.path.join(output_dir, 'experiment_setup.txt'), 'w') as fp:
time_now = datetime.datetime.now(tz = tz)
print(time_now.strftime('%Z (UTC%z)\n%Y.%b.%d %A %H:%M:%S\n'), file = fp)
print(f"data noise / safety noise (std) : {data_noise_std} / {data_noise_std_safety}", file=fp)
print("AL, num of initial training points : %d"%(num_init_data), file = fp)
print("AL, num of iterations : %d"%(iter_num_AL), file = fp)
print("AL, num of quering points : %d"%(query_num), file = fp)
print("safety threshold (probability) : >%f (with p>=%.3f)"%(Z_threshold, prob_threshold), file = fp)
print("\n\n\ntraining & test data drawn: \n", file = fp)
fp.writelines(open(os.path.join(args.input_dir, 'data_parameters.txt'), mode='r').readlines()[3:])
m, m_safety, pred_ref, pred_mean, pred_mean_training, RMSE_mean, RMSE_mean_training, test_log_density, training_log_density, safety_summary = \
experiment_pipeline(i, iter_num_AL, exp_data_manager, args.POO
, model_names, model_configs, optimizer_args, query_num, Z_threshold, prob_threshold
, args.display_figs, args.save_figs, output_dir)
Training_time = {
model_names[ind]: m[model_names[ind]].history["training_time"] for ind in range(len(model_names))
}
data_selection_time = {
model_names[ind]: m[model_names[ind]].history["point_selection_time"] for ind in range(len(model_names))
}
savefile(os.path.join(output_dir, "pkl_files", "pred_ref.pkl"),
pred_ref,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"pred_mean_exp{i}.pkl"),
pred_mean,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"pred_mean_training_exp{i}.pkl"),
pred_mean_training,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"RMSE_mean_exp{i}.pkl"),
RMSE_mean,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"RMSE_mean_training_exp{i}.pkl"),
RMSE_mean_training,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"test_log_density_exp{i}.pkl"),
test_log_density,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"training_log_density_exp{i}.pkl"),
training_log_density,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"Training_time_exp{i}.pkl"),
Training_time,
mode = "wb")
savefile(os.path.join(output_dir, "pkl_files", "individual_trials", f"data_selection_time_exp{i}.pkl"),
data_selection_time,
mode = "wb")
fullpath_noextention = os.path.join(output_dir, "pkl_files", "individual_trials", f"safety_summary_exp{i}")
savefile(fullpath_noextention+'.pkl', safety_summary, mode='wb')
with open(fullpath_noextention+'.txt', mode='w') as fp:
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', 2000)
for name in model_names:
print(f'model: {name}', file=fp)
print(f'{safety_summary[name]}\n\n', file=fp)
for i in range(args.repetition):
run(exp_idx*1000 + i)