- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.py
More file actions
Latest commit
133 lines (108 loc) · 4.57 KB
/
Copy pathutils.py
File metadata and controls
133 lines (108 loc) · 4.57 KB
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
importnumpyasnp
importgpytorch
importtorch
fromsklearn.utilsimportcheck_random_state
frombotorch.modelsimportSingleTaskGP
fromgpytorch.mlls.exact_marginal_log_likelihoodimportExactMarginalLogLikelihood
frombotorchimportfit_gpytorch_model
defglobal_optimization(objective_function, boundaries, batch_size):
"""
:param objective_function:
:param boundaries (torch.Tensor): A `2 x d` tensor of lower and upper bounds
for each column of `X`.
:param batch_size (int): Number of candidates to return.
:param optimizer:
:param maxf:
:param random:
Returns:
`(num_restarts) x q x d`-dim tensor of generated candidates
"""
# # USING BOTORCH
frombotorch.optimimportoptimize_acqf
# Boundaries must be (2 x d) for optimize_acqf to work
ifboundaries.shape[0] !=2:
boundaries=boundaries.T
# optimize
candidates, _=optimize_acqf(
acq_function=objective_function,
bounds=boundaries,
q=batch_size,
num_restarts=10, # number of initial points for optimization
raw_samples=512, # used for initialization heuristic
return_best_only=True# only returns the best of the n_restarts random restarts
)
# what exactly is raw_samples?
# Removes the 'candidates' variable from the computational graph
new_x=candidates.detach()
returnnew_x
classExactGPModel(gpytorch.models.ExactGP):
def__init__(self, train_x, train_y, likelihood):
super(ExactGPModel, self).__init__(train_x, train_y, likelihood)
self.mean_module=gpytorch.means.ConstantMean()
self.covar_module=gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
defforward(self, x):
mean_x=self.mean_module(x)
covar_x=self.covar_module(x)
returngpytorch.distributions.MultivariateNormal(mean_x, covar_x)
defget_fitted_model(train_x, train_obj, state_dict=None):
# initialize and fit model
model=SingleTaskGP(train_X=train_x, train_Y=train_obj)
# # initialize likelihood and model
# likelihood = gpytorch.likelihoods.GaussianLikelihood()
# model = ExactGPModel(train_x, train_obj, likelihood)
# model.train()
# likelihood.train()
ifstate_dictisnotNone:
model.load_state_dict(state_dict)
mll=ExactMarginalLogLikelihood(model.likelihood, model)
mll.to(train_x)
fit_gpytorch_model(mll)
returnmodel
classdict_to_tensor_IO():
"""
Map back and forth between dictionary data and tensor data.
Args:
dict_data (dict)
State point described with a key-value pairs.
Returns:
tensor_state_point ((1, d) torch.Tensor)
A tensor version of dict_data, where 'd' is the number of
keys/parameters/features/dimensions.
"""
def__init__(self, dict_data=None):
self.column_indexes_to_keys= {}
# Create the mapping as a dictionary of column_index:key pairs
ifdict_dataisnotNone:
forindex, (key, value) inenumerate(dict_data.items()):
self.column_indexes_to_keys[index] =key
else:
raiseAttributeError('A state point dictionary was not passed.')
defmap_dict_state_point_to_tensor(self, dict_data=None):
"""
Convert state point 'dict_data' into a (1, d) tensor using the map,
'column_indexes_to_keys', and then return the tensor.
"""
ifdict_dataisnotNone:
tensor_state_point=torch.Tensor() # will make this (1, d)
forindex, keyinself.column_indexes_to_keys.items():
value=torch.Tensor([[dict_data[key]]])
tensor_state_point=torch.cat([tensor_state_point, value],
dim=1)
returntensor_state_point
else:
raiseAttributeError('A state point dictionary was not passed.')
defmap_tensor_state_point_to_dict(self, tensor_state_point=None):
"""
Convert (1, d) state point 'tensor_data' into a dict using the map,
'column_indexes_to_keys', and then return the dict.
"""
dict_state_point= {}
if (tensor_state_pointisnotNone) or \
tensor_state_point.shape[0] !=1or \
tensor_state_point.ndim!=2:
forindex, keyinself.column_indexes_to_keys.items():
value=tensor_state_point[0][index]
dict_state_point[key] =float(value)
returndict_state_point
else:
raiseAttributeError('A (1,d) state point tensor was not passed.')