-
Notifications
You must be signed in to change notification settings - Fork 20
/
mixed_tanimoto_gp.py
323 lines (290 loc) · 11.7 KB
/
mixed_tanimoto_gp.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
from functools import partial
from typing import Callable, Dict, List, Optional
import pandas as pd
import torch
from botorch.fit import fit_gpytorch_mll
from botorch.models.gp_regression import SingleTaskGP
from botorch.models.kernels.categorical import CategoricalKernel
from botorch.models.transforms.input import (
ChainedInputTransform,
InputTransform,
OneHotToNumeric,
)
from botorch.models.transforms.outcome import OutcomeTransform, Standardize
from botorch.utils.transforms import normalize_indices
from gpytorch.constraints import GreaterThan
from gpytorch.kernels.kernel import Kernel
from gpytorch.kernels.matern_kernel import MaternKernel
from gpytorch.kernels.scale_kernel import ScaleKernel
from gpytorch.likelihoods.gaussian_likelihood import GaussianLikelihood
from gpytorch.likelihoods.likelihood import Likelihood
from gpytorch.mlls import ExactMarginalLogLikelihood
from gpytorch.priors import GammaPrior
from torch import Tensor
import bofire.kernels.api as kernels
import bofire.priors.api as priors
from bofire.data_models.enum import (
OutputFilteringEnum,
)
from bofire.data_models.surrogates.api import MixedTanimotoGPSurrogate as DataModel
# from bofire.data_models.kernels.categorical import HammingDistanceKernel
from bofire.surrogates.botorch import BotorchSurrogate
from bofire.surrogates.trainable import TrainableSurrogate
from bofire.surrogates.utils import (
get_categorical_feature_keys,
get_continuous_feature_keys,
get_molecular_feature_keys,
get_scaler,
)
from bofire.utils.torch_tools import tkwargs
class MixedTanimotoGP(SingleTaskGP):
def __init__(
self,
train_X: Tensor,
train_Y: Tensor,
mol_dims: List[int],
mol_kernel_factory: Callable[[torch.Size, int, List[int]], Kernel],
cat_dims: Optional[List[int]] = None,
# cat_kernel_factory: Optional[
# Callable[[torch.Size, int, List[int]], Kernel]
# ] = None, --> BoTorch forced to use CategoricalKernel
cont_kernel_factory: Optional[ # type: ignore
Callable[[torch.Size, int, List[int]], Kernel]
] = None,
likelihood: Optional[Likelihood] = None,
outcome_transform: Optional[OutcomeTransform] = None,
input_transform: Optional[InputTransform] = None,
) -> None:
if len(mol_dims) == 0:
raise ValueError("Must specify molecular dimensions for MixedTanimotoGP")
cat_dims = cat_dims or []
self._ignore_X_dims_scaling_check = cat_dims
_, aug_batch_shape = self.get_batch_dimensions(train_X=train_X, train_Y=train_Y)
d = train_X.shape[-1]
mol_dims = normalize_indices(indices=mol_dims, d=d)
cat_dims = normalize_indices(indices=cat_dims, d=d)
ord_dims = sorted(set(range(d)) - set(cat_dims) - set(mol_dims)) # type: ignore
if cont_kernel_factory is None:
def cont_kernel_factory(
batch_shape: torch.Size,
ard_num_dims: int,
active_dims: List[int],
) -> MaternKernel:
return MaternKernel(
nu=2.5,
batch_shape=batch_shape,
ard_num_dims=ard_num_dims,
active_dims=active_dims,
lengthscale_constraint=GreaterThan(1e-04),
)
if likelihood is None:
min_noise = 1e-5 if train_X.dtype == torch.float else 1e-6
likelihood = GaussianLikelihood(
batch_shape=aug_batch_shape,
noise_constraint=GreaterThan(
min_noise, transform=None, initial_value=1e-3
),
noise_prior=GammaPrior(0.9, 10.0),
)
if len(ord_dims) == 0:
sum_kernel = ScaleKernel(
CategoricalKernel(
batch_shape=aug_batch_shape,
ard_num_dims=len(cat_dims), # type: ignore
active_dims=cat_dims,
lengthscale_constraint=GreaterThan(1e-06),
)
) + ScaleKernel(
mol_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(mol_dims),
active_dims=mol_dims,
)
)
prod_kernel = ScaleKernel(
CategoricalKernel(
batch_shape=aug_batch_shape,
ard_num_dims=len(cat_dims), # type: ignore
active_dims=cat_dims,
lengthscale_constraint=GreaterThan(1e-06),
)
) * ScaleKernel(
mol_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(mol_dims),
active_dims=mol_dims,
)
)
covar_module = sum_kernel + prod_kernel
elif len(cat_dims) == 0: # type: ignore
sum_kernel = ScaleKernel(
cont_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(ord_dims),
active_dims=ord_dims,
)
) + ScaleKernel(
mol_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(mol_dims),
active_dims=mol_dims,
)
)
prod_kernel = ScaleKernel(
cont_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(ord_dims),
active_dims=ord_dims,
)
) * ScaleKernel(
mol_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(mol_dims),
active_dims=mol_dims,
)
)
covar_module = sum_kernel + prod_kernel
else:
sum_kernel = (
ScaleKernel(
cont_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(ord_dims),
active_dims=ord_dims,
)
)
+ ScaleKernel(
mol_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(mol_dims),
active_dims=mol_dims,
)
)
+ ScaleKernel(
CategoricalKernel(
batch_shape=aug_batch_shape,
ard_num_dims=len(cat_dims), # type: ignore
active_dims=cat_dims,
lengthscale_constraint=GreaterThan(1e-06),
)
)
)
prod_kernel = (
ScaleKernel(
cont_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(ord_dims),
active_dims=ord_dims,
)
)
* ScaleKernel(
mol_kernel_factory(
batch_shape=aug_batch_shape, # type: ignore
ard_num_dims=len(mol_dims),
active_dims=mol_dims,
)
)
* ScaleKernel(
CategoricalKernel(
batch_shape=aug_batch_shape,
ard_num_dims=len(cat_dims), # type: ignore
active_dims=cat_dims,
lengthscale_constraint=GreaterThan(1e-06),
)
)
)
covar_module = sum_kernel + prod_kernel
super().__init__(
train_X=train_X,
train_Y=train_Y,
likelihood=likelihood,
covar_module=covar_module,
outcome_transform=outcome_transform,
input_transform=input_transform,
)
class MixedTanimotoGPSurrogate(BotorchSurrogate, TrainableSurrogate):
def __init__(
self,
data_model: DataModel,
**kwargs,
):
self.continuous_kernel = data_model.continuous_kernel
self.categorical_kernel = data_model.categorical_kernel
self.molecular_kernel = data_model.molecular_kernel
self.scaler = data_model.scaler
self.noise_prior = data_model.noise_prior
super().__init__(data_model=data_model, **kwargs)
model: Optional[MixedTanimotoGP] = None
_output_filtering: OutputFilteringEnum = OutputFilteringEnum.ALL
training_specs: Dict = {}
def _fit(self, X: pd.DataFrame, Y: pd.DataFrame):
molecular_feature_keys = get_molecular_feature_keys(
self.input_preprocessing_specs
)
continuous_feature_keys = get_continuous_feature_keys(
self.inputs, self.input_preprocessing_specs
)
categorical_feature_keys = get_categorical_feature_keys(
self.input_preprocessing_specs
)
mol_dims = self.inputs.get_feature_indices(
self.input_preprocessing_specs, molecular_feature_keys
)
ord_dims = self.inputs.get_feature_indices(
self.input_preprocessing_specs, continuous_feature_keys
)
# these are the categorical dimesions after applying the OneHotToNumeric transform
cat_dims = list(
range(
len(ord_dims) + len(mol_dims),
len(ord_dims) + len(mol_dims) + len(categorical_feature_keys),
)
)
if len(continuous_feature_keys) == 0:
scaler = None # skip the scaler
else:
scaler = get_scaler(
self.inputs, self.input_preprocessing_specs, self.scaler, X
)
transformed_X = self.inputs.transform(X, self.input_preprocessing_specs)
tX, tY = torch.from_numpy(transformed_X.values).to(**tkwargs), torch.from_numpy(
Y.values
).to(**tkwargs)
if len(categorical_feature_keys) == 0:
tf = scaler
tXX = tX
else:
features2idx, _ = self.inputs._get_transform_info(
self.input_preprocessing_specs
)
# these are the categorical features within the OneHotToNumeric transform
categorical_features = {
features2idx[feat][0]: len(features2idx[feat])
for feat in categorical_feature_keys
}
o2n = OneHotToNumeric(
dim=tX.shape[1],
categorical_features=categorical_features,
transform_on_train=False,
)
tf = (
ChainedInputTransform(tf1=scaler, tf2=o2n)
if scaler is not None
else o2n
)
tXX = o2n.transform(tX)
# fit the model
self.model = MixedTanimotoGP(
train_X=tXX,
train_Y=tY,
cat_dims=cat_dims,
mol_dims=mol_dims,
cont_kernel_factory=partial(kernels.map, data_model=self.continuous_kernel),
# cat_kernel_factory=partial(kernels.map, data_model=self.categorical_kernel), BoTorch forced to use CategoricalKernel
mol_kernel_factory=partial(kernels.map, data_model=self.molecular_kernel),
outcome_transform=Standardize(m=tY.shape[-1]),
input_transform=tf,
)
self.model.likelihood.noise_covar.noise_prior = priors.map(self.noise_prior) # type: ignore
mll = ExactMarginalLogLikelihood(self.model.likelihood, self.model)
fit_gpytorch_mll(mll, options=self.training_specs, max_attempts=10)