Dependent sequence of random variables \(\{x_t\}_{t = 1, \ldots, T}\) taking values in \(\mathcal{X}\)
At each point \(t\), the sequence jumps between states according to transition probability \(\Pr(x_{t} \mid x_{t-1}, \ldots, x_1)\), \(\Pr(x_1 = x) = \pi(x)\)
We will illustrate a Gibbs sampler via the following toy example. Let \(y=(y_1,\dots,y_n)\) be a random sample from the N(\(\mu,\sigma^2\)). Leet’s use the improper prior \(\pi(\mu,\sigma^2)\propto (\sigma^2)^{-1}\) for simplicity.
As shown in class the full conditional distributions for \(\mu\) and \(\sigma^2\) are the N\((\bar{y},\frac{\sigma^2}{n})\) and the IGamma\(\left(n/2, \frac{1}{2}\sum_{i=1}^n(y_i-\mu)^2\right)\) respectively.
We will generate \(1000\) independent N(\(\mu,\sigma^2\)) random variables setting \(\mu\) and \(\sigma^2\) to some values.
Then we will run the Gibbs Sampler for the model above to sample from the posterior of \(\mu\) and \(\sigma\)
Code
Niter =1000# number of MCMC iterationsout_mu =rep(NA,Niter); #vector to store the mu drawsout_sigma2 =rep(NA,Niter); #vector to store the sigma2 drawsmu =20; # initial value for musigma2 =2; # initial value for sigma2xbar =mean(y) # sufficient stat for mualpha = N/2; # alpha parameter of the IGamma full conditional for sigma2#Main loop of Gibbs Samplerfor (iter in1:Niter){# Store mu and sigma2 values out_mu[iter] = mu out_sigma2[iter] = sigma2#update mu given sigma2 (and y) mu =rnorm(1,xbar,sqrt(sigma2/N))#update sigma2 given mu (and y) beta =0.5*sum((y-mu)^2); sigma2 =1/rgamma(1,alpha,beta);}
Gibbs Sampler
Finally we will summarise the posterior output to obtains Bayes estimators and \(95\%\) credible intervals.
Repeat the above exercise for the following model \[
y_i\sim \text{Poisson}(\lambda), \;\;i=1,...,N,
\] with priors \[
\lambda \sim \text{Gamma}(2,\beta),
\]\[
\beta \sim \text{Exponential}(1)
\] It can be shown (good exercise) that the full conditionals for \(\lambda,\beta\) are the Gamma\((2 + \sum_i y_i,n+\beta)\) and the Gamma\((3,1+\lambda)\).