-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathrun.py
241 lines (192 loc) · 7.62 KB
/
run.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
import numpy as np
import pandas as pd
import sklearn.decomposition
import sklearn.impute
import time
import torch
import kernels
import gplvm
from utils import transform_forward, transform_backward
import bo
torch.set_default_tensor_type(torch.FloatTensor)
fn_data = 'all_normalized_accuracy_with_pipelineID.csv'
fn_train_ix = 'ids_train.csv'
fn_test_ix = 'ids_test.csv'
fn_data_feats = 'data_feats_featurized.csv'
def get_data():
"""
returns the train/test splits of the dataset as N x D matrices and the
train/test dataset features used for warm-starting bo as D x F matrices.
N is the number of pipelines, D is the number of datasets (in train/test),
and F is the number of dataset features.
"""
df = pd.read_csv(fn_data)
pipeline_ids = df['Unnamed: 0'].tolist()
dataset_ids = df.columns.tolist()[1:]
dataset_ids = [int(dataset_ids[i]) for i in range(len(dataset_ids))]
Y = df.values[:,1:].astype(np.float64)
ids_train = np.loadtxt(fn_train_ix).astype(int).tolist()
ids_test = np.loadtxt(fn_test_ix).astype(int).tolist()
ix_train = [dataset_ids.index(i) for i in ids_train]
ix_test = [dataset_ids.index(i) for i in ids_test]
Ytrain = Y[:, ix_train]
Ytest = Y[:, ix_test]
df = pd.read_csv(fn_data_feats)
dataset_ids = df[df.columns[0]].tolist()
ix_train = [dataset_ids.index(i) for i in ids_train]
ix_test = [dataset_ids.index(i) for i in ids_test]
Ftrain = df.values[ix_train, 1:]
Ftest = df.values[ix_test, 1:]
return Ytrain, Ytest, Ftrain, Ftest
def train(m, optimizer, f_callback=None, f_stop=None):
it = 0
while True:
try:
t = time.time()
optimizer.zero_grad()
nll = m()
nll.backward()
optimizer.step()
it += 1
t = time.time() - t
if f_callback is not None:
f_callback(m, nll, it, t)
# f_stop should not be a substantial portion of total iteration time
if f_stop is not None and f_stop(m, nll, it, t):
break
except KeyboardInterrupt:
break
return m
def bo_search(m, bo_n_init, bo_n_iters, Ytrain, Ftrain, ftest, ytest,
do_print=False):
"""
initializes BO with L1 warm-start (using dataset features). returns a
numpy array of length bo_n_iters holding the best performance attained
so far per iteration (including initialization).
bo_n_iters includes initialization iterations, i.e., after warm-start, BO
will run for bo_n_iters - bo_n_init iterations.
"""
preds = bo.BO(m.dim, m.kernel, bo.ei,
variance=transform_forward(m.variance))
ix_evaled = []
ix_candidates = np.where(np.invert(np.isnan(ytest)))[0].tolist()
ybest_list = []
ix_init = bo.init_l1(Ytrain, Ftrain, ftest).tolist()
for l in range(bo_n_init):
ix = ix_init[l]
if not np.isnan(ytest[ix]):
preds.add(m.X[ix], ytest[ix])
ix_evaled.append(ix)
ix_candidates.remove(ix)
yb = preds.ybest
if yb is None:
yb = np.nan
ybest_list.append(yb)
if do_print:
print('Iter: %d, %g [%d], Best: %g' % (l, ytest[ix], ix, yb))
for l in range(bo_n_init, bo_n_iters):
ix = ix_candidates[preds.next(m.X[ix_candidates])]
preds.add(m.X[ix], ytest[ix])
ix_evaled.append(ix)
ix_candidates.remove(ix)
ybest_list.append(preds.ybest)
if do_print:
print('Iter: %d, %g [%d], Best: %g' \
% (l, ytest[ix], ix, preds.ybest))
return np.asarray(ybest_list)
def random_search(bo_n_iters, ytest, speed=1, do_print=False):
"""
speed denotes how many random queries are performed per iteration.
"""
ix_evaled = []
ix_candidates = np.where(np.invert(np.isnan(ytest)))[0].tolist()
ybest_list = []
ybest = np.nan
for l in range(bo_n_iters):
for ll in range(speed):
ix = ix_candidates[np.random.permutation(len(ix_candidates))[0]]
if np.isnan(ybest):
ybest = ytest[ix]
else:
if ytest[ix] > ybest:
ybest = ytest[ix]
ix_evaled.append(ix)
ix_candidates.remove(ix)
ybest_list.append(ybest)
if do_print:
print('Iter: %d, %g [%d], Best: %g' % (l, ytest[ix], ix, ybest))
return np.asarray(ybest_list)
if __name__=='__main__':
# train and evaluation settings
Q = 20
batch_size = 50
n_epochs = 300
lr = 1e-7
N_max = 1000
bo_n_init = 5
bo_n_iters = 200
save_checkpoint = False
fn_checkpoint = None
checkpoint_period = 50
# train
Ytrain, Ytest, Ftrain, Ftest = get_data()
maxiter = int(Ytrain.shape[1]/batch_size*n_epochs)
def f_stop(m, v, it, t):
if it >= maxiter-1:
print('maxiter (%d) reached' % maxiter)
return True
return False
varn_list = []
logpr_list = []
t_list = []
def f_callback(m, v, it, t):
varn_list.append(transform_forward(m.variance).item())
logpr_list.append(m().item()/m.D)
if it == 1:
t_list.append(t)
else:
t_list.append(t_list[-1] + t)
if save_checkpoint and not (it % checkpoint_period):
torch.save(m.state_dict(), fn_checkpoint + '_it%d.pt' % it)
print('it=%d, f=%g, varn=%g, t: %g'
% (it, logpr_list[-1], transform_forward(m.variance), t_list[-1]))
# create initial latent space with PCA, first imputing missing observations
imp = sklearn.impute.SimpleImputer(missing_values=np.nan, strategy='mean')
X = sklearn.decomposition.PCA(Q).fit_transform(
imp.fit(Ytrain).transform(Ytrain))
# define model
kernel = kernels.Add(kernels.RBF(Q, lengthscale=None), kernels.White(Q))
m = gplvm.GPLVM(Q, X, Ytrain, kernel, N_max=N_max, D_max=batch_size)
if save_checkpoint:
torch.save(m.state_dict(), fn_checkpoint + '_it%d.pt' % 0)
# optimize
print('training...')
optimizer = torch.optim.SGD(m.parameters(), lr=lr)
m = train(m, optimizer, f_callback=f_callback, f_stop=f_stop)
if save_checkpoint:
torch.save(m.state_dict(), fn_checkpoint + '_itFinal.pt')
# evaluate model and random baselines
print('evaluating...')
with torch.no_grad():
Ytest = Ytest.astype(np.float32)
regrets_automl = np.zeros((bo_n_iters, Ytest.shape[1]))
regrets_random1x = np.zeros((bo_n_iters, Ytest.shape[1]))
regrets_random2x = np.zeros((bo_n_iters, Ytest.shape[1]))
regrets_random4x = np.zeros((bo_n_iters, Ytest.shape[1]))
for d in np.arange(Ytest.shape[1]):
print(d)
ybest = np.nanmax(Ytest[:,d])
regrets_random1x[:,d] = ybest - random_search(bo_n_iters,
Ytest[:,d], speed=1)
regrets_random2x[:,d] = ybest - random_search(bo_n_iters,
Ytest[:,d], speed=2)
regrets_random4x[:,d] = ybest - random_search(bo_n_iters,
Ytest[:,d], speed=4)
regrets_automl[:,d] = ybest - bo_search(m, bo_n_init, bo_n_iters,
Ytrain, Ftrain, Ftest[d,:],
Ytest[:,d])
results = {'pmf': regrets_automl,
'random1x': regrets_random1x,
'random2x': regrets_random2x,
'random4x': regrets_random4x,
}