-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgp_check2.py
151 lines (126 loc) · 5.44 KB
/
gp_check2.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
# gp4ts1 100
import math
import numpy as np
import torch
import gpytorch
import os
from matplotlib import pyplot as plt
import gp4ts
import gp4ts1
import os
import math
from dataclasses import dataclass
from torch.quasirandom import SobolEngine
from botorch.utils.transforms import unnormalize
from gpytorch.constraints import Interval
from gpytorch.kernels import MaternKernel, ScaleKernel
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.mlls import ExactMarginalLogLikelihood
from botorch.test_functions import Ackley
x_dim = list(range(1, 101))
y_dim = np.zeros_like(x_dim, dtype=np.float32)
num_exp = 150
average = []
dimensions = []
# for dimension in x_dim:
for dimension in range(1, 101, 10):
print('dim:', dimension)
lst_iters=[]
for _ in range(num_exp):
#print('dim:', dimension)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dtype = torch.double
SMOKE_TEST = os.environ.get("SMOKE_TEST")
fun = Ackley(dim=dimension, negate=True).to(dtype=dtype, device=device)
fun.bounds[0, :].fill_(-5)
fun.bounds[1, :].fill_(10)
dim = fun.dim
lb, ub = fun.bounds
n_init = dim*2
# if dim == 1:
# n_init = dim*2
# else:
# n_init = dim
max_cholesky_size = float("inf") # Always use Cholesky
def eval_objective(x):
"""This is a helper function we use to unnormalize and evalaute a point"""
return fun(unnormalize(x, fun.bounds))
def get_initial_points(dim, n_pts, seed=0):
sobol = SobolEngine(dimension=dim, scramble=True, seed=seed)
X_init = sobol.draw(n=n_pts).to(dtype=dtype, device=device)
return X_init
train_x = get_initial_points(dim, n_init)
Y_turbo = torch.tensor(
[eval_objective(x) for x in train_x], dtype=dtype, device=device)
train_y = (Y_turbo - Y_turbo.mean()) / Y_turbo.std()
# now unsqueeze
# train_x = train_x.unsqueeze(-1)
class ExactGPModel(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())
self.covar_module = gpytorch.kernels.ScaleKernel( # Use the same lengthscale prior as in the TuRBO paper
MaternKernel(nu=2.5, ard_num_dims=dim, lengthscale_constraint=Interval(0.005, 4.0))
)
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
# initialize likelihood and model
likelihood = gpytorch.likelihoods.GaussianLikelihood(noise_constraint=Interval(1e-8, 1e-3))
gp_model = ExactGPModel(train_x, train_y, likelihood)
# Find optimal model hyperparameters
training_iter = 150 #300
gp_model.train()
likelihood.train()
# Use the adam optimizer
optimizer = torch.optim.Adam(gp_model.parameters(), lr=0.1)#1.5) # Includes GaussianLikelihood parameters
# "Loss" for GPs - the marginal log likelihood
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# train gp_model
for i in range(training_iter):
# Zero gradients from previous iteration
optimizer.zero_grad()
# Output from model
output = gp_model(train_x)
# Calc loss and backprop gradients
loss = -mll(output, train_y)
loss.backward()
# print('Iter %d/%d - Loss: %.3f lengthscale: %.3f noise: %.3f' % (
# i + 1, training_iter, loss.item(),
# gp_model.covar_module.base_kernel.lengthscale.item(),
# gp_model.likelihood.noise.item()
# ))
optimizer.step()
gp_model.eval()
likelihood.eval()
lengthscale = gp_model.covar_module.base_kernel.lengthscale
#print("lengthscale: ", lengthscale)
# test local_TS
initializer = train_x[torch.argmin(train_y)].unsqueeze(0)
#print("initializer: ", initializer)
#initializer = torch.linalg.norm(initializer).unsqueeze(0).unsqueeze(0)
star_x, num_iter = gp4ts1.local_thompson_sample(gp_model, initializer, dim=dim)
lst_iters.append(num_iter)
full_iters = torch.tensor(lst_iters).float()
#print("num_iters: ", lst_iters)
# star_x_norm = torch.linalg.norm(star_x)
lengthscale_norm = torch.linalg.norm(lengthscale)
# star_y = star_x*lengthscale_norm
star_y = torch.linalg.norm(star_x - initializer)/lengthscale_norm
# star_y = torch.linalg.norm(star_x - initializer)*lengthscale_norm
# star_y = 1/star_y
# star_y = -star_y
# y = torch.linalg.norm(star_y)
# y = star_x_norm/lengthscale_norm
# y_dim.append(star_y.data)
#y_dim[dim-1] = y_dim[dim-1] + star_y
#print("next_point:", star_x.data)#, "lengthscale:", lengthscale.data)
# print('lengthscale_norm:', lengthscale_norm.data, 'y*:', star_y.data)
exp_mean = lst_iters.mean()
average.append(exp_mean)
print("Average: ", average)
dimensions.append(dimension)
y_dim = y_dim/num_exp
print("Y_dim:", y_dim)