The purpose of this is twofold: First to illustrate how MCMC algorithms are easy to implement (at least in principle) in situations where classical Monte Carlo methods do not work and second to provide a glimpse of practical MCMC implementation issues. It is difficult to work through a truly complex example of a Metropolis-Hastings algorithm in a short tutorial. Our example is therefore necessarily simple but working through it should provide a beginning MCMC user a taste for how to implement an MCMC procedure for a problem where classical Monte Carlo methods are unusable.

Monte Carlo works as follows: Suppose we want to estimate an expectation of a function g(x) with respect to the probability distribution f. We denote this desired quantity m= E

A toy example to calculate P(-1 < X < 0) when X is a Normal(0,1) random variable:

xs <- rnorm(10000) # simulate 10,000 draws from N(0,1) xcount <- sum((xs>-1) & (xs<0)) # count number of draws between -1 and 0 xcount/10000 # Monte Carlo estimate of probability pnorm(0)-pnorm(-1) # Compare it to R's answer (cdf at 0) - (cdf at -1)R has random number generators for most standard distributions and there are many more general algorithms (such as rejection sampling) for producing independent and identically distributed (i.i.d.) draws from f. Another, very general approach for producing non i.i.d. draws (approximately) from f is the Metropolis-Hastings algorithm.

Aside: A powerful technique for estimating expectations is

The raw data, which arrives approximately according to a Poisson process, gives the individual photon arrival times (in seconds) and their energies (in keV). The processed data we consider here is obtained by grouping the events into evenly-spaced time bins (10,000 seconds width).

Our goal for this data analysis is to identify the change point and estimate the intensities of the Poisson process before and after the change point.

We describe a Bayesian model for this change point problem (Carlin and Louis, 2000). Let Y

We first read in the data:

chptdat <- read.table("COUP551_rates.dat",skip=1, head=T)We can begin with a simple time series plot as exploratory analysis.

Y <- chptdat[,2] # store data in Y ts.plot(Y,main="Time series plot of change point data")The plot suggests that the change point may be around 10.

Please save code from the MCMC template in R into a file and open this file using the editor. Save this file as MCMCchpt.R .

Note that in this version of the code, all parameters are sampled except for k (which is fixed at our guessed change point).

To load the program from the file MCMCchpt.R we use the "source" command. (Reminder: It may be helpful to type:

source("MCMCchpt.R") # with appropriate filepathname source("batchmeans.R") # with appropriate filepathnameWe can now run the MCMC algorithm:

mchain <- mhsampler(NUMIT=1000,dat=Y) # call the function with appropriate arguments

mean(mchain[1,]) # obtain mean of first row (thetas)To get estimates for means for all parameters:

apply(mchain,1,mean) # compute means by row (for all parameters at once) apply(mchain,1,median) # compute medians by row (for all parameters at once)To obtain an estimate of the entire posterior distribution:

plot(density(mchain[1,]),main="smoothed density plot for theta posterior") plot(density(mchain[2,]),main="smoothed density plot for lambda posterior") hist(mchain[3,],main="histogram for k posterior")To find the (posterior) probability that lambda is greater than 10:

sum(mchain[2,]>10)/length(mchain[2,])Now comment the line that fixes k at our guess (add the # mark):

# currk <- KGUESSRerun the sampler with k also sampled.

mchain <- mhsampler(NUMIT=1000,dat=Y)With the new output, you can repeat the calculations above (finding means, plotting density estimates etc.)

You can also study how your estimate for the expectation of the posterior distribution for k changes with each iteration.

estvssamp(mchain[3,])We would like to assess whether our Markov chain is moving around quickly enough to produce good estimates (this property is often called 'good mixing'). While this is in general difficult to do rigorously,

acf(mchain[1,],main="acf plot for theta") acf(mchain[2,],main="acf plot for lambda") acf(mchain[3,],main="acf plot for k") acf(mchain[4,],main="acf plot for b1") acf(mchain[5,],main="acf plot for b2")If the samples are heavily autocorrelated we should rethink our sampling scheme or, at the very least, run the chain for much longer. Note that the autocorrelations are negligible for all parameters except k which is heavily autocorrelated. This is easily resolved for this example since the sampler is fast (we can run the chain much longer very easily). In problems where producing additional samples is more time consuming, such as complicated high dimensional problems, improving the sampler `mixing' can be much more critical.

Why are there such strong autocorrelations for k? The acceptance rate for k proposals (printed out with each MCMC run) are well below 10% which suggests that k values are stagnant more than 90% of the time. A better proposal for the Metropolis-Hastings update of a parameter can help improve acceptance rates which often, in turn, reduces autocorrelations. Try another proposal for k and see how it affects autocorrelations. In complicated problems, carefully constructed proposals can have a major impact on the efficiency of the MCMC algorithm.

mchain2 <- mhsampler(NUMIT=1000,dat=Y)You can study how your estimate for the expectation of the posterior distribution for k changes with each iteration.

estvssamp(mchain2[3,])

Regarding (1): Computing standard errors for a Monte Carlo estimate for an i.i.d. (classical Monte Carlo) sampler is easy, as shown for the toy example on estimating P(-1 < X < 0) when X is a Normal(0,1) random variable. Simply obtain the sample standard deviation of the g(x

There are many ways to compute Monte Carlo standard errors. See, for instance, Practical Markov chain Monte Carlo and the references therein. We describe a simple but reasonable way of calculating it: the consistent batch means method in R and a brief description (pdf) .

To compute MC s.error via batch means, download the bm function from the batchmeans.R file above and source the file into R. We can now calculate standard error estimates for each of the five parameter estimates:

bm(mchain[1,]) bm(mchain[2,]) bm(mchain[3,]) bm(mchain[4,]) bm(mchain[5,])Are these standard errors acceptable ?

There is a vast literature on different proposals for dealing with the latter issue (how long to run the chain) but they are all heuristics at best. The links at the bottom of this page (see section titled "Some resources") provide references to learn more about suggested solutions. One method that is fairly simple, theoretically justified in some cases and seems to work reasonably well in practice is as follows: run the MCMC algorithm and periodically compute Monte Carlo standard errors. Once the Monte Carlo standard errors are below some (user-defined) threshold, stop the simulation. Often MCMC users do not run their simulations long enough. For complicated problems run lengths in the millions (or more) are typically suggested (although this may not always be feasible). For our example run the MCMC algorithm again, this time for 100000 iterations (set NUMIT=100000).

mchain2 <- mhsampler(NUMIT=100000,dat=Y)You can now obtain estimates of the posterior distribution of the parameters as before and compute the new Monte Carlo standard error. Note whether the estimates and corresponding MC standard error have changed with respect to the previous sampler.

An obvious modification to this model would be to allow for more than one change point. A very sophisticated model that may be useful in many change point problems is one where the number of change points is also treated as unknown. In this case the

In addition to deciding how long to run the sampler and how to compute Monte Carlo standard error, there are many possibilities for choosing how to update the parameters and more sophisticated methods used to make the Markov chain move around the posterior distribution efficiently. The literature on such methods is vast. The following references are a useful starting point.