=c('pD', 'deviance', 'var1', ...)
varnames<- jags.samples(model, varnames, n.iter, thin, type = "trace") out
Get Deviance Information Criterion (DIC) when sampling in JAGS
Get Deviance Information Criterion (DIC) when sampling in JAGS
I use the rjags package from R to sample with JAGS. When sampling with the coda.samples() function, there is no way of getting the DIC from these samples (you need to use another run with dic.samples(). When using jags.samples(), it is possible to include deviance and pD in the variable-names array
but the resulting structure is awkward to handle and even more awkward to transfer to the nice coda-structure that allows to use all the nice plotting/diagnostic functions.
For complex models, the resulting overhead can be severe and I therefore set up a coda.samples.dic() function that returns both the coda-structure for the mcmc samples and the dic (the solution is inspired by a discussion in the JAGS forum):
<- function (model, variable.names = NULL, n.iter, thin = 1, ...)
coda.samples.dic
{load.module('dic') # necessary for pD and deviance monitor
<- model$iter() + thin
start =c(variable.names, c('deviance', 'pD'))
varnames<- jags.samples(model, varnames, n.iter, thin,
out type = "trace", ...)
<- out$deviance
deviance <- out$pD
pD $deviance <- NULL
out$pD <- NULL
out<- vector("list", nchain(model))
ans for (ch in 1:nchain(model)) {
<- vector("list", length(out))
ans.ch <- NULL
vnames.ch for (i in seq(along = out)) {
<- names(out)[[i]]
varname <- dim(out[[i]])
d if (length(d) < 3) {
stop("Invalid dimensions for sampled output")
}<- d[1:(length(d) - 2)]
vardim <- prod(vardim)
nvar <- d[length(d) - 1]
niter <- d[length(d)]
nchain <- as.vector(out[[i]])
values <- matrix(NA, nrow = niter, ncol = nvar)
var.i for (j in 1:nvar) {
<- values[j + (0:(niter - 1)) * nvar +
var.i[, j] - 1) * niter * nvar]
(ch
}<- c(vnames.ch, coda.names(varname, vardim))
vnames.ch <- var.i
ans.ch[[i]]
}<- do.call("cbind", ans.ch)
ans.ch colnames(ans.ch) <- vnames.ch
<- mcmc(ans.ch, start = start, thin = thin)
ans[[ch]]
}
<- list(deviance = mean(as.vector(deviance)), penalty = mean(as.vector(pD)), type = 'pD')
dic class(dic) <- "dic"
return(list(samples=mcmc.list(ans), dic=dic))
}
This code is just a copy of coda.samples() source code.
Changes: include "deviance" and "pD" in sampling:
=c(variable.names, c('deviance', 'pD'))
varnames<- jags.samples(model, varnames, n.iter, thin,
out type = "trace", ...)
<- out$deviance
deviance <- out$pD
pD $deviance <- NULL
out$pD <- NULL out
and return as dic structure
<- list(deviance = mean(as.vector(deviance)), penalty = mean(as.vector(pD)), type = 'pD')
dic class(dic) <- "dic"
return(list(samples=mcmc.list(ans), dic=dic))
You need to run the sampler with more than one chain, though.