转换rstan中的变量(贝叶斯分析)

时间:2017-01-24 21:19:38

标签: r bayesian stan

我是贝叶斯分析的新手,我正在尝试使用rstan来估计后密度分布。练习试图重新创建我的大学使用stan给我们的一个例子,但我对如何正确转换变量感到有点困惑。我当前的代码运行时没有错误,但结果与大学给出的结果不一致(虽然很接近),下图是为了清晰,黑色的stan估计。我通过查阅手册和拼凑随机位来获得代码,但特别是我不太确定为什么需要target以及伽玛的转换确实是正确的。任何指导将不胜感激!

型号

enter image description here

Stan Code

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
)

dat

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")
)

---更新解决方案---

本古德里奇指出的问题是我从theta那里得到了伽玛,因为它应该是另一种方式,因为伽玛是我的随机变量。正确的标准代码如下。

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 );
}

1 个答案:

答案 0 :(得分:2)

作为提示,请尝试将gam(ma)放在parameters块中,然后根据您在theta块中的分配声明并定义transformed parameters首先。

Stan的初学者经常假设Stan有能力逻辑地计算出你的Stan程序的含义,当它真正被字面意义地转换为C ++以及来自transformed parameters和{{1}的代码行时块一遍又一遍地执行。

model(ma)或gam是原始参数会产生差异的原因与变量变换原理有关。如果您真的想要,如果您将雅可比行列式项(以日志单位表示)添加到theta,则可以使用原始参数化获得相同的结果,但通过移动target更容易避免这种情况( ma)到gam块和parameterstheta块。有关变量变更原则的详细信息,请参阅此case study