从 Stan 输出中提取平均参数估计 Table

Extracting Mean Parameter Estimates from Stan Output Table

我了解如何从 Stan 模型中提取链,但我想知道是否有任何快速方法来提取默认 Stan 输出中显示的值 table。

这是一些玩具数据

# simulate linear model
a <- 3 # intercept
b <- 2 # slope

# we can have both the predictor and the noise vary
x <- rnorm(28, 0, 1)
eps <- rnorm(28, 0, 2)
y <- a + b*x + eps

当我们分析时

mod <- lm(y ~ x, df)

我们可以从

中提取系数
mod$coefficients

# (Intercept)           x 
#    3.355967    2.151597 

我想知道是否有任何方法可以用 Stan 输出做同样的事情 table

# Step 1: Make List
data_reg <- list(N = 28, x = x, y = y)

# Step 2: Create Model String
write("
      data {
      int<lower=0> N;
      vector[N] x;
      vector[N] y;
      }
      parameters {
      real alpha;
      real beta;
      real<lower=0> sigma;
      }
      model {
      vector[N] mu;
      sigma ~ cauchy(0, 2);
      beta ~ normal(0,10);
      alpha ~ normal(0,100);
      for ( i in 1:N ) {
      mu[i] = alpha + beta * x[i];
      }
      y ~ normal(mu, sigma);
      }
      ", file = "temp.stan")


# Step 3: Generate MCMC Chains
fit1 <- stan(file = "temp.stan",    
             data = data_reg,        
             chains = 2,             
             warmup = 1000,          
             iter = 2000,            
             cores = 2,               
             refresh = 1000) 

现在,当我们调用模型时

fit1

# Output
#         mean se_mean   sd   2.5%    25%    50%    75%  97.5% n_eff Rhat
# alpha   3.33    0.01 0.40   2.57   3.06   3.33   3.59   4.13  1229    1
# beta    2.14    0.01 0.40   1.37   1.89   2.14   2.40   2.98  1470    1
# sigma   1.92    0.01 0.27   1.45   1.71   1.90   2.09   2.51  1211    1
# lp__  -31.92    0.05 1.30 -35.27 -32.50 -31.63 -30.96 -30.43   769    1

有没有办法从上面显示的 table 输出中索引和提取元素?

如果你只想要手段,那么get_posterior_mean功能就可以了。否则,您将 print(fit1)summary(print1) 的结果分配给一个对象,您可以从该对象中提取内容,但最好只执行 as.matrix(fit1)as.data.frame(fit1) 和在结果列上自行计算您想要的任何内容。