9

我想rstan在 rnotebook中使用模型的估计系数

我有以下stan块:

```{stan output.var="rats"}
data {
  int<lower=0> N;
  int<lower=0> T;
  real x[T];
  real y[N,T];
  real xbar;
}
parameters {
  real alpha[N];
  real beta[N];

  real mu_alpha;
  real mu_beta;          // beta.c in original bugs model

  real<lower=0> sigmasq_y;
  real<lower=0> sigmasq_alpha;
  real<lower=0> sigmasq_beta;
}
transformed parameters {
  real<lower=0> sigma_y;       // sigma in original bugs model
  real<lower=0> sigma_alpha;
  real<lower=0> sigma_beta;

  sigma_y = sqrt(sigmasq_y);
  sigma_alpha = sqrt(sigmasq_alpha);
  sigma_beta =  sqrt(sigmasq_beta);
}
model {
  mu_alpha ~ normal(0, 100);
  mu_beta ~ normal(0, 100);
  sigmasq_y ~ inv_gamma(0.001, 0.001);
  sigmasq_alpha ~ inv_gamma(0.001, 0.001);
  sigmasq_beta ~ inv_gamma(0.001, 0.001);
  alpha ~ normal(mu_alpha, sigma_alpha); // vectorized
  beta ~ normal(mu_beta, sigma_beta);  // vectorized
  for (n in 1:N)
    for (t in 1:T) 
      y[n,t] ~ normal(alpha[n] + beta[n] * (x[t] - xbar), sigma_y);

}
generated quantities {
  real alpha0;
  alpha0 = mu_alpha - xbar * mu_beta;
}
```

我也有以下数据

```{r}
df <- read_delim("https://raw.githubusercontent.com/wiki/stan-dev/rstan/rats.txt",delim = " ")

y <- as.matrix(df)
x <- c(8,15,22,29,36)
xbar <- mean(x)
N <- nrow(y)
T <- ncol(y)
```

github 上的文档rats_fit <- stan(file = 'https://raw.githubusercontent.com/stan-dev/example-models/master/bugs_examples/vol1/rats/rats.stan')显示,但由于我使用的是块,因此我没有要参考的文件。

我已经尝试过stan(rats), summary(rats), print(rats),但这些似乎都不起作用。

4

2 回答 2

8

第一个 RMarkdown 块rats <- rstan::stan_model(model_code=the_text)在幕后调用,因此为了从后验分布中采样,您最终需要执行rats_fit <- sampling(rats, data = list()),其剩余参数与 for 几乎相同stan。但你必须library(rstan)在这一切之前打电话。

于 2018-02-03T19:40:28.527 回答
1

谢谢!在你的帮助下,我想出了以下

library(tidyverse)
df <- read_delim("https://raw.githubusercontent.com/wiki/stan-dev/rstan/rats.txt",delim = " ")
y <- as.matrix(df)
x <- c(8,15,22,29,36)
xbar <- mean(x)
N <- nrow(y)
T <- ncol(y)
library(rstan)
options(mc.cores = parallel::detectCores())
rats_fit <- rstan::sampling(rats, 
                     data = list(y,x,xbar,N,T))
rstan::summary(rats_fit)
于 2018-02-04T01:24:28.780 回答