7.3 The Metropolis-Hastings algorithm

  • step 1: ok : q(μproposal|μ)

  • step 2:

    • we are going to calculate an acceptance probability:

    α={1,f(μproposal)L(μproposal|y)q(μ|μproposal)f(μ)L(μ|y)q(μproposal|μ)}

Because the Uniform proposal model is symmetric:

q(μproposal|μ)=q(μ|μproposal)

Then after multiplying by f(y) we have now:

α=min{1,f(μproposal|y)f(μ|y)}

This ration is equivalent to the unnormalized posterior.

Two scnearios:

  • Scenario 1: f(μproposal|y)f(μ|y) -> α=1 we are moving

  • Scenario 2: $f(_{proposal}|y) < f(|y) $ then we move according to the probability α

one_mh_iteration <- function(w, current){
 # STEP 1: Propose the next chain location
 proposal <- runif(1, min = current - w, max = current + w)
  
 # STEP 2: Decide whether or not to go there
 proposal_plaus <- dnorm(proposal, 0, 1) * dnorm(6.25, proposal, 0.75)
 current_plaus  <- dnorm(current, 0, 1) * dnorm(6.25, current, 0.75)
 alpha <- min(1, proposal_plaus / current_plaus)
 next_stop <- sample(c(proposal, current), 
                     size = 1, prob = c(alpha, 1-alpha))
  
 # Return the results
 return(data.frame(proposal, alpha, next_stop))
}

set.seed(8)
one_mh_iteration(w = 1, current = 3)
##   proposal     alpha next_stop
## 1  2.93259 0.8240205   2.93259