Chapter 6: Posterior approximation with the Gibbs sampler
Jesse Mu
2016-11-04
1 A semiconjugate prior distribution
In Chapter 5, we performed two-parameter inference by decomposing the prior \(p(\theta, \sigma^2) = p(\theta \mid \sigma^2) p(\sigma^2)\). So our prior distribution on \(\theta\) relates to the variance \(\sigma^2\):
However, consider that we may want to decouple the priors of the two parameters. This allows flexibility with specification of the prior (initial estimate and confidence) of either parameter.
Consider the midge wing example: we picked a prior on \(\theta\) that was centered around 1.9 (our prior expectation) but with most of its mass above 0, since wing lengths cannot be above 0. We can’t freely do this from what we know in section 5 (i.e. setting \(\tau_0^2 = \sigma^2 / \kappa_0\)). Alternatively, we can set \(\tau_0^2\) to be whatever we want, but then there is no longer a known form of the joint posterior
The numerator here is often easy to calculate, but the denominator is often prohibitively hard to compute. When the numerator is not known to be proportional to a known probability distribution, we can’t get the full joint density without the denominator.
Notice however that we can still evaluate relative probabilites of \(\boldsymbol{\theta}_a\) and \(\boldsymbol{\theta}_b\), as their ratio cancels out the integral. More generally, we can create a discrete approximation of the probabilities by evaluating the numerator of this density for values of \(\boldsymbol{\theta}\) across an \(n\)-dimensional grid, then dividing each of these unnormalized densities by the sum of the entire grid.
Funnily, this is pretty much what I have been doing in the past chapters when plotting heatmaps:
[R code]
y =c(1.64, 1.70, 1.72, 1.74, 1.82, 1.82, 1.82, 1.90, 2.08)n =length(y)ybar =mean(y)s2 =var(y)# Priormu0 =1.9# Tau chosen such that most of the mass of the normal distribution > 0t20 =0.95^2s20 =0.01nu0 =1Theta =seq(1.505, 2, length =100)Sigma2 =seq(0.005, 0.05, length =100)# This calculates p(sigma2, theta, y_1, \dots, y_n)library(invgamma)post.func =Vectorize(function(theta, sigma2) {dnorm(theta, mu0, sqrt(t20)) *dinvgamma(sigma2, nu0 /2, s20 * nu0 /2) *prod(dnorm(y, theta, sqrt(sigma2)))})d =outer(Theta, Sigma2, post.func)rownames(d) = Thetacolnames(d) = Sigma2d = d /sum(d)df =as.data.frame(d) |> tibble::rownames_to_column('theta') |>pivot_longer(cols =-theta, names_to ='sigma2', values_to ='density') |>mutate(theta =as.numeric(theta), sigma2 =as.numeric(sigma2))ggplot(df, aes(x = theta, y = sigma2, z = density)) +geom_contour(aes(color = ..level..))
3 Sampling from the conditional distributions
Again, to proceed with Gibbs sampling, we simply need to calculate the full conditional distributions of the parameters. We already computed the full conditional for \(\theta \mid \sigma^2, y_1, \dots, y_n\) in 5.2. For \(\theta
\mid \mathcal{N}(\mu_0, \tau_0^2)\), then \(\theta \mid \sigma^2, y_1, \dots, y_n
\sim \mathcal{N}(\mu_n, \tau_n^2)\), where \(\mu_n\) and \(\tau_n^2\) are not reproduced here (see 5.2).
Now we find the full conditional for \(\sigma^2\) using the exact same method as in 5.2:
So \(\sigma^2 \sim \text{inverse-gamma}(\nu_n / 2, \nu_n \sigma_n^2(\theta) /
2)\), and \(\tilde{\sigma^2} \sim \text{gamma}(\cdot, \cdot))\), with the parameters:
\(\nu_n = \nu_0 + n\)
\(\sigma_n^2(\theta) = (\sigma_0^n \nu_0 + n s_n^2(\theta)) / \nu_n\)
We denote \(\sigma_n^2(\theta)\), \(s_n^2(\theta)\) to indicate that \(\sigma_n^2\) is dependent on \(\theta\) which is assumed known.
A shortcut for thinking about full conditionals, instead of explicitly decomposing the probability according to Bayes rule each time, is to write the numerator of the full joint posterior \(p(\boldsymbol{\theta} \mid \mathbf{y})\). Then, if you are interested in the full conditional of \(p(\theta_i \mid
\mathbf{y})\), simply evaluate the full joint posterior while treating all \(\theta_j\) for \(j \neq i\) as constants (and thus discardable to maintain proportionality). This is used in later chapters (e.g. 8.3.1)
4 Gibbs sampling
From this, Gibbs sampling proceeds as follows:
Begin with start values \(\theta_i^{(0)}\) for all \(i\). Usually these can be standard naive estimates of the parameters. Also, you technically only have to have start values for all but one parameter, because now…
(WOLOG) Sample \(\theta_1^{(1)} \sim p(\theta_1 \mid \theta_2^{(0)}, \dots,
\theta_n^{(0)}, \dots)\) (the full conditional)
\(\boldsymbol{\theta}^{(1)} = \begin{pmatrix} \theta_1^{(1)} & \cdots & \theta_n^{(1)} \end{pmatrix}\) is your first Gibbs sample.
Given Gibbs sample \(\boldsymbol{\theta}^{(s)}\), for further samples, sample each \(\theta_i^{(s + 1)}\) individually as before, conditioning on the \(\theta_i^{(s)}\) of the previous gibbs sampling \(\boldsymbol{\theta}^{(s)}\)and the new samples \(\theta_i^{(s + 1)}\) as they are received. Then \(\boldsymbol{\theta}^{(s + 1)} = \begin{pmatrix} \theta_1^{(s + 1)} & \cdots & \theta_n^{(s + 1)} \end{pmatrix}\) is the \(s + 1\)th Gibbs sample.
Notice that the \(s + 1\)th sample is only conditionally dependent on the \(s\)th sample, hence the term “Markov Chain Monte Carlo”. Once these samples are obtained, you can treat them like a standard Monte Carlo sample, and compute all of the desired quantities.
The following is an example for our midge length data:
[R code]
S =1000PHI =matrix(nrow = S, ncol =2)PHI[1, ] = phi =c(ybar, 1/ s2) # Start with sample mean + varianceset.seed(1) # Reproducibility# Should use a for loop, as there are variables we need to keep track of through# iterationsfor (s in2:S) {# Sample theta based on \sigma^2 (phi[2])# According to normal(\mu_n, \tau^2_n) where \mu_n and \tau^2_n are as below mun = (mu0 / t20 + n * ybar * phi[2]) / (1/t20 + n * phi[2]) t2n =1/ (1/ t20 + n * phi[2]) phi[1] =rnorm(1, mun, sqrt(t2n))# Sample 1/sigma^2 based on \theta nun = nu0 + n s2n = (nu0 * s20 + (n -1) * s2 + n * (ybar - phi[1])^2) / nun# This posterior distribution: inverse-gamma(\nu_n / 2, \sigma^2_n(\theta)# \nu_n / 2) phi[2] =rgamma(1, nun /2, s2n * nun /2) PHI[s, ] = phi}
The following are plots of 5, 15, and 100 consecutive Gibbs samples for \(\theta\) and \(\tilde{\sigma^2}\):
This is the scatterplot of all 1000 of our Gibbs samples:
[R code]
ggplot(phi.df, aes(x = theta, y =`1/sigma^2`)) +geom_point()
Finally, some quantiles:
[R code]
# CI for population mean - first column is thetaquantile(PHI[, 1], c(0.025, 0.5, 0.975))#> 2.5% 50% 97.5% #> 1.707282 1.804348 1.901129# CI for population precision, second columnquantile(PHI[, 2], c(0.025, 0.5, 0.975))#> 2.5% 50% 97.5% #> 17.48020 53.62511 129.20020# CI for population stddev, arbitrary function of second columnquantile(1/sqrt(PHI[, 2]), c(0.025, 0.5, 0.975))#> 2.5% 50% 97.5% #> 0.08797701 0.13655763 0.23918408# For latermidge.df = phi.df
5 General properties of the Gibbs sampler
Under conditions that will be met for our models, like the law of large numbers for standard monte carlo sampling, a sufficient number of Gibbs samples approaches the target distribution. The question of course is how many samples is enough, which is covered in the next section.
Another important point is that Gibbs sampling is not a Bayesian model. These two concepts should be separated: Gibbs sampling is a general framework for “observing” the posterior probability distribution, whatever that distribution is.
6 Introduction to MCMC diagnostics
For an example of the importance of assessing convergence of Gibbs sampling, consider the following target distribution, a 45-10-45 mixture of \(\mathcal{N}(-3, 1/3), \mathcal{N}(0, 1/3), \mathcal{N}(3, 1/3)\):
A Gibbs sampler to obtain samples from this is:
[R code]
# Gibbs sampling with S = 1000S =1000PHI =matrix(nrow = S, ncol =2)# Let delta0 = 2 and theta0 = 0PHI[1, ] = phi =c(2, 0)set.seed(1) # Reproducibility# Should use a for loop, as there are variables we need to keep track of through# iterationsfor (s in2:S) {# Sample delta s+1 based on theta s probs =sapply(1:3, function(d) { PROB.DENS[d] *dnorm(phi[2], MU.DENS[d], sqrt(S2.DENS[d])) }) probs = probs /sum(probs) phi[1] =sample.int(3, size =1, prob = probs)# Sample theta s+1 based on delta (easy) phi[2] =rnorm(1, MU.DENS[phi[1]], sqrt(S2.DENS[phi[1]])) PHI[s, ] = phi}theta.mcmc =data.frame(PHI)colnames(theta.mcmc) =c('delta', 'theta')theta.mcmc$iteration =1:nrow(theta.mcmc)# How well does this work?ggplot(theta.dist, aes(x = theta, y = density)) +geom_histogram(mapping =aes(x = theta, y = ..density..), data = theta.mcmc,color ='black', fill ='grey') +geom_line()
Notice that the histogram does not adequately approximate the distribution. Try changing the number of samples to 10000 or 100000, which should be better.
The problem is that since the sampler generates dependent samples, the sampler sticks in high probability regions for a long time. After sufficient samples, this balances out, but sometimes the number of samples required may be very large.
Getting it right
Estimate of MCMC depends on autocorrelation: how correlated a chain of values is with itself. We prefer low correlation values. The acf function can be used to assess this: each bar represents the autocorrelation for varying levels of lag, where “lag” is the gap in subsequent samples.
[R code]
acf(theta.mcmc$theta, lag.max =50)
Another thing we can do is obtain the “effective sample size” of the MCMC sample. This exploits the fact that with \(n\) samples of a value \(\theta\) the following
only holds if the autocorrelation of the samples is zero. If there is positive autocorrelation in the samples, the variance of the sample mean increases, which “reduces” \(n\). So by obtaining estimates of the variance of the population (by estimating the variance of the sample) and estimates of the variance of the mean, we can solve for \(n\) which is an “effective sample size”.
Estimating the variance of the mean, given that we cannot assume an independent sample, is nontrivial, and requires calculating the spectral density estimate at frequency zero (Marmer 2010) which is “a convenient way to represent the sequence of autocovariances” of a stochastic process, and is related to 1) autocorrelation, and 2) Fourier transformation.
This is implemented as the effectiveSize function in R, which abridged looks like this:
ggplot(midge.df, aes(x = iteration, y =`1/sigma^2`)) +geom_point() +geom_line(alpha =0.25)
By viewing the autocorrelation function and effective sample sizes of our data, we can see that the samples look quite good and seem to have reasonable effective sample sizes.
Since \(a_\gamma\) and \(b_\gamma\) are equal, the gamma distribution is centered around 1 and the magnitude represents the strength of our belief that \(\gamma\) (the proportion \(\theta_B / \theta_A\)) is 1. As expected, as our belief in that increases, the mean posterior difference between \(\theta_B\) and \(\theta_A\) decreases.
These samples are actually highly autocorrelated, hence the minimum effective sample sizes. However, the purpose of calculating the autocorrelation of the minimum and maximum \(\theta\) is unclear.
d
[R code]
YCOMP =rbind(data.frame(y = YPRED, dataset ='predictive'), data.frame(y = Y, dataset ='original'))ggplot(YCOMP, aes(x = y, fill = dataset)) +geom_density(alpha =0.5)
Based on the very close correspondence with the densities of the original and posterior predictive dataset, it seems like this mixture model fits very well.