我想对具有不同较低测量阈值的计数数据使用相同的模型。截短的泊松模型使我可以做到这一点。
可以在R中成功定义模型。但是我无法将同一模型转换为JAGS。问题似乎在于,在定义可能性时,不可能用CDF划分PDF。
这是我尝试过的:
数据
set.seed(42)
N <- 10000
x1 <- runif(N, -1, 1)
lower_limit = 7
upper_limit = Inf
b0 <- 0.5
b1 <- 1.3
b2 <- 0.1
true_lambda <- exp(b0 + b1 * x1 + b2 * x1^2)
# extraDistr::dtpois behaves exactly like the truncated poisson defined below
y <- extraDistr::rtpois(N, lambda = true_lambda, a = lower_limit, b = upper_limit)
summary(y)
Min. 1st Qu. Median Mean 3rd Qu. Max.
8.000 8.000 8.000 8.354 8.000 16.000
hist(y)
对于模型,我使用了可以通过以下方式用基数R定义的截断的泊松分布:
trunc <- function(x,s, lambda, log){
out <- dpois(x, lambda)/(1-ppois(s, lambda))
if(log){
out <- log(out)
}
return(out)
}
optfun <- function(data, par){
b0 <- par[1]
b1 <- par[2]
b2 <- par[3]
loglikelihood <- sum(trunc(
x = data,
lambda = exp(b0 + b1 * x1 + b2 * x1^2),
s = lower_limit,
log = T
))
return(-loglikelihood)
}
output <- optim(par = rep(0, 3),
fn = optfun2,
data = y)
output$par
[1] 0.4808197 1.3141579 0.1097217
但是,我想在JAGS中定义相同的模型:
Model.Data <- list(
y = y,
N = N,
s = rep(lower_limit,N),
x1 = x1
)
sink("trunc_pois.txt")
cat(
"
model{
# Likelihood data model:
for (i in 1:N) {
# truncated poisson in JAGS:
y[i] ~ dpois(lambda_fit[i])/(1-ppois(s[i],lambda_fit[i]))
log(lambda_fit[i]) <- b0 + b1 * x1[i] + b2 * pow(x1[i],2)
}
# Priors:
b0 ~ dnorm(0, 0.0001) # mean, precision = N(0, 10^4)
b1 ~ dnorm(0, 0.0001)
b2 ~ dnorm(0, 0.0001)
}
"
)
sink()
inits.fn <- function() list(
b0 = rnorm(1),
b1 = rnorm(1),
b2 = rnorm(1)
)
jagsModel <- rjags::jags.model(file = "trunc_pois.txt", data = Model.Data,
inits = inits.fn,n.chains = 3, n.adapt = 100)
这会给我以下错误消息:
Error in rjags::jags.model(file = "trunc_pois.txt", data = Model.Data, :
Error parsing model file:
syntax error on line 7 near "/"
有没有办法在JAGS中定义截短的泊松模型?我应该使用T()以某种方式截断泊松模型吗?