Bayesian Inference with MCMC
A gentle introduction with code examples
By Pietro Lesci in Probabilistic Programming
June 19, 2019
This blog post is an attempt at trying to explain the intuition behind MCMC sampling: specifically, a particular instance of the MetropolisHasting algorithm. Critically, we’ll be using TensorFlowProbability
code examples to explain the various concepts.
The Problem
First, let’s import our modules. Note that we will use TensorFlow 2 Beta and we will use the TFP nightly distribution with works fine with TF2.
1import numpy as np
2import tensorflow as tf
3import tensorflow_probability as tfp
4tfd = tfp.distributions
5
6import matplotlib.pyplot as plt
7import seaborn as sns
8
9tf.random.set_seed(1905)
10
11%matplotlib inline
12sns.set(rc={'figure.figsize':(9.3,6.1)})
13sns.set_context('paper')
14sns.set_style('whitegrid')
15
16print(tf.__version__, tfp.__version__)
2.0.0 0.7.0
Let’s generate some data: 20 points from a Gaussian distribution centered around zero (the true DataGenerating Process that we want to discover from the 20 samples we can see). Note that in TFP the Gaussian distribution is parametrized by mean and standard deviation, not the variance.
1true_dgp = tfd.Normal(loc=0., scale=1.)
2observed = true_dgp.sample(20)
3sns.distplot(observed, kde=False)
4sns.despine();
We have some observations $x$
.
Usually (in parametric statistics) we assume a datagenerating process, i.e. a model $P(x\theta)$
, from which the data we see had been sampled – note that $P$
is used to denote a probability density/mass function. Looking at the data, we come up – somehow – with the idea that a good model for our data is the Gaussian distribution. In other words, we assume that the data are normally distributed.
The model often depends on unknown parameters $\theta$
. They can be unknown because they are intrinsecally random or because simply we do not know them. A normal distribution has two parameters: the mean, $\mu$
, and the standard deviation, $\sigma$
. For simplicity, we assume we know $\sigma=1$
and we want to make inference on $\mu$
only, that is $\theta \equiv \mu$
.
From a Bayesian viewpoint, we have to define a prior distribution for this parameter, i.e. $P(\theta)$
. Let’s also assume a normal distribution as a prior for $\mu$
. Our model can be written as follows (we assumed that the prior is a Gaussian distribution with mean 4 and stardard deviation 2)
$$x_i\mu \stackrel{i.i.d.}{\sim} \mathcal{N}(\mu, \sigma=1)$$
$$\mu \sim \mathcal{N}(\mu_0 = 4, \sigma_0 = 2)$$
In the Bayesian Stat lingo, this way of writing the model derives from the fact that knowing nothing about the joint distribution of the $x$
’s' we can assume
exchangeability. By the
De Finetti’s Theorem we arrive to the above formulation. Anyway, this goes beyond the scope of this blog post. For more information on Bayesian Analysis look at (the bible)
Gelman et al. book.
1# prior
2mu_0, sigma_0 = 4., 2.
3prior = tfd.Normal(mu_0, sigma_0)
4
5# likelihood
6mu, sigma = prior.sample(1), 1. # use a sample from the prior as guess for mu
7likelihood = tfd.Normal(mu, sigma)
Digression: note that actually what I called likelihood, is the likelihood for one specific datapoint – call it
$\mathrm{likelihood}_i, i=1,\dots,N$
. The “proper” likelihood function is (given that we have an$i.i.d.$
sample) equal to the product of the “perdatapoint” likelihoods
$$\mathcal{L}(\mu; x) = \prod_{i=1}^n \underbrace{\frac{1}{\sqrt{2\pi\sigma^2}} \exp \left\{\frac{(x_i\mu)^2}{2\sigma^2}\right\}}_{\mathcal{L}(\mu; x_i)}$$
When we consider the loglikelihood, obviously, for an$i.i.d.$
sample, the loglikelihood is the sum of the individual “perdatapoint” likelihoods
$$\mathcal{l}(\mu; x) = \sum_{i=1}^n \mathcal{l}(\mu; x_i)$$
Usually, the likelihood is denoted by$\mathcal{L}(\mu; x)$
or$p(x\mu)$
.
Since we do not know the mean of the Gaussian distribution which generated the data, we use a sample from the prior distribution as a guess for $\mu$
in order to be able to draw it (we need a value), the likelihood has a mean similar to that of the prior distribution.
In the graph below, I plot both the prior and the likelihood, as well as the true datagenerating process with the data plotted as a rug
1sns.rugplot(observed, linewidth=2, height=0.1)
2sns.distplot(prior.sample(10**5))
3sns.distplot(likelihood.sample(10**5))
4sns.distplot(true_dgp.sample(10**5))
5sns.despine()
6plt.legend(labels=['Data', 'Prior','Likelihood', 'True DGP'])
7plt.xlim(5, 7);
In the Bayesian framework, inference, i.e. knowing something more about the unknown parameters, is solved by the Bayes formula
$$P(\thetax)=\frac{P(x\theta)P(\theta)}{P(x)}$$
The posterior distribution $P(\thetax)$
– that is, what we know about our model parameters $\theta$
after having seen thet data $x$
– is our quantity of interest.
To compute it, we multiply the prior $P(\theta)$
(what we think about $\theta$
before we have seen any data) and the likelihood $P(x\theta)$
, dividing by the evidence $P(x)$
(a.k.a. marginal likelihood).
However, let’s take a closer look at this last term: the denominator, $P(x)$
. We do not observe it, but we can compute this quantity by integrating over all possible parameter values:
$$P(x)=\int_\Theta P(x,\theta) \ d\theta$$
This is the key difficulty with the Bayes formula – while the formula looks pretty enough, for even slightly nontrivial models we cannot compute the posterior in a closedform way.
NOTE: $P(x)$
is a normalizing constant. Up to this normalizing constant, we know exactly how the unnormalized posterior distribution looks like, i.e.
$$P(\thetax) \propto P(x\theta) P(\theta)$$
(where $\propto$
mean “proportional to”). Since we defined both terms on the rhs, we DO know how to sample from the unnormalized posterior distribution
Furthermore, by the product rule – $P(A, B) = P(AB) P(B)$
– we can write
$$P(\thetax) \propto P(x, \theta)$$
meaning that the unnormalized posterior is proportional to the joint distribution of $x$
and $\theta$
.
Back to the example. The prior distribution we defined is convenient because we can actually compute the posterior distribution analytically. That’s because for a normal likelihood with known standard deviation, the normal prior distribution for $\mu$
is
conjugate, i.e. our posterior distribution will belong to the same family of distributions of the prior. Therefore, we know that our posterior distribution for $\mu$
is also normal. For a mathematical derivation see
here.
Let’s define a function which computes the updates for the parameters of the posterior distribution analytically
1def get_param_updates(data, sigma, prior_mu, prior_sigma): #sigma is known
2 n = len(data)
3 sigma2 = sigma**2
4 prior_sigma2 = prior_sigma**2
5 x_bar = tf.reduce_mean(data)
6
7 post_mu = ((sigma2 * prior_mu) + (n * prior_sigma2 * x_bar)) / ((n * prior_sigma2) + (sigma2))
8 post_sigma2 = (sigma2 * prior_sigma2) / ((n * prior_sigma2) + sigma2)
9 post_sigma = tf.math.sqrt(post_sigma2)
10
11 return post_mu, post_sigma
1# posterior
2mu_n, sigma_n = get_param_updates(observed,
3 sigma=1,
4 prior_mu=mu_0,
5 prior_sigma=sigma_0)
6posterior = tfd.Normal(mu_n, sigma_n, name='posterior')
In the graph below, I plot both the prior and the posterior distributions. Furthermore, I plot the likelihood both with mean set to a sample from the prior and a sample from the posterior
1sns.distplot(prior.sample(10**5))
2sns.distplot(posterior.sample(10**5))
3sns.distplot(likelihood.sample(10**5))
4sns.distplot(tfd.Normal(posterior.sample(1), 1.).sample(10**5))
5sns.despine()
6plt.legend(labels=['Prior','Posterior', 'Likelihood (prior)', 'Likelihood (Posterior)'])
7plt.xlim(5, 7);
This shows our quantity of interest (orange): the probability of $\mu$
’s values after having seen the data, taking our prior information into account.
The important thing to acknowledge is that, without conjugacy, we would not even be capable of sketching the posterior distribution: we would not know its shape at all. Let’s assume, however, that our prior was not conjugate and we could not solve this by hand – which is often the case.
Approximation methods
When we do not have access to the analytic form of the posterior distribution we can resort to MCMC methods. The basic idea is that we can find strategies to sample from the posterior distribution, even if we cannot “write it down”. These samples are then used to approximate the posterior distribution. One simple strategy to get samples from the posterior distribution is the Rejection Sampling algorithm.
Rejection Sampling
The basic idea of rejection sampling is to sample from an instrumental distribution and reject samples that are “unlikely” under the target distribution. Here we consider a very specific instance of rejection sampling: the Naive Rejection Sampling.
Suppose that you can sample from a joint distribution $P(X, \theta)$
(where $X$
is random as well) – we have seen that we can sample from it since using the product rule we get $P(X, \theta) = P(X\theta) P(\theta)$
, which are both defined by us, so we know how to sample from them!
We are interested in sampling $\theta$
from the conditional distribution $P(\thetaX = x)$
, for some fixed values of $x$
– i.e. the observed data.
The Naive Rejection Sampling algorithm works as follows:

