-
Notifications
You must be signed in to change notification settings - Fork 5
/
bnn_vi.py
176 lines (140 loc) · 6.4 KB
/
bnn_vi.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
import torch
import os
import math
import numpy as np
import sys
sys.path.append('..')
from zhusuan.framework.bn import BayesianNet
from zhusuan.variational.elbo import ELBO
from examples.utils import load_uci_boston_housing, standardize
class Net(BayesianNet):
def __init__(self, layer_sizes, n_particles):
super().__init__()
self.layer_sizes = layer_sizes
self.n_particles = n_particles
self.y_logstd = torch.nn.parameter.Parameter(
torch.nn.init.constant_(torch.empty([1], dtype=torch.float32), 0.0), requires_grad=True)
def forward(self, observed):
self.observe(observed)
x = self.observed['x']
h = x.repeat([self.n_particles, *len(x.shape) * [1]])
batch_size = x.shape[0]
for i, (n_in, n_out) in enumerate(zip(self.layer_sizes[:-1], self.layer_sizes[1:])):
w = self.normal(
name='w' + str(i),
mean=torch.zeros([n_out, n_in + 1]),
std=torch.ones([n_out, n_in + 1]),
group_ndims=2,
n_samples=self.n_particles,
reduce_mean_dims=[0])
w = torch.unsqueeze(w, 1)
w = w.repeat([1, batch_size, 1, 1])
h = torch.cat((h, torch.ones([*h.shape[:-1], 1]).to(self.device)), -1)
h = torch.unsqueeze(h, -1)
p = torch.sqrt(torch.as_tensor(h.shape[2], dtype=torch.float32))
h = torch.matmul(w, h) / p
h = torch.squeeze(h, -1)
if i < len(self.layer_sizes) - 2:
h = torch.nn.ReLU()(h)
y_mean = torch.squeeze(h, 2)
y = self.observed['y']
y_pred = torch.mean(y_mean, 0)
self.cache['rmse'] = torch.sqrt(torch.mean((y - y_pred) ** 2))
self.normal(name='y',
mean=y_mean,
logstd=self.y_logstd,
reparameterize=True,
reduce_mean_dims=[0, 1],
multiplier=456) # training data size
return self
class Variational(BayesianNet):
def __init__(self, layer_sizes, n_particles):
super().__init__()
self.layer_sizes = layer_sizes
self.n_particles = n_particles
self.w_means = []
self.w_logstds = []
for i, (n_in, n_out) in enumerate(zip(self.layer_sizes[:-1], self.layer_sizes[1:])):
w_mean = torch.nn.init.constant_(torch.empty([n_out, n_in + 1], dtype=torch.float32), 0)
_name = 'w_mean_' + str(i)
self.__dict__[_name] = w_mean
w_logstd = torch.nn.init.constant_(torch.empty([n_out, n_in + 1], dtype=torch.float32), 0)
_name = 'w_logstd_' + str(i)
self.__dict__[_name] = w_logstd
w_mean = torch.nn.parameter.Parameter(w_mean, requires_grad=True)
w_logstd = torch.nn.parameter.Parameter(w_logstd, requires_grad=True)
self.w_means.append(w_mean)
self.w_logstds.append(w_logstd)
self.w_means = torch.nn.ParameterList(self.w_means)
self.w_logstds = torch.nn.ParameterList(self.w_logstds)
def forward(self, observed):
self.observe(observed)
for i, (n_in, n_out) in enumerate(zip(self.layer_sizes[:-1], self.layer_sizes[1:])):
self.normal(
name='w' + str(i),
mean=self.w_means[i],
logstd=self.w_logstds[i],
group_ndims=2,
n_samples=self.n_particles,
reparameterize=True,
reduce_mean_dims=[0])
return self
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
data_path = os.path.join('data', 'housing.data')
x_train, y_train, x_valid, y_valid, x_test, y_test = load_uci_boston_housing(data_path)
x_train = np.vstack([x_train, x_valid])
y_train = np.hstack([y_train, y_valid])
n_train, x_dim = x_train.shape
x_train, x_test, _, _ = standardize(x_train, x_test)
y_train, y_test, mean_y_train, std_y_train = standardize(y_train, y_test)
print('data size:', len(x_train))
lb_samples = 512
epoch_size = 5000
batch_size = 114
n_hiddens = [50]
layer_sizes = [x_dim] + n_hiddens + [1]
print('layer size:', layer_sizes)
net = Net(layer_sizes, lb_samples)
variational = Variational(layer_sizes, lb_samples)
model = ELBO(net, variational)
model.to(device)
x_train = torch.as_tensor(x_train).to(device)
y_train = torch.as_tensor(y_train).to(device)
x_test = torch.as_tensor(x_test).to(device)
y_test = torch.as_tensor(y_test).to(device)
lr = 0.001
optimizer = torch.optim.Adam(model.parameters(), lr)
len_ = len(x_train)
num_batches = math.floor(len_ / batch_size)
test_freq = 20
for epoch in range(epoch_size):
perm = np.random.permutation(x_train.shape[0])
x_train = x_train[perm, :]
y_train = y_train[perm]
for step in range(num_batches):
x = x_train[step * batch_size:(step + 1) * batch_size]
y = y_train[step * batch_size:(step + 1) * batch_size]
lbs = model({'x': x, 'y': y})
optimizer.zero_grad()
lbs.backward()
optimizer.step()
if (step + 1) % num_batches == 0:
rmse = net.cache['rmse'].clone().cpu().detach().numpy()
print("Epoch[{}/{}], Step [{}/{}], Lower bound: {:.4f}, RMSE: {:.4f}".format(epoch + 1, epoch_size,
step + 1,
num_batches,
float(
lbs.clone().cpu().detach().numpy()),
float(rmse) * std_y_train))
# eval
if epoch % test_freq == 0:
x_t = x_test
y_t = y_test
lbs = model({'x': x_t, 'y': y_t})
rmse = net.cache['rmse'].clone().cpu().detach().numpy()
print('>> TEST')
print('>> Test Lower bound: {:.4f}, RMSE: {:.4f}'.format(float(lbs.clone().cpu().detach().numpy()),
float(rmse) * std_y_train))
if __name__ == '__main__':
main()