Example 5.2 Suppose that have an iid random sample of size n, x

Example 5.2
Suppose that have an iid random sample of size n, x = (x1 , . . . , xn )T from an Exponential
distribution with parameter θ. Now assume a priori that θ ∼ Gamma(g, h) so that the
posterior is θ|x ∼ Ga(n + g , h + nx̄) distribution.
Suppose that n = 100, x̄ = 0.092, md(x) = 0.065, g = 1 and h = 0.1.
R code
abcmcmc=function (iters,sigma,epsilon,xbar,md,n,g,h)
{
vec=rep(0,iters)
theta=g/h
vec[1]=theta #initialise at prior mean
for (i in 2:iters) {
can = theta+rnorm(1,0,sigma)
z=rexp(n,can)
rho=abs(mean(z)-xbar) #out, below uses this
#rho=abs(median(z)-md) #uncommented for out2
if(rho<=epsilon)
{
laprob = dgamma(can,g,h,log=T)-dgamma(theta,g,h,log=T)
u = runif(1)
if (log(u) < laprob)
{
theta = can
}
}
vec[i] = theta
}
return(vec)
}
out=abcmcmc(iters=10000,sigma=1,epsilon=0.01,xbar=0.092,n=100,g=1,h=0.1)
out2=abcmcmc(iters=10000,sigma=1,epsilon=0.01,md=0.065,n=100,g=1,h=0.1)
par(mfrow=c(2,3))
plot(ts(out),main="theta",xlab="iteration",ylab="value")
acf(out,main="")
hist(out,freq=F,main="theta",xlab="value",ylim=c(0,0.4))
lines(seq(0,20,0.01),dgamma(seq(0,20,0.01),100+1,0.1+100*0.092),type="l")
plot(ts(out2),main="theta",xlab="iteration",ylab="value")
acf(out2,main="")
hist(out2,freq=F,main="theta",xlab="value",ylim=c(0,0.4))
lines(seq(0,20,0.01),dgamma(seq(0,20,0.01),100+1,0.1+100*0.092),type="l")
Output
theta
0
2000
4000
6000
8000
10000
0.3
0.2
Density
0.1
0.0
0.0
8
0.2
10
0.4
ACF
value
0.6
12
0.8
14
0.4
1.0
theta
0
10
iteration
20
30
40
8
10
Lag
12
14
value
theta
0
2000
4000
6000
iteration
8000
10000
0.0
0.0
8
0.2
0.1
0.2
Density
ACF
0.4
12
10
value
0.6
14
0.3
0.8
16
0.4
1.0
theta
0
10
20
Lag
30
40
8
10
12
14
16
value
Figure 1: Output of 10,000 iterations of ABC MCMC with s(x) = x̄ (top) and s(x) =
md(x) (bottom). The actual posterior is given by the solid line.