Sample
$\theta$
from the prior$P(\theta)$
and$X$
from the likelihood$P(X\theta)$

If
$X = x$
(the observed data) , accept$\theta$
as a sample from the posterior$P(\thetaX = x)$
, otherwise return to (1) and repeat
Each time you return to step 1, the samples of $\theta$
are independent from the previous ones.
Pros: step 1 is often practical because both the prior and the likelihood are often easytosample distributions. Cons: the clear shortcoming is that step 2 can be very unlikely and thus we will very rarely (if ever) accept the candidate sample $\theta$
.
This simple implementation of rejection sampling is enough to provide some intuition and motivates the use of more sophisticated and robust sampling algorithms based on Markov chains.
MCMC: The RandomWalk MetropolisHasting algorithm
There is a large family of algorithms that perform MCMC. Most of these algorithms can be expressed at a high level as follows:

Start at current position (i.e. a value for
$\theta$
, say$\theta^{(1)}$
) 
Propose moving to a new position (say,
$\theta^\star$
) 
Accept/Reject the new position based on the position’s adherence to the data and prior distributions

 If you accept: Move to the new position (i.e.
$\theta^{(2)}=\theta^\star$
) and return to Step 1  Else: Do not move to new position. Return to Step 1.
 If you accept: Move to the new position (i.e.

After a large number of iterations, return all accepted positions.
Based on how you implement the above steps you get the various MCMC algorithm. Here we will review the RandomWalk MetropolisHasting algorithm.
As we have seen, the main drawback of the rejection sampling is that it is not efficient – it is unlikely to get exactly $X = x$
, especially when it is highdimensional.
One way around this problem is to allow for “local updates”, i.e. let the proposed value depend on the last accepted value (here is the part where Markov Chains enter the scene).
This makes it easier to come up with a suitable (conditional) proposal, however at the price of yielding a Markov chain, instead of a sequence of independent realizations – putting it simply, a sequence of random variables is a Markov Chain if the future state only depends on the present state.
At first, you find a starting position (can be randomly chosen), lets fix it arbitrarily to
1mu_current = 2.
The critical point is how you propose the new position (that’s the Markov part). You can be very naive or very sophisticated about how you come up with that proposal. The RWMH algorithm is very naive and just takes a sample from a Gaussian distribution (or whatever simmetric distribution you like) centered on the current value with a certain standard deviation, usually called proposal width that will determine how far you propose jumps. In other words, the RWMH proposes a new $\theta^\star$
according to
$$\theta^\star = \theta_{s} + \varepsilon, \quad \varepsilon \sim g$$
where $g$
may be any simmetric distribution. Usually, $g = \mathcal{N}(0, \tau)$
, so that the proposed new value, $\theta^\star$
, is simply a draw from $\mathcal{N}(\theta_{s}, \tau)$
.
1proposal_width = 1.
2mu_proposal = tfd.Normal(mu_current, proposal_width).sample()
Next, you evaluate whether that’s a good place to jump to or not. To evaluate if it is good, you compute the ratio
$$\rho = \frac{P(\theta^\starx)}{P(\theta_sx)} = \frac{P(x\theta^\star) P(\theta^\star)/P(x)}{P(x\theta_s) P(\theta_s)/P(x)} = \frac{P(x, \theta^\star)}{P(x, \theta_s)}$$
Here is the trick: the normalizing constants cancel out. We only have to compute the numerator of the Bayes' formula, that is the product of likelihood and prior. We have seen that it is the same as computing the joint probability distribution – usually, we compute the log joint probability in practise – of the data and the parameter values. TFP performs probabilistic inference by evaluating the model parameters using a joint_log_prob
function that the user as to provide (which we define below).
Then,

If
$\rho\geq1$
, set$\theta^{s+1}=\theta^\star$

If
$\rho<1$
, set$\theta_{s+1}=\theta^\star$
with probability$\rho$
, otherwise set$\theta_{s+1}=\theta_s$
(this is where we use the standard uniform distribution – in practice you draw a sample$u \sim \mathrm{Unif}(0,1)$
and check if$\rho > u$
; if it is you accept the proposal)
To sum up, we accept a proposed move to $\theta^\star$
whenever the density of the (unnormalzied) joint distribution evaluated at $\theta^\star$
is larger than the value of the unnormalized joint distribution evaluated at $\theta_s$
– so $\theta$
will more often be found in places where the unnormalized joint distribution is denser.
If this was all we accepted, $\theta$
would get stuck at a local mode of the target distribution, so we also accept occasional moves to lower density regions.
NOTE: The model we define enters the inference scheme only when we evaluate the proposal. In other words, the model we define is important made explicit in the definition of the joint_log_prob
function, that is
joint_log_prob = model definition
Let’s now define the joint log probability of the normal model above.
1# definition of the joint_log_prob to evaluate samples
2def joint_log_prob(data, proposal):
3 prior = tfd.Normal(mu_0, sigma_0, name='prior')
4 likelihood = tfd.Normal(proposal, sigma, name='likelihood')
5
6 return prior.log_prob(proposal) + tf.reduce_mean(likelihood.log_prob(data))
Let’s evaluate the proposal above, i.e. mu_proposal
1# compute acceptance ratio
2p_accept = joint_log_prob(observed, mu_proposal) / joint_log_prob(observed, mu_current)
3print('Acceptance probability:', p_accept.numpy())
Acceptance probability: 1.0373609
It is more than 1, therefore we accept directly. Imagine that p_accept
was $0.8$
, then we would have drawn a sample from the uniform distribution and check the following
1if p_accept > tfd.Uniform().sample():
2 mu_current = mu_proposal
3 print('Proposal accepted')
4else:
5 print('Proposal not accepted')
Proposal accepted
At this point we would restart the process again.
TFP implementation
In TFP the algorithm is implemented as follows.
First we define how the step should be taken, i.e. how the proposal should be made. Since we are implementing the RWMH algorithm we use the function tfp.mcmc.RandomWalkMetropolis
. It takes as argument the unnormalized join distribution that it will use to compute the acceptance ratio. The only thing we have to remenber is that we have to “lock the data” or “define a closure” over our joint_log_prob function. In other words, fix the data input of the function joint_log_prob
1# define a closure on joint_log_prob
2def unnormalized_log_posterior(proposal):
3 return joint_log_prob(data=observed, proposal=proposal)
Now we can pass the unnormalized_log_posterior
as the argument of the function which implements the step
1rwm = tfp.mcmc.RandomWalkMetropolis(
2 target_log_prob_fn=unnormalized_log_posterior
3)
Secondly, we have to define the initial state of the chain, say $\theta_0$
. We choose this arbitrarily.
1initial_state = tf.constant(0., name='initial_state')
Finally, we can sample the chain with the function
tf.mcmc.sample_chain
, which returns the samples (named trace
usign the usual stat lingo) and some additional information regarding the procedure implemented (kernel_results
)
1trace, kernel_results = tfp.mcmc.sample_chain(
2 num_results=10**5,
3 num_burnin_steps=5000,
4 current_state=initial_state,
5 num_steps_between_results=1,
6 kernel=rwm,
7 parallel_iterations=1
8)
However, to take full advantage of TF, we will enclose this sampling process into a function and we will decorate it with
tf.function
1@tf.function
2def run_chain():
3 samples, kernel_results = tfp.mcmc.sample_chain(
4 num_results=10**5,
5 num_burnin_steps=5000,
6 current_state=initial_state,
7 kernel=rwm,
8 parallel_iterations=1,
9 trace_fn=lambda _, pkr: pkr)
10
11 return samples, kernel_results
Note: To print the code generated by
tf.function
onfn
, use
1 tf.autograph.to_code(fn.python_function)
1trace, kernel_results = run_chain()
2plt.plot(trace);
1sns.distplot(prior.sample(10**5))
2sns.distplot(posterior.sample(10**5))
3sns.distplot(trace)
4sns.despine()
5plt.legend(labels=['Prior','Analytic Posterior', 'MCMC Posterior'])
6plt.xlim(5, 7);
As you can see, even after $10^5$
samples, the MCMC posterior is not even close to the true posterior. That’s normal since the RWMH algorithm is not very efficient: it is not a great sampler for this kind of problems. You might need a crazy number of samples before it gets close to the true posterior.
On the other hand, other frameworks like PyMC uses the
NUTS sampler – a kind of adaptive Hamiltonian Monte Carlo method. TFP supports HMC (
tfp.mcmc.HamiltonianMonteCarlo
), but still you might have to tune the step size and leapfrog steps parameters (this is the thing that NUTS does adaptively for you). That alone should get you closer to consistent results.
For more material on this subject consult Thomas Wiecki’s Blog, Bayesian Methods for Hacker book, Duke University STAT course page, and this lecture notes for a technical review of Monte Carlo Methods. The material covered here was inspired by Thomas Wiecki’s blogpost.
In a future blogpost I will discuss in more detail both the TFP implemetation of MCMC methods and the diagnostics of the MCMC procedure.
Bonus: PyMC3 implementation with NUTS
Without going into the detail of the procedure (left as a future blogpost), below I implement the same procedure, but using pymc3
and its default sampler (NUTS)
1import pymc3 as pm
1with pm.Model() as model:
2 mu = pm.Normal('mu', mu=4., sigma=2.)
3 x = pm.Normal('observed', mu=mu, sigma=1., observed=observed)
4 trace_pm = pm.sample(10000, tune=500, chains=1)
100%██████████ 10500/10500 [00:05<00:00, 1971.43it/s]
1sns.distplot(posterior.sample(10**5))
2sns.distplot(trace_pm['mu'])
3sns.distplot(trace)
4plt.legend(labels=['Analytic Posterior', 'PyMC Posterior', 'TFP Posterior']);
As you might notice, just after $10^4$
samples, the NUTS is able to retrieve the true posterior (they are in fact indistinguishable).
 Posted on:
 June 19, 2019
 Length:
 14 minute read, 2786 words
 Categories:
 Probabilistic Programming
 Tags:
 Python TensorFlow 2.0 PyMC3
 See Also: