/
models.py
289 lines (206 loc) · 10.8 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
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
import numpy as np
from layers import Linear_BBB, Conv_BBB
class Classifier_BBB(nn.Module):
def __init__(self, in_dim, hidden_dim, out_dim, prior_var, prior_type, imsize):
super().__init__()
self.h1 = Linear_BBB(in_dim, hidden_dim, prior_var, prior_type= prior_type)
self.h2 = Linear_BBB(hidden_dim, hidden_dim, prior_var, prior_type= prior_type)
self.out = Linear_BBB(hidden_dim, out_dim, prior_var, prior_type= prior_type)
self.imsize = imsize
self.out_dim = out_dim
def forward(self, x, logit= False):
x = x.view(-1, self.imsize*self.imsize)
x = torch.relu(self.h1(x))
x = torch.relu(self.h2(x))
x = self.out(x)
logits = x
x = F.log_softmax(x ,dim=1)
if(logit == True):
return x, logits
else:
return x
return x
def log_prior(self):
return self.h1.log_prior + self.h2.log_prior + self.out.log_prior
def log_post(self):
return self.h1.log_post + self.h2.log_post + self.out.log_post
def log_like(self,outputs,target, reduction):
#log P(D|w)
return F.nll_loss(outputs, target, reduction=reduction)
# avg cost function over no. of samples = {1, 2, 5, 10}
def sample_elbo(self, input, target, samples, batch, num_batches, samples_batch, T=1.0, burnin=None, reduction = "sum", logit=False):
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
outputs = torch.zeros(samples, target.shape[0], self.out_dim).to(self.device)
log_priors = torch.zeros(samples).to(self.device)
log_posts = torch.zeros(samples).to(self.device)
log_likes = torch.zeros(samples).to(self.device)
for i in range(samples):
if(logit == True):
outputs[i], logits = self(input, logit = True)
else:
outputs[i] = self(input, logit = False)
log_priors[i] = self.log_prior()
log_posts[i] = self.log_post()
log_likes[i] = self.log_like(outputs[i,:,:], target, reduction)
# the mean of a sum is the sum of the means:
log_prior = log_priors.mean()
log_post = log_posts.mean()
log_like = log_likes.mean()
if burnin=="blundell":
frac = 2**(num_batches - (batch + 1))/2**(num_batches - 1)
elif burnin==None:
if reduction == "sum":
frac = T/(num_batches) # 1./num_batches #
elif reduction == "mean":
frac = T/(num_batches*samples_batch)
else:
pass
complexity_cost = frac*(log_post - log_prior)
loss = complexity_cost + log_like #or likelihood_cost
if(logit==True):
return loss, outputs, complexity_cost, log_like, logits
else:
return loss, outputs, complexity_cost, log_like
class Classifier_ConvBBB(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size, prior_var, prior_type):
super().__init__()
z = 0.5*(150 +1 - 2)
z = int(0.5*(z - 2))
self.conv1 = Conv_BBB(in_ch, 6, kernel_size, stride=1, padding = 1, prior_var = prior_var, prior_type=prior_type)
self.conv2 = Conv_BBB(6, 16, kernel_size, stride=1, padding = 1, prior_var = prior_var, prior_type=prior_type)
self.conv3 = Conv_BBB(16, 26, kernel_size, stride=1, padding = 1, prior_var = prior_var, prior_type=prior_type)
self.conv4 = Conv_BBB(26, 32, kernel_size, stride=1, padding = 1, prior_var = prior_var, prior_type=prior_type)
self.h1 = Linear_BBB(7*7*32, 120, prior_var, prior_type)# --
self.h2 = Linear_BBB(120, 84, prior_var, prior_type)
self.out = Linear_BBB(84, out_ch, prior_var, prior_type)
self.out_dim = out_ch
def forward(self, x, logit= False):
x = torch.relu(self.conv1(x))
x = torch.max_pool2d(x, 2)
x = torch.relu(self.conv2(x))
x = torch.max_pool2d(x, 2)
x = torch.relu(self.conv3(x))
x = torch.max_pool2d(x, 2)
x = torch.relu(self.conv4(x))
x = torch.max_pool2d(x, 2)
#print(x.shape)
x = x.view(-1, 7*7*32)
x = torch.relu(self.h1(x))
x = torch.relu(self.h2(x))
x = self.out(x)
logits = x
x = F.log_softmax(x ,dim=1)
if(logit == True):
return x, logits
else:
return x
def log_prior(self):
conv_layers = self.conv1.log_prior + self.conv2.log_prior + self.conv3.log_prior + self.conv4.log_prior
linear_layers = self.h1.log_prior + self.h2.log_prior + self.out.log_prior
return conv_layers, linear_layers
def log_post(self):
conv_layers = self.conv1.log_post + self.conv2.log_post + self.conv3.log_post +self.conv4.log_post
linear_layers = self.h1.log_post + self.h2.log_post + self.out.log_post
return conv_layers, linear_layers
def log_like(self,outputs,target, reduction):
#log P(D|w)
return F.nll_loss(outputs, target, reduction=reduction)
def posterior_samples(self, n_samples, n_params, log_space):
samples = np.zeros((n_params,n_samples))
if(log_space == True):
for j in range(n_params):
for i in range(n_samples):
samples[j][i] = self.out.log_prior
else:
for j in range(n_params):
for i in range(n_samples):
samples[j][i] = self.out.w_post.sample()[0][j]
return samples
# avg cost function over no. of samples = {1, 2, 5, 10}
def sample_elbo(self, input, target, samples, batch, num_batches, samples_batch, T=1.0, burnin=None, reduction = "sum", logit= False, pac = False):
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
outputs = torch.zeros(samples, target.shape[0], self.out_dim).to(self.device)
#pac
if(pac == True):
outputs1 = torch.zeros(samples, target.shape[0], self.out_dim).to(self.device)
log_priors_conv = torch.zeros(samples).to(self.device)
log_priors_linear = torch.zeros(samples).to(self.device)
log_priors = torch.zeros(samples).to(self.device)
log_posts_conv = torch.zeros(samples).to(self.device)
log_posts_linear = torch.zeros(samples).to(self.device)
log_posts = torch.zeros(samples).to(self.device)
log_likes = torch.zeros(samples).to(self.device)
#pac
if(pac == True):
log_likes_1 = torch.zeros(samples).to(self.device)
for i in range(samples):
if(logit == True):
outputs[i], logits = self(input, logit = True)
else:
outputs[i] = self(input.to(self.device), logit = False)
#pac
if(pac == True):
outputs1[i] = self(input, logit=False)
log_priors_conv[i],log_priors_linear[i] = self.log_prior()
log_priors[i] = log_priors_conv[i] + log_priors_linear[i]
log_posts_conv[i], log_posts_linear[i] = self.log_post()
log_posts[i] = log_posts_conv[i] + log_posts_linear[i]
log_likes[i] = self.log_like(outputs[i,:,:], target, reduction)
#pac
if(pac == True):
log_likes_1[i] = self.log_like(outputs1[i,:,:], target, reduction)
# the mean of a sum is the sum of the means:
log_prior = log_priors.mean()
log_post = log_posts.mean()
log_like = log_likes.mean()
#pac
if(pac == True):
log_like_1 = log_likes_1.mean()
log_prior_conv = log_priors_conv.mean()
log_prior_linear = log_priors_linear.mean()
log_post_conv = log_posts_conv.mean()
log_post_linear = log_posts_linear.mean()
#print(self.out.w_post.sample())
if burnin=="blundell":
frac = 2**(num_batches - (batch + 1))/(2**(num_batches) - 1)
elif burnin==None:
if reduction == "sum":
frac = T/num_batches
elif reduction == "mean":
frac = T/(num_batches*samples_batch)
else:
pass
loss = frac*(log_post - log_prior) + log_like
complexity_cost = frac*(log_post - log_prior)
likelihood_cost = log_like
#uncomment for pac
if(pac == True and self.training == True):
#print("training")
variance=[]
#replacing all tensors with np arrays
for i in range(len(target)):
prob = -F.nll_loss(outputs[0,:,:][i].reshape(1,2), target[i].reshape(1), reduction=reduction).detach().numpy()
#print(prob)
prob1 = -F.nll_loss(outputs1[0,:,:][i].reshape(1,2), target[i].reshape(1), reduction=reduction).detach().numpy()
max_prob = np.maximum(prob, prob1)
#alpha = np.log(np.exp(prob - max_prob) +np.exp(prob1 - max_prob)) - np.log(2)
#h_alpha = alpha/(1-np.exp(alpha))**2 + 1/(np.exp(alpha)*(1-np.exp(alpha)))
var = np.exp(2*prob - 2*max_prob) - np.exp(prob + prob1 - 2*max_prob)
#print(var)
#print("halpha*var", (h_alpha*var))
variance = np.append(variance, var)
loss = complexity_cost + log_like - np.sum((variance))
#loss = complexity_cost + log_like - np.sum(h_alpha*variance)
#print("loss after var term", loss)
else:
pass
complexity_conv = frac*(log_post_conv - log_prior_conv)
complexity_linear = frac*(log_post_linear - log_prior_linear)
if(logit==True):
return loss, outputs, complexity_cost, likelihood_cost, complexity_conv, complexity_linear, logits
else:
return loss, outputs, complexity_cost, likelihood_cost, complexity_conv, complexity_linear