|
| 1 | +""" |
| 2 | +Bayesian Quickstart Testing |
| 3 | +=========================== |
| 4 | +""" |
| 5 | + |
| 6 | +# %% md |
| 7 | +# This is the second half of a Bayesian version of the classification problem from this Pytorch Quickstart tutorial: |
| 8 | +# https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html |
| 9 | +# |
| 10 | +# This script assumes you have already run the Bayesian Quickstart Testing script and saved the optimized model |
| 11 | +# to a file named ``bayesian_model.pth``. This script |
| 12 | +# |
| 13 | +# - Loads a trained model from the file ``bayesian_model.pt`` |
| 14 | +# - Makes deterministic predictions |
| 15 | +# - Makes probabilistic predictions |
| 16 | +# - Plots probabilistic predictions |
| 17 | +# |
| 18 | +# First, we import the necessary modules and define the BayesianNeuralNetwork class, so we can load the model state |
| 19 | +# dictionary saved in ``bayesian_model.pth``. |
| 20 | + |
| 21 | +# %% |
| 22 | +import torch |
| 23 | +import torch.nn as nn |
| 24 | +from torchvision import datasets |
| 25 | +from torchvision.transforms import ToTensor |
| 26 | +import matplotlib.pyplot as plt |
| 27 | +import UQpy.scientific_machine_learning as sml |
| 28 | + |
| 29 | +plt.style.use("ggplot") |
| 30 | + |
| 31 | + |
| 32 | +class BayesianNeuralNetwork(nn.Module): |
| 33 | + """UQpy: Replace torch's nn.Linear with UQpy's sml.BayesianLinear""" |
| 34 | + |
| 35 | + def __init__(self): |
| 36 | + super().__init__() |
| 37 | + self.flatten = nn.Flatten() |
| 38 | + self.linear_relu_stack = nn.Sequential( |
| 39 | + sml.BayesianLinear(28 * 28, 512), # nn.Linear(28 * 28, 512) |
| 40 | + nn.ReLU(), |
| 41 | + sml.BayesianLinear(512, 512), # nn.Linear(512, 512) |
| 42 | + nn.ReLU(), |
| 43 | + sml.BayesianLinear(512, 512), # nn.Linear(512, 512) |
| 44 | + nn.ReLU(), |
| 45 | + sml.BayesianLinear(512, 10), # nn.Linear(512, 10) |
| 46 | + ) |
| 47 | + |
| 48 | + def forward(self, x): |
| 49 | + x = self.flatten(x) |
| 50 | + logits = self.linear_relu_stack(x) |
| 51 | + return logits |
| 52 | + |
| 53 | + |
| 54 | +# %% md |
| 55 | +# Since the model is already trained, we only need to load test data and can ignore the training data. |
| 56 | +# Then we use Pytorch's framework for loading a model from a state dictionary. |
| 57 | + |
| 58 | +# %% |
| 59 | + |
| 60 | +# Download test data from open datasets. |
| 61 | +test_data = datasets.FashionMNIST( |
| 62 | + root="data", |
| 63 | + train=False, |
| 64 | + download=False, |
| 65 | + transform=ToTensor(), |
| 66 | +) |
| 67 | + |
| 68 | +device = "cpu" |
| 69 | +network = BayesianNeuralNetwork().to(device) |
| 70 | +model = sml.FeedForwardNeuralNetwork(network).to(device) |
| 71 | +model.load_state_dict(torch.load("bayesian_model.pt")) |
| 72 | + |
| 73 | +# %% md |
| 74 | +# Here we make the deterministic prediction. We set the sample mode to ``False`` and evaluate our model on the first |
| 75 | +# image in ``test_data``. |
| 76 | + |
| 77 | +# %% |
| 78 | + |
| 79 | +classes = [ |
| 80 | + "T-shirt/top", |
| 81 | + "Trouser", |
| 82 | + "Pullover", |
| 83 | + "Dress", |
| 84 | + "Coat", |
| 85 | + "Sandal", |
| 86 | + "Shirt", |
| 87 | + "Sneaker", |
| 88 | + "Bag", |
| 89 | + "Ankle boot", |
| 90 | +] |
| 91 | +model.eval() |
| 92 | +model.sample(False) # UQpy: Set sample mode to False |
| 93 | +x, y = test_data[0][0], test_data[0][1] |
| 94 | +with torch.no_grad(): |
| 95 | + x = x.to(device) |
| 96 | + pred = model(x) |
| 97 | + predicted, actual = classes[pred[0].argmax(0)], classes[y] |
| 98 | + print("----- Deterministic Prediction") |
| 99 | + print(f"Predicted: {predicted}, Actual: {actual}") |
| 100 | + print(f"{'Class'.ljust(11)} {'Logits'.rjust(7)} {'softmax(Logits)'}") |
| 101 | + for i, c in enumerate(classes): |
| 102 | + print(f"{c.ljust(12)} {pred[0, i]: 6.2f} {torch.softmax(pred, 1)[0, i]: 15.2e}") |
| 103 | + |
| 104 | +# %% md |
| 105 | +# Just like the torch tutorial, our model correctly identifies this image as an ankle boot. |
| 106 | +# Next, we show how to make probabilistic predictions by turning on our model's ``sampling`` mode. |
| 107 | +# We feed the same image of an ankle boot into our model 1,000 times and each time the weights and biases |
| 108 | +# are sampled from the distributions that were learned during training. |
| 109 | +# Rather than one static output, we get a distribution of 1,000 predictions! |
| 110 | + |
| 111 | +# %% |
| 112 | + |
| 113 | +model.sample() |
| 114 | +n_samples = 1_000 |
| 115 | +logits = torch.empty((n_samples, len(classes))) |
| 116 | +with torch.no_grad(): |
| 117 | + for i in range(n_samples): |
| 118 | + logits[i] = model(x) |
| 119 | + |
| 120 | +# %% md |
| 121 | +# Those few lines are all it takes to make Bayesian predictions. |
| 122 | +# The rest of this example converts the predicted logits into class predictions. |
| 123 | +# The predicted distribution is visualized in the histogram below, which |
| 124 | +# shows the majority of predictions classify the image as an ankle boot. |
| 125 | +# Interestingly, the two other shoe classes (sneaker and sandal) are also common predictions. |
| 126 | + |
| 127 | +# %% |
| 128 | + |
| 129 | +predicted_classes = torch.argmax(logits, dim=1) |
| 130 | +predicted_counts = torch.bincount(predicted_classes) |
| 131 | +predictions = {c: int(i) for c, i in zip(classes, predicted_counts)} |
| 132 | +i = torch.argmax(predicted_counts) |
| 133 | + |
| 134 | +print("----- Probabilistic Predictions") |
| 135 | +print("Most Commonly Predicted:", classes[i], "Actual:", actual) |
| 136 | +print(f"{'Class'.ljust(11)} Probability") |
| 137 | +for c in classes: |
| 138 | + print(f"{c.ljust(11)} {predictions[c] / n_samples: 11.3f}") |
| 139 | + |
| 140 | +# Plot probabilistic class predictions |
| 141 | +fig, ax = plt.subplots() |
| 142 | +colors = plt.cm.tab10_r(torch.linspace(0, 1, 10)) |
| 143 | +b = ax.bar(classes, predicted_counts, label=predicted_counts, color=colors) |
| 144 | +ax.bar_label(b) |
| 145 | +ax.set_title("Bayesian NN Predictions", loc="left") |
| 146 | +ax.set(xlabel="Classes", ylabel="Counts") |
| 147 | +ax.set_xticklabels(classes, rotation=45) |
| 148 | +fig.tight_layout() |
| 149 | + |
| 150 | +# %% md |
| 151 | +# In addition to visualizing the class predictions, we can look at the logit values output by our Bayesian model. |
| 152 | +# Below we plot a histogram of the logits for Sandal, Sneaker, Bag, and Ankle Boot. |
| 153 | +# The other classes are omitted since they were never predicted by our model. |
| 154 | +# |
| 155 | +# Notice that for Bag, the histogram peaks near zero. |
| 156 | +# This aligns with the fact that Bag is a very unlikely prediction from our model. |
| 157 | +# Contrast that histogram with the one for Ankle Boot, which is very likely to take on a high value. |
| 158 | +# We interpret this as our model being very likely to predict Ankle Boot. |
| 159 | + |
| 160 | +# %% |
| 161 | + |
| 162 | +# Plot probabilistic logit predictions |
| 163 | +softmax_logits = torch.softmax(logits, 1) |
| 164 | +fig, ax = plt.subplots() |
| 165 | +ax.hist(softmax_logits[:, 9], label="Ankle Boot", bins=20, facecolor=colors[9]) |
| 166 | +for i in (5, 7, 8): # loop over Sandal, Sneaker, Bag |
| 167 | + ax.hist( |
| 168 | + softmax_logits[:, i], |
| 169 | + label=classes[i], |
| 170 | + bins=20, |
| 171 | + edgecolor=colors[i], |
| 172 | + facecolor="none", |
| 173 | + linewidth=2, |
| 174 | + ) |
| 175 | +ax.set_title("Bayesian NN softmax(logits)", loc="left") |
| 176 | +ax.set(xlabel="softmax(logit) Value", ylabel="Log(Counts)") |
| 177 | +ax.legend() |
| 178 | +ax.set_yscale("log") |
| 179 | +fig.tight_layout() |
| 180 | + |
| 181 | + |
| 182 | +# %% md |
| 183 | +# We can also visualize these distributions and how they correlate with one another with a pair plot. |
| 184 | + |
| 185 | +# %% |
| 186 | + |
| 187 | +# Use pandas and seaborn for easy pair plots |
| 188 | +import seaborn |
| 189 | +import pandas as pd |
| 190 | + |
| 191 | +df = pd.DataFrame({classes[i]: softmax_logits[:, i] for i in (5, 7, 8, 9)}) |
| 192 | +seaborn.pairplot(df, corner=True, plot_kws={"alpha": 0.2, "edgecolor": None}) |
| 193 | + |
| 194 | +plt.show() |
0 commit comments