-
Notifications
You must be signed in to change notification settings - Fork 0
/
vRB3_beta.py
2348 lines (1921 loc) · 86.7 KB
/
vRB3_beta.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Bayes By Backprop - variational version
This module contains two deep nets (with the possibility to change their activation
function(s)): A Multi-Layer Perceptron, two (one-sided) Recurrent Neural Network
Here they are named:
Elang, Jordan or IIR Recurrent Bayes by Backprop
Multi-Layer Bayes by Backprop
The classes are:
MLP_BBB - multi-layer Bayes by Backprop
RNN_BBB - recurrent IIR-like layer
SRN_BBB - Elang / Jordan Bayes by backprop
The variational part:
In terms of variation we do sample similar than in a normal Bayesian Neural
Network (BNN).
But we also sample many parameter sets for each batch at each iteration and
select a smaller portion of those samples for actual inference.
One part of this selection are the Kopt maximum posterior samples and the other
part is drawn randomly from the rest.
We do sample randomly because of keeping a part of the variance into our
optimization step and thou avoid local optima.
TODO:
- !!! detaching the sampling / training from the particular networks !!!
-> more dynamic and less redundant code / classes
-> modularization: "put things together sequentially"
- evaluate samples with the single datapoint dimension
-> choosing the best sample for each data point per sample
- more optimization methods for sampling
@author(s): Markus Meister, ft. Josh Feldman (Feldman 12/17/2018)
@literature:
(Feldman 12/17/2018):
Title = Weight Uncertainty in Neural Networks Tutorial
Authors = Josh Feldman
Blog = Josh Feldman Blog - ml
Link = {https://joshfeldman.net/ml/2018/12/17/WeightUncertainty.html}
(Blundell et al 05/21/2015):
Tilte = Weight Uncertainty in Neural Networks
Authors = Charles Blundell CBLUNDELL@GOOGLE.COM,
Julien Cornebise JUCOR@GOOGLE.COM,
Koray Kavukcuoglu KORAYK@GOOGLE.COM,
Daan Wierstra WIERSTRA@GOOGLE.COM
Journal = stat.ML (in proceeding)
Link = {https://arxiv.org/pdf/1505.05424.pdf}
(Laumann 12/12/2018):
Title = Bayesian Convolutional Neural Networks with Bayes by Backprop
Authors = Felix Laumann
Blog = Neural Space
Link = {https://medium.com/neuralspace/bayesian-convolutional-neural-networks-with-bayes-by-backprop-c84dcaaf086e}
(Lipton et al 23/03/2019):
Title = Bayes by Backprop from scratch (NN, classification)
Authors = Zachary C. Lipton
Mu Li
Alex Smola
Sheng Zha
Aston Zhang
Joshua Z. Zhang
Eric Junyuan Xie
Kamyar Azizzadenesheli
Jean Kossaifi
Stephan Rabanser
Blog = Gluon MXNet Documentation (ft. Read the Docs)
Link = {https://gluon.mxnet.io/chapter18_variational-methods-and-uncertainty/bayes-by-backprop.html}
@imporvements:
- introduced variational sampling directly into the network
- select & sample based on K-max. posterior + random samples
@outlook:
- generative model version(s) (where update rules are defined by pretty math)
- a convolutional filter with any parametric function e.g. ADBUDGE
- other networks like this e.g. convolutional one (Laumann 12/12/2018)
"""
# %% -- imports --
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions \
import \
Normal, \
Poisson, \
Cauchy, \
Uniform, \
HalfCauchy, \
Exponential, \
Bernoulli, \
Binomial
import numpy as np
import warnings
import math
from SignalTorch import ConvT
cpi = torch.Tensor([math.pi])
# %% -- some function(s) --
def roll(x, n):
return torch.cat((x[-n:], x[:-n]))
def roll_mat(x,order,strafe=1):
Xe = torch.zeros(order,*x.shape)
for m in range(order):
Xe[m] = roll(x,m*strafe)
return Xe
# activation function parser
def act_fun(a):
if type(a) == type('a'):
try:
return eval('F.%s' %a)
except:
return None
else:
return a
def test_act_fun():
act_funs = [None, 'softmax', 'relu', '+235r+f2fl', F.relu6, None, 'sigmoid', F.softmin]
length_old = len(act_funs)
act_funs = list(map(lambda a: act_fun(a), act_funs))
length_new = len(act_funs)
assert length_old == length_new
assert act_funs[0] == None
assert act_funs[1] == F.softmax
assert act_funs[length_new-1] == F.softmin
assert act_funs[2] == F.relu
def parse_layer(layer):
if type(layer) == type(''):
try:
out = eval('LB3_'+layer.split('_')[-1].split('(')[0])
except Exception as e:
print('Error parsing layer:')
print(e)
print('Using normal distribution!')
out = LB3_Normal
return out
else:
return layer
def device_check(device):
# check if cuda is available iff cuda is the device
if device == 'cuda' and not torch.cuda.is_available():
warnings.warn('ERROR: CUDA not available! - Using CPU!!', RuntimeWarning)
device = 'cpu'
return device
def eval_prop(prop):
if 'method' in type(prop).__name__.split('_'):
return prop()
else:
return prop
################################
# %% -- standard linear B3 --
class LB3_Normal(nn.Module):
"""
Normal Layer of our Bayesian Neural Net.
implementation: (Feldman 12/17/2018)
theory and initial work: (Blundell et al 05/21/2015)
"""
def __init__(self,
input_features, output_features,
prior_var = 1.,
prior_pies = .5,
device='cuda',
use_bias=False,
dropout_flag = False,
):
"""
Initialization of our layer : our prior is a normal distribution
centered in 0 and of variance 1.
"""
# checking the device first to see if it is available
device = device_check(device)
# initialize layers
super().__init__()
# set input and output dimensions
self.input_features = input_features
self.output_features = output_features
# initialize mu and rho parameters for the weights of the layer
self.w_mu = nn.Parameter(torch.randn(input_features, output_features))
self.w_rho = nn.Parameter(torch.rand(input_features, output_features))
#initialize mu and rho parameters for the layer's bias
self.b_mu = nn.Parameter(torch.randn(output_features))
self.b_rho = nn.Parameter(torch.rand(output_features))
# initialize Bernoulli Dropout probabilities
if dropout_flag:
self.z_pies = nn.Parameter(torch.zeros(input_features))
# in case z willbe given in the forward call
self.dropout_prior = Bernoulli(torch.tensor(prior_pies).to(device))
#initialize weight samples (these will be calculated whenever the layer makes a prediction)
self.w = None
self.b = None
self.z = None
# initialize prior distribution for all of the weights and biases
self.prior = torch.distributions.Normal(0,prior_var)
# flags for later calculations
self.use_bias = use_bias
self.dropout_flag = dropout_flag
# this has to be the same device type, you sent the network to
self.device = device
self.to(self.device)
def log_like(self, o, y, noise_tol=0.1):
return Normal(o,noise_tol).log_prob(y)
def forward(
self, input,
w_epsilon = None, b_epsilon = None, z_epsilon = None,
sample_var = 1.0, n_sample = 1, z = None, z_pies = None,
):
"""
Optimization process
inputs:
- input .. a tensor batch of shape (N_batch x D_dim)
- sample_var .. variance to noisify the parameters artificially
- *_epsilon .. presamples from the 0-mean 1-var normal for reuse
outputs:
- a linear feed forward calculation using the sampled weights and biases
records:
- *_epsilon .. samples from the 0-mean 1-var normal for reuse
- *_log_prior .. log prior of the respective parameter
- *_log_post .. log posterior of the respective parameter
- log_prior .. overall sample log prior
- log_post .. overall sample log posterior
"""
if type(w_epsilon) != type(None):
S = w_epsilon.shape[0]
else:
S = 0
# input dimensions
D = self.input_features # input / batch dimension
H = self.output_features # output / hidden dimension
S = max(n_sample, S) # number of samples
# getting the standard deviation for annealing variance
sample_std = torch.sqrt(torch.tensor([sample_var])).to(self.device)
if self.dropout_flag:
if type(z_epsilon) == type(None):
self.z_epsilon = Uniform(0,1).sample((S, *self.z_pies.shape)).to(self.device)
else:
self.z_epsilon = z_epsilon.to(self.device)
# get Bernoulli for input space
self.z = (self.z_epsilon >= self.z_pies).float()
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z_pies).log_prob(self.z)
elif type(z) != type(None):
# use given z
self.z = z
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z_pies).log_prob(self.z)
else:
self.z = torch.ones((S,D)).to(self.device)
self.z_epsilon = torch.zeros((S,D)).to(self.device)
self.z_post = torch.zeros((S,D)).to(self.device)
z_log_prior = torch.zeros((S,D)).to(self.device)
if self.use_bias:
if type(b_epsilon) == type(None):
self.b_epsilon = Normal(0,1).sample((S, *self.b_mu.shape)).to(self.device)
else:
self.b_epsilon = b_epsilon.to(self.device)
# bias sample
self.b = self.b_mu + torch.log(1+torch.exp(self.b_rho)) * sample_std * self.b_epsilon
# bias prior
b_log_prior = self.prior.log_prob(self.b)
# bias posterior
self.b_post = Normal(self.b_mu.data, torch.log(1+torch.exp(self.b_rho))).log_prob(self.b)
else:
self.b = torch.zeros((S,H)).to(self.device)
self.b_epsilon = torch.zeros((S,H)).to(self.device)
self.b_post = torch.zeros((S,H)).to(self.device)
b_log_prior = torch.zeros((S,H)).to(self.device)
# sample weights noise if not given
if type(w_epsilon) == type(None):
self.w_epsilon = Normal(0,1).sample((S, *self.w_mu.shape)).to(self.device)
else:
self.w_epsilon = w_epsilon.to(self.device)
# calculate weights
self.w = self.w_mu + torch.log(1+torch.exp(self.w_rho)) * sample_std * self.w_epsilon
# dropout of weights
# (take only those weights into account whos input is chosen)
self.w = self.w * self.z[:,:,None]
# record log prior by evaluating log pdf of prior at sampled weight and bias
w_log_prior = self.prior.log_prob(self.w[self.z > 0])
# w posterior
self.w_post = Normal(self.w_mu.data, torch.log(1+torch.exp(self.w_rho))).log_prob(self.w)
# record log prior by evaluating log pdf of prior
self.log_prior = (
w_log_prior.sum(dim = [-1,-2]) / D / H +
b_log_prior.sum(dim = -1) / H +
z_log_prior.sum(dim = -1) / D
)
# record log variational posterior by evaluating log pdf of normal distribution defined by parameters with respect at the sampled values
self.log_post = (
self.w_post.sum(dim = [-1,-2]) / H / D +
self.b_post.sum(dim = -1) / H +
self.z_post.sum(dim = -1) / D
)
return input @ self.w + self.b[:,None]
#%% -- cauchy version --
class LB3_Cauchy(nn.Module):
"""
Cauchy Layer of our BNN.
implementation: (Feldman 12/17/2018)
theory and initial work: (Blundell et al 05/21/2015)
"""
def __init__(self,
input_features, output_features,
prior_var=1.,
prior_pies = .5,
device='cuda',
use_bias = False,
dropout_flag = False,
):
"""
Initialization of our layer : our prior is a normal distribution
centered in 0 and of variance 1.
"""
# checking the device first to see if it is available
device = device_check(device)
# initialize layers
super().__init__()
# set input and output dimensions
self.input_features = input_features
self.output_features = output_features
# initialize mu and rho parameters for the weights of the layer
self.w_mu = nn.Parameter(torch.randn(input_features, output_features))
self.w_rho = nn.Parameter(torch.rand(input_features, output_features))
#initialize mu and rho parameters for the layer's bias
self.b_rho = nn.Parameter(torch.rand(output_features))
self.b_mu = nn.Parameter(torch.randn(output_features))
# initialize Bernoulli Dropout probabilities
if dropout_flag:
self.z_pies = nn.Parameter(torch.rand(input_features))
# in case z willbe given in the forward call
self.dropout_prior = Bernoulli(torch.tensor(prior_pies).to(device))
#initialize weight samples (these will be calculated whenever the layer makes a prediction)
self.w = None
self.b = None
self.z = None
# initialize prior distribution for all of the weights and biases
self.prior = torch.distributions.Cauchy(0,prior_var)
# flags for later calculations
self.use_bias = use_bias
self.dropout_flag = dropout_flag
# this has to be the same device type, you sent the network to
self.device = device
self.to(self.device)
def log_like(self, o, y, noise_tol=0.1):
return Cauchy(o,noise_tol).log_prob(y)
def forward(
self, input,
w_epsilon = None, b_epsilon = None, z_epsilon = None,
sample_var = 1.0, n_sample = 1, z = None, z_pies = None,
):
"""
Optimization process
inputs:
- input .. a tensor batch of shape (N_batch x D_dim)
- sample_var .. variance to noisify the parameters artificially
- *_epsilon .. presamples from the 0-mean 1-var normal for reuse
outputs:
- a linear feed forward calculation using the sampled weights and biases
records:
- *_epsilon .. samples from the 0-mean 1-var normal for reuse
- *_log_prior .. log prior of the respective parameter
- *_log_post .. log posterior of the respective parameter
- log_prior .. overall sample log prior
- log_post .. overall sample log posterior
"""
if type(w_epsilon) != type(None):
S = w_epsilon.shape[0]
else:
S = 0
# input dimensions
D = self.input_features # input / batch dimension
H = self.output_features # output / hidden dimension
S = max(n_sample, S) # number of samples
# getting the standard deviation for annealing variance
sample_std = torch.sqrt(torch.tensor([sample_var])).to(self.device)
if self.dropout_flag:
if type(z_epsilon) == type(None):
self.z_epsilon = Uniform(0,1).sample((S, *self.z_pies.shape)).to(self.device)
else:
self.z_epsilon = z_epsilon.to(self.device)
# get Bernoulli for input space
self.z = (self.z_epsilon >= self.z_pies).to(self.device).float()
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z.pies).log_prob(self.z)
elif type(z) != type(None):
# use given z
self.z = z
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z_pies).log_prob(self.z)
else:
self.z = torch.ones((S,D)).to(self.device)
self.z_epsilon = torch.zeros((S,D)).to(self.device)
self.z_post = self.z_epsilon
z_log_prior = torch.zeros((S,D))
if self.use_bias:
if type(b_epsilon) == type(None):
self.b_epsilon = Uniform(0,1).sample((S, *self.b_mu.shape)).to(self.device)
else:
self.b_epsilon = b_epsilon.to(self.device)
# calculate bias with cauchy reparameterization
self.b = self.b_mu + torch.log(1+torch.exp(self.b_rho)) * sample_std * torch.tan(
math.pi * ( .5 + self.b_epsilon )
)
# bias prior
b_log_prior = self.prior.log_prob(self.b)
# bias posterior
self.b_post = Cauchy(self.b_mu.data, torch.log(1+torch.exp(self.b_rho))).log_prob(self.b)
else:
self.b = torch.zeros((S,H)).to(self.device)
self.b_epsilon = torch.zeros((S,H)).to(self.device)
self.b_post = torch.zeros((S,H)).to(self.device)
b_log_prior = torch.zeros((S,H)).to(self.device)
if type(w_epsilon) == type(None):
self.w_epsilon = Uniform(0,1).sample((S, *self.w_mu.shape)).to(self.device)
else:
self.w_epsilon = w_epsilon.to(self.device)
# calculate weights with cauchy reparameterization
self.w = self.w_mu + torch.log(1+torch.exp(self.w_rho)) * sample_std * torch.tan(
math.pi * ( .5 + self.w_epsilon )
)
# dropout of weights
# (take only those weights into account whos input is chosen)
self.w = self.w * self.z[:,:,None]
# weights prior
w_log_prior = self.prior.log_prob(self.w[self.z > 0])
# weights posterior
self.w_post = Cauchy(self.w_mu.data, torch.log(1+torch.exp(self.w_rho))).log_prob(self.w)
# record log prior by evaluating log pdf of prior
self.log_prior = \
w_log_prior.sum(dim = [-1,-2]) / self.z.sum(dim=-1) / H + \
b_log_prior.sum(dim = -1) / H + \
z_log_prior.sum(dim = -1) / D
# record log variational posterior by evaluating log pdf of normal distribution defined by parameters with respect at the sampled values
self.log_post = self.w_post.sum(dim = [-1,-2]) / H / D + \
self.b_post.sum(dim = -1) / H + \
self.z_post.sum(dim = -1) / D
return input @ self.w + self.b[:,None]
#%%
class LB3_HalfCauchy(nn.Module):
"""
Half Cauchy Layer of our Baysian Neural Net.
implementation: (Feldman 12/17/2018)
theory and initial work: (Blundell et al 05/21/2015)
"""
def __init__(self,
input_features, output_features,
prior_var=1.,
prior_pies=.5,
device='cuda',
use_bias = False,
dropout_flag = False,
):
"""
Initialization of our layer : our prior is a normal distribution
centered in 0 and of variance 1.
"""
# checking the device first to see if it is available
device = device_check(device)
# initialize layers
super().__init__()
# set input and output dimensions
self.input_features = input_features
self.output_features = output_features
# initialize mu and rho parameters for the weights of the layer
self.w_rho = nn.Parameter(torch.rand(input_features, output_features))
#initialize mu and rho parameters for the layer's bias
self.b_rho = nn.Parameter(torch.rand(output_features))
# initialize Bernoulli Dropout probabilities
if dropout_flag:
self.z_pies = nn.Parameter(torch.rand(input_features))
# in case z willbe given in the forward call
self.dropout_prior = Bernoulli(torch.tensor(prior_pies).to(device))
#initialize weight samples (these will be calculated whenever the layer makes a prediction)
self.w = None
self.b = None
self.z = None
# initialize prior distribution for all of the weights and biases
self.prior = HalfCauchy(prior_var)
# flags for later calculations
self.use_bias = use_bias
self.dropout_flag = dropout_flag
# this has to be the same device type, you sent the network to
self.device = device
self.to(self.device)
def log_like(self, o, y, noise_tol = 0.1 ):
return HalfCauchy(noise_tol).log_prob(y).mean()
def forward(
self, input,
w_epsilon = None, b_epsilon = None, z_epsilon = None,
sample_var = 1.0, n_sample = 1, z = None, z_pies = None,
):
"""
Optimization process
inputs:
- input .. a tensor batch of shape (N_batch x D_dim)
- sample_var .. variance to noisify the parameters artificially
- *_epsilon .. presamples from the 0-mean 1-var normal for reuse
outputs:
- a linear feed forward calculation using the sampled weights and biases
records:
- *_epsilon .. samples from the 0-mean 1-var normal for reuse
- *_log_prior .. log prior of the respective parameter
- *_log_post .. log posterior of the respective parameter
- log_prior .. overall sample log prior
- log_post .. overall sample log posterior
"""
if type(w_epsilon) != type(None):
S = w_epsilon.shape[0]
else:
S = 0
# input dimensions
D = self.input_features # input / batch dimension
H = self.output_features # output / hidden dimension
S = max(n_sample, S) # number of samples
# getting the standard deviation for annealing variance
sample_std = torch.sqrt(torch.tensor([sample_var])).to(self.device)
if self.dropout_flag:
if type(z_epsilon) == type(None):
self.z_epsilon = Uniform(0,1).sample((S, *self.z_pies.shape)).to(self.device)
else:
self.z_epsilon = z_epsilon.to(self.device)
# get Bernoulli for input space
self.z = (self.z_epsilon >= self.z_pies).to(self.device).float()
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z.pies).log_prob(self.z)
elif type(z) != type(None):
# use given z
self.z = z
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z_pies).log_prob(self.z)
else:
self.z = torch.ones((S,D)).to(self.device)
self.z_epsilon = torch.zeros((S,D)).to(self.device)
self.z_post = torch.zeros((S,D)).to(self.device)
z_log_prior = torch.zeros((S,D)).to(self.device)
if self.use_bias():
# sample bias noise if not given
if type(b_epsilon) == type(None):
self.b_epsilon = Uniform(0,1).sample((S, *self.b_rho.shape)).to(self.device)
else:
self.b_epsilon = b_epsilon.to(self.device)
# calculate bias with cauchy reparameterization
self.b = ( torch.log(1+torch.exp(self.b_rho)) * sample_std * torch.tan( math.pi* (self.b_epsilon - .5) ) ).abs()
# record log prior by evaluating log pdf of prior at sampled bias
b_log_prior = self.prior.log_prob(self.b)
# bias log posterior
self.b_post = HalfCauchy(torch.log(1+torch.exp(self.b_rho)).data).log_prob(self.b)
else:
self.b = torch.zeros((S,*self.b_rho.shape)).to(self.device)
self.b_epsilon = self.b
self.b_post = self.b
b_log_prior = self.b
# sample weights noise if not given
if type(w_epsilon) == type(None):
self.w_epsilon = Uniform(0,1).sample((S, *self.w_rho.shape)).to(self.device)
else:
self.w_epsilon = w_epsilon.to(self.device)
# calculate weights with cauchy reparameterization
self.w = ( torch.log(1+torch.exp(self.w_rho)) * sample_std * torch.tan( math.pi* (self.w_epsilon - .5) ) ).abs()
# record log prior by evaluating log pdf of prior at sampled weights
w_log_prior = self.prior.log_prob(self.w)
# weights log posterior
self.w_post = HalfCauchy(torch.log(1+torch.exp(self.w_rho)).data).log_prob(self.w)
# record log prior by evaluating log pdf of prior
self.log_prior = \
w_log_prior.sum(dim = [-1,-2]) / D / H + \
b_log_prior.sum(dim = -1) / H + \
z_log_prior.sum(dim = -1) / D
# record log variational posterior by evaluating log pdf of normal distribution defined by parameters with respect at the sampled values
self.log_post = self.w_post.sum(dim = [-1,-2]) / H / D + \
self.b_post.sum(dim = -1) / H + \
self.z_post.sum(dim = -1) / D
return input[:,self.z.long()] @ (self.w[self.z.long()]) + self.b[:,None]
#%%
class LB3_Exponential(nn.Module):
"""
Exponential Layer of our Bayesian Neural Net.
implementation: (Feldman 12/17/2018)
theory and initial work: (Blundell et al 05/21/2015)
"""
def __init__(self,
input_features, output_features,
prior_var=1.,
prior_pies=.5,
device='cuda',
use_bias = False,
dropout_flag = False,
):
"""
Initialization of our layer : our prior is a normal distribution
centered in 0 and of variance 1.
"""
# checking the device first to see if it is available
device = device_check(device)
# initialize layers
super().__init__()
# set input and output dimensions
self.input_features = input_features
self.output_features = output_features
# initialize mu and rho parameters for the weights of the layer
self.w_rho = nn.Parameter(torch.rand(input_features, output_features))
#initialize mu and rho parameters for the layer's bias
self.b_rho = nn.Parameter(torch.rand(output_features))
# initialize Bernoulli Dropout probabilities
if dropout_flag:
self.z_pies = nn.Parameter(torch.rand(input_features))
# in case z willbe given in the forward call
self.dropout_prior = Bernoulli(torch.tensor(prior_pies).to(device))
#initialize weight samples (these will be calculated whenever the layer makes a prediction)
self.w = None
self.b = None
self.z = None
# initialize prior distribution for all of the weights and biases
self.prior = torch.distributions.Exponential(prior_var)
# flags for later calculations
self.use_bias = use_bias
self.dropout_flag = dropout_flag
# this has to be the same device type, you sent the network to
self.device = device
self.to(self.device)
def log_like(self, o, y, noise_tol = 0.1 ):
return ( o.clone() * Exponential(noise_tol).log_prob(y) ).sum()
def forward(
self, input,
w_epsilon = None, b_epsilon = None, z_epsilon = None,
sample_var = 1.0, n_sample = 1, z = None, z_pies = None,
):
"""
Optimization process
inputs:
- input .. a tensor batch of shape (N_batch x D_dim)
- sample_var .. variance to noisify the parameters artificially
- *_epsilon .. presamples from the 0-mean 1-var normal for reuse
outputs:
- a linear feed forward calculation using the sampled weights and biases
records:
- *_epsilon .. samples from the 0-mean 1-var normal for reuse
- *_log_prior .. log prior of the respective parameter
- *_log_post .. log posterior of the respective parameter
- log_prior .. overall sample log prior
- log_post .. overall sample log posterior
"""
if type(w_epsilon) != type(None):
S = w_epsilon.shape[0]
else:
S = 0
# input dimensions
D = self.input_features # input / batch dimension
H = self.output_features # output / hidden dimension
S = max(n_sample, S) # number of samples
# getting the standard deviation for annealing variance
sample_std = torch.sqrt(torch.tensor([sample_var])).to(self.device)
if self.dropout_flag:
if type(z_epsilon) == type(None):
self.z_epsilon = Uniform(0,1).sample((S, *self.z_pies.shape)).to(self.device)
else:
self.z_epsilon = z_epsilon.to(self.device)
# get Bernoulli for input space
self.z = (self.z_epsilon <= self.z_pies).to(self.device).float()
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z_pies).log_prob(self.z)
elif type(z) != type(None):
# use given z
self.z = z
# get greedy Bernoulli probs
z_log_prior = self.dropout_prior.log_prob(self.z)
self.z_post = Bernoulli(self.z_pies).log_prob(self.z)
else:
self.z = torch.ones((S,D)).to(self.device)
self.z_epsilon = torch.zeros((S,D)).to(self.device)
self.z_post = torch.zeros((S,D)).to(self.device)
z_log_prior = torch.zeros((S,D)).to(self.device)
if self.use_bias:
# sample bias noise if not given
if type(b_epsilon) == type(None):
self.b_epsilon = Uniform(0,1).sample((S, *self.b_rho.shape)).to(self.device)
else:
self.b_epsilon = b_epsilon.to(self.device)
# calculate bias with the exponential of a unit distribution
# if x is negative, we don't calculate and probability, what so ever
self.b = torch.log(1+torch.exp(self.b_rho)) * sample_std * \
torch.exp( - torch.log(1+torch.exp(self.b_rho)) * \
self.b_epsilon ) * (self.b_epsilon >= 0).float()
# bias log prior
b_log_prior = self.prior.log_prob(self.b)
# bias log posterior
self.b_post = Exponential(torch.log(1+torch.exp(self.b_rho))).log_prob(self.b)
else:
self.b = torch.zeros((S,*self.b_rho.shape)).to(self.device)
self.b_epsilon = self.b
self.b_post = self.b
b_log_prior = self.b
# sample weights noise if not given
if type(w_epsilon) == type(None):
self.w_epsilon = Uniform(0,1).sample((S, *self.w_rho.shape)).to(self.device)
else:
self.w_epsilon = w_epsilon.to(self.device)
# calculate weights with the exponential of a unit distribution
# if x is negative, we don't calculate and probability, what so ever
self.w = torch.log(1+torch.exp(self.w_rho)) * sample_std * \
torch.exp( - torch.log(1+torch.exp(self.w_rho)) * sample_std * \
self.w_epsilon ) * (self.w_epsilon >= 0).float()
# dropout of weights
# (take only those weights into account whos input is chosen)
self.w = self.w * self.z[:,:,None]
# record log prior by evaluating log pdf of prior at sampled weight and bias
w_log_prior = self.prior.log_prob(self.w[self.z > 0])
# record log variational posterior by evaluating log pdf of normal distribution defined by parameters with respect at the sampled values
self.w_post = Exponential(torch.log(1+torch.exp(self.w_rho))).log_prob(self.w)
# record log prior by evaluating log pdf of prior
self.log_prior = \
w_log_prior.sum(dim = [-1,-2]) / self.z.sum(dim=-1) / H + \
b_log_prior.sum(dim = -1) / H + \
z_log_prior.sum(dim = -1) / D
# record log variational posterior by evaluating log pdf of normal distribution defined by parameters with respect at the sampled values
self.log_post = self.w_post.sum(dim = [-1,-2]) / H / D + \
self.b_post.sum(dim = -1) / H + \
self.z_post.sum(dim = -1) / D
return input @ self.w + self.b[:,None]
###############################################################################
#%% -- standard in-place convolutions and other filters --
class Conv1D_BBB(nn.Module):
"""
1D Convolutional Layer of our Bayesian Neural Net.
implementation: Nils-Markus Meister
theory and initial work: (Blundell et al 05/21/2015)
"""
def __init__(self,
input_features, filter_length,
prior_var = 1.,
prior_pies = .5,
device='cuda',
dropout_flag = False,
full_conv = False,
zero_padd = 0,
activation_function = None,
):
"""
Initialization of our layer : our prior is a normal distribution
centered in 0 and of variance 1.
"""
# checking the device first to see if it is available
device = device_check(device)
# initialize layers
super().__init__()
# set input and output dimensions
self.input_features = input_features
self.filter_length = filter_length
self.zero_padd = zero_padd
self.full_conv = full_conv
# initialize mu and rho parameters for the weights of the layer
self.w_mu = nn.Parameter(torch.randn(input_features, filter_length))
self.w_rho = nn.Parameter(torch.rand(input_features, filter_length))
# initialize Bernoulli Dropout probabilities
if dropout_flag:
self.z_pies = nn.Parameter(torch.rand(input_features))
# in case z willbe given in the forward call
self.dropout_prior = Bernoulli(torch.tensor(prior_pies).to(device))
#initialize weight samples (these will be calculated whenever the layer makes a prediction)
self.w = None
self.z = None
# initialize prior distribution for all of the weights and biases
self.prior = torch.distributions.Normal(0,prior_var)
# flags for later calculations
self.dropout_flag = dropout_flag
# activation function
self.activation_function = act_fun(activation_function)
# this has to be the same device type, you sent the network to
self.device = device
self.to(self.device)
def log_like(self, o, y, noise_tol=0.1):
return Normal(o,noise_tol).log_prob(y)
def forward(
self, input,
w_epsilon = None, b_epsilon = None, z_epsilon = None,
sample_var = 1.0, n_sample = 1, z = None, z_pies = None,
):
"""
Optimization process
inputs:
- input .. a tensor batch of shape (N_batch x D_dim)
- sample_var .. variance to noisify the parameters artificially
- *_epsilon .. presamples from the 0-mean 1-var normal for reuse
outputs:
- a linear feed forward calculation using the sampled weights and biases
records:
- *_epsilon .. samples from the 0-mean 1-var normal for reuse
- *_log_prior .. log prior of the respective parameter
- *_log_post .. log posterior of the respective parameter
- log_prior .. overall sample log prior
- log_post .. overall sample log posterior
"""
if type(w_epsilon) != type(None):
S = w_epsilon.shape[0]
else: