我是贝叶斯分析的新手,正在尝试使用 rstan 来估计后验密度分布。该练习试图重新创建我的大学使用 stan 提供给我们的示例,但我对如何正确转换变量有点困惑。我当前的代码运行没有错误,但结果与大学给出的结果不匹配(尽管很接近),为了清楚起见,下图以黑色显示 stan 估计。我通过查阅手册并将随机位拼凑在一起使代码工作,但特别是我不太确定为什么target
需要以及伽玛的转换是否确实正确。任何指导将不胜感激!
模型
斯坦代码
data {
int<lower=0> I;
int<lower=0> n[I];
int<lower=0> x[I];
real<lower=0> a;
real<lower=0> b;
real m;
real<lower=0> p;
}
parameters {
real<lower=0> lambda;
real mu;
real<lower=0, upper=1> theta[I];
}
transformed parameters {
real gam[I];
for( j in 1:I)
gam[j] = log(theta[j] / (1-theta[j])) ;
}
model {
target += gamma_lpdf( lambda | a, b);
target += normal_lpdf( mu | m , 1/sqrt(p));
target += normal_lpdf( gam | mu, 1/sqrt(lambda));
target += binomial_lpmf( x | n , theta);
}
R代码
library(rstan)
fit <- stan(
file = "hospital.stan" ,
data = dat ,
iter = 20000,
warmup = 2000,
chains = 1
)
数据
structure(
list(
I = 12L,
n = c(47, 211, 810, 148, 196, 360, 119, 207, 97, 256, 148, 215),
x = c(0, 8, 46, 9, 13, 24, 8, 14, 8, 29, 18, 31),
a = 2,
b = 2,
m = 0,
p = 0.01),
.Names = c("I", "n", "x", "a", "b", "m", "p")
)
---更新解决方案---
Ben Goodrich 指出的问题是我从 theta 推导出 gamma,因为它应该是相反的,因为 gamma 是我的随机变量。正确的 stan 代码如下。
data {
int<lower=0> I;
int<lower=0> n[I];
int<lower=0> x[I];
real<lower=0> a;
real<lower=0> b;
real m;
real<lower=0> p;
}
parameters {
real<lower=0> lambda;
real mu;
real gam[I];
}
transformed parameters {
real<lower=0 , upper=1> theta[I];
// theta = inv_logit(gam); // Alternatively can use the in-built inv_logit function which is vectorised
for(j in 1:I){
theta[j] = 1 / ( 1 + exp(-gam[j]));
}
}
model {
target += gamma_lpdf( lambda | a, b);
target += normal_lpdf( mu | m , 1/sqrt(p));
target += normal_lpdf( gam | mu, 1/sqrt(lambda));
target += binomial_lpmf( x | n , theta );
}