7.5 A Beta-Binomial example
1 success in 2 trials
Y|π=bin(2,π)
π=Beta(2,3)
We are still playing “pretend”
We are moving for step 1 to an Uniform to a Beta model because we want π to be [0,1]. And we will draw every step from this Beta model. -> change in step 1
α=min{1,f(πproposal|y)q(π)f(π|y)q(πproposal)}
<- function(a, b, current){
one_iteration # STEP 1: Propose the next chain location
<- rbeta(1, a, b)
proposal
# STEP 2: Decide whether or not to go there
<- dbeta(proposal, 2, 3) * dbinom(1, 2, proposal)
proposal_plaus <- dbeta(proposal, a, b) # <- new
proposal_q <- dbeta(current, 2, 3) * dbinom(1, 2, current)
current_plaus <- dbeta(current, a, b) # <- new
current_q <- min(1, proposal_plaus / current_plaus * current_q / proposal_q)
alpha <- sample(c(proposal, current),
next_stop size = 1, prob = c(alpha, 1-alpha))
return(data.frame(proposal, alpha, next_stop))
}
<- function(N, a, b){
betabin_tour # 1. Start the chain at location 0.5
<- 0.5
current
# 2. Initialize the simulation
<- rep(0, N)
pi
# 3. Simulate N Markov chain stops
for(i in 1:N){
# Simulate one iteration
<- one_iteration(a = a, b = b, current = current)
sim
# Record next location
<- sim$next_stop
pi[i]
# Reset the current location
<- sim$next_stop
current
}
# 4. Return the chain locations
return(data.frame(iteration = c(1:N), pi))
}