I'm incorporating a Bayesian Model Averageing(BMA) approach in my research and strapped in trapped in the estimated of Pr(theta|D). Professor John K. Kruschke(2014)'s book in chapter 10 offers an example to compute model posterior probability using hierarchical MCMC, but I do not know how to set the index value of model(m) using this method to linear regression. Here is the code
library(BMS)
data(attitude)
#show the model posterior probability of four combination of variable compaints and #privileges
bma4c = bms(rating ~complaints + privileges , data = attitude)
pmp.bma(bma4c)
I want use hierarchical MCMC method to get the similar results.
# The date
library(rjags)
dataList <- list( N = nrow(attitude),
y =attitude$rating,
x = attitude$complaints,
z = attitude$privileges)
#The model
modelString = "
model {
for ( i in 1:N ) {
y[i] ~ dnorm( mu[i,m] , tau )
mu[i,1] <- beta0 + beta1 *x
mu[i,2] <- beta0
mu[i,3] <- beta0 + beta2 *z
mu[i,4] <- beta0 + beta2 *z +beta1 *x
}
tau <- 1/100
mu[] <- equals(m,1)*mu[,1] + equals(m,2)*mu[,2] + equals(m,3)*mu[,3] + equals(m,4)*mu[,4]
# this sentence cause the error <Cannot evaluate subset expression for mu>
beta0 ~ dnorm(0 , 1.0E-12)
beta1 ~ dnorm(0 , 1.0E-12)
beta2 ~ dnorm(0 , 1.0E-12)
m ~ dcat(mPrior[])
mPrior[1] <- 0.25
mPrior[2] <- 0.25
mPrior[3] <- 0.25
mPrior[4] <- 0.25
}"
writeLines( modelString , con="TEMPmodel.txt" )
# RUN THE CHAINS.
parameters = c("theta","m")
adaptSteps = 1000 # Number of steps to "tune" the samplers.
burnInSteps = 1000 # Number of steps to "burn-in" the samplers.
nChains = 4 # Number of chains to run.
numSavedSteps=50000 # Total number of steps in chains to save.
thinSteps=1 # Number of steps to "thin" (1=keep every step).
nPerChain = ceiling( ( numSavedSteps * thinSteps ) / nChains ) # Steps per chain.
# Create, initialize, and adapt the model:
jagsModel = jags.model( "TEMPmodel.txt" , data=dataList ,
n.chains=nChains , n.adapt=adaptSteps )
# Burn-in:
update( jagsModel , n.iter=burnInSteps )
# The saved MCMC chain:
codaSamples = coda.samples( jagsModel , variable.names=parameters ,
n.iter=nPerChain , thin=thinSteps )
mcmcMat = as.matrix( codaSamples , chains=TRUE )
m = mcmcMat[,"m"]
# compute the model posterior probability
pM1 = sum( m == 1 ) / length( m )
pM2 = sum( m == 2 ) / length( m )
pM3 = sum( m == 3 ) / length( m )
pM4 = sum( m == 4 ) / length( m )
Does anyone know how to modify this code to get the relative model probability?