1
1
# ruff: noqa: E402, E703, D212, D415, T201
2
2
"""
3
- Train a Bayesian Neural Network in Three Minutes
3
+ Training a Bayesian Neural Network in 20 seconds
4
4
================================================
5
5
6
- In this tutorial, we will train a variational inference Bayesian Neural Network (BNN ) LeNet classifier on the MNIST dataset.
6
+ In this tutorial, we will train a variational inference Bayesian Neural Network (viBNN ) LeNet classifier on the MNIST dataset.
7
7
8
8
Foreword on Bayesian Neural Networks
9
9
------------------------------------
10
10
11
11
Bayesian Neural Networks (BNNs) are a class of neural networks that estimate the uncertainty on their predictions via uncertainty
12
12
on their weights. This is achieved by considering the weights of the neural network as random variables, and by learning their
13
- posterior distribution. This is in contrast to standard neural networks, which only learn a single set of weights, which can be
14
- seen as Dirac distributions on the weights.
13
+ posterior distribution. This is in contrast to standard neural networks, which only learn a single set of weights (this can be
14
+ seen as Dirac distributions on the weights) .
15
15
16
- For more information on Bayesian Neural Networks, we refer the reader to the following resources:
16
+ For more information on Bayesian Neural Networks, we refer to the following resources:
17
17
18
18
- Weight Uncertainty in Neural Networks `ICML2015 <https://arxiv.org/pdf/1505.05424.pdf>`_
19
- - Hands-on Bayesian Neural Networks - a Tutorial for Deep Learning Users `IEEE Computational Intelligence Magazine <https://arxiv.org/pdf/2007.06823.pdf>`_
19
+ - Hands-on Bayesian Neural Networks - a Tutorial for Deep Learning Users `IEEE Computational Intelligence Magazine
20
+ <https://arxiv.org/pdf/2007.06823.pdf>`_
20
21
21
22
Training a Bayesian LeNet using TorchUncertainty models and Lightning
22
23
---------------------------------------------------------------------
23
24
24
- In this part, we train a Bayesian LeNet, based on the model and routines already implemented in TU.
25
+ In this first part, we train a Bayesian LeNet, based on the model and routines already implemented in TU.
25
26
26
27
1. Loading the utilities
27
28
~~~~~~~~~~~~~~~~~~~~~~~~
28
29
29
30
To train a BNN using TorchUncertainty, we have to load the following modules:
30
31
31
- - our TUTrainer
32
- - the model: bayesian_lenet, which lies in the torch_uncertainty.model
33
- - the classification training routine from torch_uncertainty.routines
32
+ - our TUTrainer to improve the display of our metrics
33
+ - the model: bayesian_lenet, which lies in the torch_uncertainty.model.classification.lenet module
34
+ - the classification training routine from torch_uncertainty.routines module
34
35
- the Bayesian objective: the ELBOLoss, which lies in the torch_uncertainty.losses file
35
36
- the datamodule that handles dataloaders: MNISTDataModule from torch_uncertainty.datamodules
36
37
46
47
from torch_uncertainty import TUTrainer
47
48
from torch_uncertainty .datamodules import MNISTDataModule
48
49
from torch_uncertainty .losses import ELBOLoss
49
- from torch_uncertainty .models .classification import bayesian_lenet
50
+ from torch_uncertainty .models .classification . lenet import bayesian_lenet
50
51
from torch_uncertainty .routines import ClassificationRoutine
51
52
53
+ # We also define the main hyperparameters, with just one epoch for the sake of time
54
+ BATCH_SIZE = 512
55
+ MAX_EPOCHS = 2
56
+
52
57
# %%
53
58
# 2. Creating the necessary variables
54
59
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
55
60
#
56
61
# In the following, we instantiate our trainer, define the root of the datasets and the logs.
57
62
# We also create the datamodule that handles the MNIST dataset, dataloaders and transforms.
58
- # Please note that the datamodules can also handle OOD detection by setting the eval_ood
59
- # parameter to True. Finally, we create the model using the blueprint from torch_uncertainty.models.
63
+ # Please note that the datamodules can also handle OOD detection by setting the `eval_ood`
64
+ # parameter to True, as well as distribution shift with `eval_shift`.
65
+ # Finally, we create the model using the blueprint from torch_uncertainty.models.
60
66
61
- trainer = TUTrainer (accelerator = "gpu" , devices = 1 , enable_progress_bar = False , max_epochs = 1 )
67
+ trainer = TUTrainer (accelerator = "gpu" , devices = 1 , enable_progress_bar = False , max_epochs = MAX_EPOCHS )
62
68
63
69
# datamodule
64
70
root = Path ("data" )
65
- datamodule = MNISTDataModule (root = root , batch_size = 128 , eval_ood = False )
71
+ datamodule = MNISTDataModule (root = root , batch_size = BATCH_SIZE , num_workers = 8 )
66
72
67
73
# model
68
74
model = bayesian_lenet (datamodule .num_channels , datamodule .num_classes )
69
75
70
76
# %%
71
77
# 3. The Loss and the Training Routine
72
78
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
73
- # Then, we just have to define the loss to be used during training. To do this,
74
- # we redefine the default parameters from the ELBO loss using the partial
75
- # function from functools. We use the hyperparameters proposed in the blitz
76
- # library. As we are train a classification model, we use the CrossEntropyLoss
77
- # as the likelihood.
78
- # We then define the training routine using the classification training routine
79
- # from torch_uncertainty.classification. We provide the model, the ELBO
79
+ #
80
+ # Then, we just define the loss to be used during training, which is a bit special and called
81
+ # the evidence lower bound. We use the hyperparameters proposed in the blitz
82
+ # library. As we are training a classification model, we use the CrossEntropyLoss
83
+ # as the negative log likelihood. We then define the training routine using the classification
84
+ # training routine from torch_uncertainty.classification. We provide the model, the ELBO
80
85
# loss and the optimizer to the routine.
81
- # We will use the Adam optimizer with the default learning rate of 0.001 .
86
+ # We use an Adam optimizer with a learning rate of 0.02 .
82
87
83
88
loss = ELBOLoss (
84
89
model = model ,
91
96
model = model ,
92
97
num_classes = datamodule .num_classes ,
93
98
loss = loss ,
94
- optim_recipe = optim .Adam (
95
- model .parameters (),
96
- lr = 1e-3 ,
97
- ),
99
+ optim_recipe = optim .Adam (model .parameters (), lr = 2e-2 ),
98
100
is_ensemble = True ,
99
101
)
100
102
105
107
# Now that we have prepared all of this, we just have to gather everything in
106
108
# the main function and to train the model using our wrapper of Lightning Trainer.
107
109
# Specifically, it needs the routine, that includes the model as well as the
108
- # training/eval logic and the datamodule
110
+ # training/eval logic and the datamodule.
109
111
# The dataset will be downloaded automatically in the root/data folder, and the
110
112
# logs will be saved in the root/logs folder.
111
113
112
114
trainer .fit (model = routine , datamodule = datamodule )
113
115
trainer .test (model = routine , datamodule = datamodule )
114
-
115
116
# %%
116
117
# 5. Testing the Model
117
118
# ~~~~~~~~~~~~~~~~~~~~
118
119
#
119
120
# Now that the model is trained, let's test it on MNIST.
120
121
# Please note that we apply a reshape to the logits to determine the dimension corresponding to the ensemble
121
- # and to the batch. As for TorchUncertainty 0.2.0 , the ensemble dimension is merged with the batch dimension
122
+ # and to the batch. As for TorchUncertainty 0.5.1 , the ensemble dimension is merged with the batch dimension
122
123
# in this order (num_estimator x batch, classes).
124
+
123
125
import matplotlib .pyplot as plt
124
126
import numpy as np
125
127
import torch
126
128
import torchvision
129
+ from einops import rearrange
127
130
128
131
129
132
def imshow (img ) -> None :
@@ -134,32 +137,33 @@ def imshow(img) -> None:
134
137
plt .show ()
135
138
136
139
137
- dataiter = iter (datamodule .val_dataloader ())
138
- images , labels = next (dataiter )
140
+ images , labels = next (iter (datamodule .val_dataloader ()))
139
141
140
142
# print images
141
143
imshow (torchvision .utils .make_grid (images [:4 , ...]))
142
144
print ("Ground truth: " , " " .join (f"{ labels [j ]} " for j in range (4 )))
143
145
144
146
# Put the model in eval mode to use several samples
145
- model = model .eval ()
146
- logits = model (images ).reshape (16 , 128 , 10 ) # num_estimators, batch_size, num_classes
147
+ model = routine .eval ()
148
+ logits = routine (images [:4 , ...])
149
+ print ("Output logit shape (Num predictions x Batch) x Classes: " , logits .shape )
150
+ logits = rearrange (logits , "(m b) c -> b m c" , b = 4 ) # batch_size, num_estimators, num_classes
147
151
148
- # We apply the softmax on the classes and average over the estimators
152
+ # We apply the softmax on the classes then average over the estimators
149
153
probs = torch .nn .functional .softmax (logits , dim = - 1 )
150
- avg_probs = probs .mean (dim = 0 )
151
- var_probs = probs .std (dim = 0 )
154
+ avg_probs = probs .mean (dim = 1 )
155
+ var_probs = probs .std (dim = 1 )
152
156
153
- _ , predicted = torch .max (avg_probs , 1 )
157
+ predicted = torch .argmax (avg_probs , - 1 )
154
158
155
159
print ("Predicted digits: " , " " .join (f"{ predicted [j ]} " for j in range (4 )))
156
160
print (
157
161
"Std. dev. of the scores over the posterior samples" ,
158
- " " .join (f"{ var_probs [j ][predicted [j ]]:.3 } " for j in range (4 )),
162
+ " " .join (f"{ var_probs [j ][predicted [j ]]:.3f } " for j in range (4 )),
159
163
)
160
164
# %%
161
165
# Here, we show the variance of the top prediction. This is a non-standard but intuitive way to show the diversity of the predictions
162
- # of the ensemble. Ideally, the variance should be high when the average top prediction is incorrect.
166
+ # of the ensemble. Ideally, the variance should be high when the prediction is incorrect.
163
167
#
164
168
# References
165
169
# ----------
0 commit comments