Bayesian Deep Learning

Bayesian neural networks in PyMC: fit a probabilistic neural net with ADVI variational inference and quantify prediction uncertainty.
stats
NeuralNetworks
Author

Thomas Wiecki & Maxim Kochurov

Published

June 1, 2016

Variational Inference: Bayesian Neural Networks

  1. 2016-2018 by Thomas Wiecki, updated by Maxim Kochurov

Original blog post: https://twiecki.github.io/blog/2016/06/01/bayesian-deep-learning/

This post was updated in August 2026 to run on PyMC v6 (formerly PyMC3; PyTensor backend).

Bayesian Neural Networks in PyMC

Generating data

First, lets generate some toy data – a simple binary classification problem that’s not linearly separable.

%matplotlib inline
import pytensor
import pymc as pm
import arviz as az
import sklearn
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from warnings import filterwarnings
filterwarnings('ignore')
sns.set_style('white')
from sklearn import datasets
from sklearn.preprocessing import scale
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_moons

floatX = pytensor.config.floatX
X, Y = make_moons(noise=0.2, random_state=0, n_samples=1000)
X = scale(X)
X = X.astype(floatX)
Y = Y.astype(floatX)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5)
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(X[Y==0, 0], X[Y==0, 1], label='Class 0')
ax.scatter(X[Y==1, 0], X[Y==1, 1], color='r', label='Class 1')
sns.despine(); ax.legend()
ax.set(xlabel='X', ylabel='Y', title='Toy binary classification data set');

Model specification

A neural network is quite simple. The basic unit is a perceptron which is nothing more than logistic regression. We use many of these in parallel and then stack them up to get hidden layers. Here we will use 2 hidden layers with 5 neurons each which is sufficient for such a simple problem.

def construct_nn(ann_input, ann_output, batch_size=None):
    n_hidden = 5

    # Initialize random weights between each layer
    init_1 = np.random.randn(X.shape[1], n_hidden).astype(floatX)
    init_2 = np.random.randn(n_hidden, n_hidden).astype(floatX)
    init_out = np.random.randn(n_hidden).astype(floatX)

    with pm.Model() as neural_network:
        # Trick: Turn inputs and outputs into pm.Data containers.
        # It's still the same thing, but we can later change the values inside the
        # containers with pm.set_data() (to switch in the test-data later) and PyMC
        # will just use the new data. Kind-of like a pointer we can redirect.
        ann_input = pm.Data('ann_input', ann_input)
        ann_output = pm.Data('ann_output', ann_output)

        # For mini-batch ADVI (see further below), stream random
        # subsets of the data instead of the full data set
        if batch_size is not None:
            ann_input, ann_output = pm.Minibatch(ann_input, ann_output,
                                                 batch_size=batch_size)

        # Weights from input to hidden layer
        weights_in_1 = pm.Normal('w_in_1', 0, sigma=1,
                                 shape=(X.shape[1], n_hidden),
                                 initval=init_1)

        # Weights from 1st to 2nd layer
        weights_1_2 = pm.Normal('w_1_2', 0, sigma=1,
                                shape=(n_hidden, n_hidden),
                                initval=init_2)

        # Weights from hidden layer to output
        weights_2_out = pm.Normal('w_2_out', 0, sigma=1,
                                  shape=(n_hidden,),
                                  initval=init_out)

        # Build neural-network using tanh activation function
        act_1 = pm.math.tanh(pm.math.dot(ann_input,
                                         weights_in_1))
        act_2 = pm.math.tanh(pm.math.dot(act_1,
                                         weights_1_2))
        act_out = pm.math.sigmoid(pm.math.dot(act_2,
                                              weights_2_out))

        # Binary classification -> Bernoulli likelihood
        out = pm.Bernoulli('out',
                           act_out,
                           observed=ann_output,
                           total_size=Y_train.shape[0] # IMPORTANT for minibatches
                          )
    return neural_network

neural_network = construct_nn(X_train, Y_train)

That’s not so bad. The Normal priors help regularize the weights. Usually we would add a constant b to the inputs but I omitted it here to keep the code cleaner.

Variational Inference: Scaling model complexity

We could now just run a MCMC sampler like NUTS which works pretty well in this case, but as I already mentioned, this will become very slow as we scale our model up to deeper architectures with more layers.

Instead, we will use ADVI variational inference algorithm which was recently added to PyMC, and updated to use the operator variational inference (OPVI) framework. This is much faster and will scale better. Note, that this is a mean-field approximation so we ignore correlations in the posterior.

RANDOM_SEED = 42
%%time

with neural_network:
    inference = pm.ADVI()
    approx = pm.fit(n=50000, method=inference, random_seed=RANDOM_SEED)

Finished [100%]: Average Loss = 129.23
CPU times: user 7.48 s, sys: 193 ms, total: 7.67 s
Wall time: 7.93 s

Performance wise that’s pretty good considering that NUTS is having a really hard time. Further below we make this even faster. To make it really fly, we probably want to run the Neural Network on the GPU.

As samples are more convenient to work with, we can very quickly draw samples from the variational approximation using the sample method (this is just sampling from Normal distributions, so not at all the same like MCMC):

trace = approx.sample(draws=5000)

Plotting the objective function (ELBO) we can see that the optimization slowly improves the fit over time.

plt.plot(-inference.hist)
plt.ylabel('ELBO')
plt.xlabel('iteration');

Now that we trained our model, lets predict on the hold-out set using a posterior predictive check (PPC).

