-
Notifications
You must be signed in to change notification settings - Fork 0
/
bnn_sghmc.py
67 lines (56 loc) · 1.75 KB
/
bnn_sghmc.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
import numpy as np
import torch
import time
from pybnn.bohamiann import Bohamiann,predict_bnn
from sklearn.model_selection import KFold
from joblib import Parallel,delayed
from uq_metrics import metrics_ensemble
from data_utils import Dataset
class ExactBayesianMLPCV:
def __init__(
self,X:torch.Tensor,
y:torch.Tensor,
n_splits=5,
n_jobs=1
):
self.X = X
self.y = y
self.input_dim = X.shape[1]
self.rkf = KFold(n_splits=n_splits,shuffle=True)
self.n_jobs=n_jobs
def fit_and_test(
self,
train_index,test_index,
):
model_bnn = Bohamiann(
normalize_input=False,
normalize_output=False,
use_double_precision=False,
print_every_n_steps=1000
)
start_time = time.time()
model_bnn.train(
self.X[train_index,:].numpy(),self.y[train_index].numpy(),
num_steps=12000,
num_burn_in_steps=2000,
keep_every=200,
lr=0.05,
verbose=False,
batch_size=100
)
training_time = time.time()-start_time
predictions = predict_bnn(model_bnn,self.X[test_index,:].numpy())
y_mean = predictions[:,:,0]
y_std = predictions[:,:,1].exp().sqrt()
metrics = metrics_ensemble(self.y[test_index],y_mean,y_std,0.05)
metrics['training_time'] = training_time
return metrics
def cvloss(self,cv=None):
if cv is None:
cv = self.rkf
scores = Parallel(n_jobs=self.n_jobs)(
delayed(self.fit_and_test)(
train_index,test_index,
) for train_index,test_index in cv.split(self.X)
)
return scores