-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
291 lines (249 loc) · 10.1 KB
/
models.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
from typing import Tuple, List, Optional, Dict
import ipdb
import numpy as np
import torch
from torch import Tensor
from torch import nn
from tqdm import tqdm, trange
from catboost import CatBoostRegressor
from gpytorch.likelihoods import GaussianLikelihood
from models_gp import GPARDModel, GPLaplaceMahalanobisModel, GPMahalanobisARDFullModel, GPDeepKLModel, train_gp, predict_gp
from ngboost import NGBRegressor
from utils import Preprocessing
from recursive_feature_machine import LaplaceRFM
class ModelGeneric(nn.Module):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(ModelGeneric, self).__init__()
self.config = config
self.device = device
self.verbose = verbose
# define preprocessing
self.preprocessing = Preprocessing(config, device)
X_train, y_train, X_test, y_test = self.preprocessing.preprocess(*data_train, *data_test)
self.X_train = X_train
self.y_train = y_train
self.X_test = X_test
self.y_test = y_test
self.likelihood = None
self.model = None
self.weight_matrix = None
self.def_model()
def def_model(self):
raise NotImplementedError
def preprocessed_data(self):
return self.X_train, self.y_train, self.X_test, self.y_test
def postprocess_data(self, y_mean: Tensor, y_std: Tensor,
y_test: Tensor, y_train: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
return self.preprocessing.postprocess(y_mean, y_std, y_test, y_train)
def fit(self, X: Tensor, y: Tensor, desc: str = "Training") -> None:
raise NotImplementedError
def predict(self, X: Tensor) -> Tuple[Tensor, Tensor]:
raise NotImplementedError
class GPGeneric(ModelGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(GPGeneric, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
# define GP
self.likelihood = GaussianLikelihood().to(self.device)
self.model = GPARDModel(
self.X_train, self.y_train,
self.likelihood,
ard_num_dims=self.config["ard_num_dims"]
).to(self.device)
def fit(self, X: Tensor, y: Tensor, desc: str = "Training") -> None:
self.model, self.likelihood = train_gp(
X, y,
self.model, self.likelihood,
num_iter=self.config["n_iter"],
lr=self.config["lr"],
desc=desc,
verbose=self.verbose,
)
def predict(self, X: Tensor) -> Tuple[Tensor, Tensor]:
y_mean, y_std = predict_gp(X, self.model, self.likelihood)
return y_mean, y_std
class GPRBF(GPGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(GPRBF, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
# define GP
self.likelihood = GaussianLikelihood().to(self.device)
self.model = GPARDModel(
self.X_train, self.y_train,
self.likelihood,
ard_num_dims=self.config["ard_num_dims"]
).to(self.device)
class GPLaplace(GPGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(GPLaplace, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
# define GP
self.likelihood = GaussianLikelihood().to(self.device)
self.model = GPLaplaceMahalanobisModel(
self.X_train, self.y_train,
self.likelihood,
ard_num_dims=self.config["ard_num_dims"]
).to(self.device)
class GPLaplaceARDFull(GPGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(GPLaplaceARDFull, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
# define GP
self.likelihood = GaussianLikelihood().to(self.device)
self.model = GPMahalanobisARDFullModel(
self.X_train, self.y_train,
self.likelihood,
ard_num_dims=1,
squared=False,
).to(self.device)
class GPDeepKL(GPGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(GPDeepKL, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
# define GP
self.likelihood = GaussianLikelihood().to(self.device)
self.model = GPDeepKLModel(
self.X_train, self.y_train,
self.likelihood,
).to(self.device)
class GPRFMLaplace(GPGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
diag: Optional[bool] = False,
):
self.diag = diag
super(GPRFMLaplace, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self, weight_matrix=None):
# define RFM
rfm = LaplaceRFM(
mem_gb=38, # 38 GB, 2 GB for other stuff
bandwidth=1,
device=self.device,
reg=self.config["rfm_reg"],
ridge=self.config["rfm_ridge"],
verbose=False,
diag=self.diag,
centering=True,
)
# fit RFM
rfm.fit(
(self.X_train, self.y_train), (self.X_test, self.y_test),
loader=False,
iters=self.config["rfm_n_iter"],
classif=False,
)
# weight matrix
if weight_matrix is None:
self.weight_matrix = rfm.M if not self.diag else torch.diag(rfm.M)
else:
self.weight_matrix = weight_matrix
# define GP
self.likelihood = GaussianLikelihood().to(self.device)
self.model = GPLaplaceMahalanobisModel(
self.X_train, self.y_train,
self.likelihood,
# diag=self.diag,
weight_matrix=self.weight_matrix,
ard_num_dims=1
).to(self.device)
del rfm
torch.cuda.empty_cache()
class NGBoost(ModelGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(NGBoost, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
self.model = NGBRegressor(
natural_gradient=True,
n_estimators=self.config["n_estimators"],
minibatch_frac=1.0,
verbose=False,
random_state=self.config["seed"],
)
def fit(self, X: Tensor, y: Tensor, desc: str = "Training") -> None:
tqdm.write(desc) if self.verbose else None
self.model.fit(X, y)
def predict(self, X: Tensor) -> Tuple[Tensor, Tensor]:
y_dists = self.model.pred_dist(X)
y_mean, y_std = y_dists.loc, y_dists.scale
return y_mean, y_std
class CatBoostEnsemble(ModelGeneric):
def __init__(self,
data_train: Tuple[Tensor, Tensor],
data_test: Tuple[Tensor, Tensor],
config: Dict,
device: torch.device = torch.device("cpu"),
verbose: Optional[bool] = False,
):
super(CatBoostEnsemble, self).__init__(data_train, data_test, config, device, verbose)
def def_model(self):
self.model = []
for i in range(self.config["n_ensembles"]):
self.model.append(CatBoostRegressor(
random_seed=self.config["seed"] + i,
iterations=self.config["n_iter"],
learning_rate=self.config["lr"],
depth=self.config["depth"],
loss_function='RMSEWithUncertainty',
posterior_sampling=True,
bootstrap_type='No',
verbose=False,
# task_type=task_type, # posterior_sampling is unimplemented for task type GPU
))
def fit(self, X: Tensor, y: Tensor, desc: str = "Training") -> None:
for i in trange(self.config["n_ensembles"], desc=desc, disable=not self.verbose):
self.model[i].fit(X, y)
def predict(self, X: Tensor) -> Tuple[Tensor, Tensor]:
ens_preds = np.zeros((self.config["n_ensembles"], X.shape[0], 2))
for i in range(self.config["n_ensembles"]):
ens_preds[i] = self.model[i].predict(X)
y_mean = ens_preds.mean(axis=0)[:, 0]
var_data = ens_preds.mean(axis=0)[:, 1]
var_knowledge = ens_preds.var(axis=0)[:, 0]
y_std = np.sqrt(var_data + var_knowledge) # total std
return y_mean, y_std