# Swap in the test data via the pm.Data containers our NN references
with neural_network:
    pm.set_data({'ann_input': X_test, 'ann_output': Y_test})
    # sample_posterior_predictive no longer takes a samples= argument,
    # so we thin the trace to 500 draws instead
    ppc = pm.sample_posterior_predictive(trace.sel(draw=slice(None, None, 10)),
                                         progressbar=False)

# Use probability of > 0.5 to assume prediction of class 1
pred = ppc.posterior_predictive['out'].mean(('chain', 'draw')).values > 0.5

Let’s look at our predictions:

fig, ax = plt.subplots()
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1])
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r')
sns.despine()
ax.set(title='Predicted labels in testing set', xlabel='X', ylabel='Y');

print('Accuracy = {}%'.format((Y_test == pred).mean() * 100))
Accuracy = 95.19999999999999%

Hey, our neural network did all right!

Lets look at what the classifier has learned

For this, we evaluate the class probability predictions on a grid over the whole input space.

grid = np.mgrid[-3:3:100j,-3:3:100j].astype(floatX)
grid_2d = grid.reshape(2, -1).T
dummy_out = np.ones(grid_2d.shape[0], dtype=floatX)
with neural_network:
    pm.set_data({'ann_input': grid_2d, 'ann_output': dummy_out})
    ppc = pm.sample_posterior_predictive(trace.sel(draw=slice(None, None, 10)),
                                         progressbar=False)

Probability surface

cmap = sns.diverging_palette(250, 12, s=85, l=25, as_cmap=True)
fig, ax = plt.subplots(figsize=(14, 8))
contour = ax.contourf(grid[0], grid[1],
                      ppc.posterior_predictive['out'].mean(('chain', 'draw')).values.reshape(100, 100),
                      cmap=cmap)
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1])
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r')
cbar = plt.colorbar(contour, ax=ax)
_ = ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel='X', ylabel='Y');
cbar.ax.set_ylabel('Posterior predictive mean probability of class label = 0');

Uncertainty in predicted value

So far, everything I showed we could have done with a non-Bayesian Neural Network. The mean of the posterior predictive for each class-label should be identical to maximum likelihood predicted values. However, we can also look at the standard deviation of the posterior predictive to get a sense for the uncertainty in our predictions. Here is what that looks like:

cmap = sns.cubehelix_palette(light=1, as_cmap=True)
fig, ax = plt.subplots(figsize=(14, 8))
contour = ax.contourf(grid[0], grid[1],
                      ppc.posterior_predictive['out'].std(('chain', 'draw')).values.reshape(100, 100),
                      cmap=cmap)
ax.scatter(X_test[pred==0, 0], X_test[pred==0, 1])
ax.scatter(X_test[pred==1, 0], X_test[pred==1, 1], color='r')
cbar = plt.colorbar(contour, ax=ax)
_ = ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel='X', ylabel='Y');
cbar.ax.set_ylabel('Uncertainty (posterior predictive standard deviation)');

We can see that very close to the decision boundary, our uncertainty as to which label to predict is highest. You can imagine that associating predictions with uncertainty is a critical property for many applications like health care. To further maximize accuracy, we might want to train the model primarily on samples from that high-uncertainty region.

Mini-batch ADVI

So far, we have trained our model on all data at once. Obviously this won’t scale to something like ImageNet. Moreover, training on mini-batches of data (stochastic gradient descent) avoids local minima and can lead to faster convergence.

Fortunately, ADVI can be run on mini-batches as well. It just requires some setting up:

# pm.Minibatch is applied inside construct_nn() via the batch_size argument
neural_network_minibatch = construct_nn(X_train, Y_train, batch_size=32)
with neural_network_minibatch:
    inference = pm.ADVI()
    approx = pm.fit(40000, method=inference, random_seed=RANDOM_SEED)

Finished [100%]: Average Loss = 8.4346
plt.plot(-inference.hist)
plt.ylabel('ELBO')
plt.xlabel('iteration');

As you can see, mini-batch ADVI’s running time is much lower. It also seems to converge faster.

For fun, we can also look at the trace. The point is that we also get uncertainty of our Neural Network weights.

az.plot_trace(trace);

Summary

Hopefully this blog post demonstrated a very powerful new inference algorithm available in PyMC: ADVI. I also think bridging the gap between Probabilistic Programming and Deep Learning can open up many new avenues for innovation in this space, as discussed above. Specifically, a hierarchical neural network sounds pretty bad-ass. These are really exciting times.

Next steps

Theano, which is used by PyMC as its computational backend (today, PyMC uses PyTensor, a fork of Theano, for the same job), was mainly developed for estimating neural networks and there are great libraries like Lasagne that build on top of Theano to make construction of the most common neural network architectures easy. See my follow-up blog post on how to use Lasagne together with PyMC.

You can also run this example on the GPU by setting device = gpu and floatX = float32 in your .theanorc (today: PyTensor’s .pytensorrc).

You might argue that the above network isn’t really deep, but note that we could easily extend it to have more layers, including convolutional ones to train on more challenging data sets, as demonstrated [here](follow-up blog post on how to use Lasagne together with PyMC.

I also presented some of this work at PyData London, view the video below:

Finally, you can download this NB here. Leave a comment below, and follow me on twitter.

Acknowledgements

Taku Yoshioka did a lot of work on the original ADVI implementation in PyMC. I’d also like to the thank the Stan guys (specifically Alp Kucukelbir and Daniel Lee) for deriving ADVI and teaching us about it. Thanks also to Chris Fonnesbeck, Andrew Campbell, Taku Yoshioka, and Peadar Coyle for useful comments on an earlier draft.