我在R中通过rstan包使用stan。下面是我的模型。这个模型有一个交互术语,叫做X1 * X2
library(rstan)
library(bayesrules)
data(weather_WU); head(weather_WU, 20)
MCMC_Regression_Model =
"
data {
int<lower = 0> n;
vector[n] Y;
vector[n] X1;
vector[n] X2;
}
parameters {
real beta0;
real beta1;
real beta2;
real beta3;
real<lower = 0> sigma;
}
model {
Y ~ normal(beta0 + beta1 * X1 + beta2 * X2 +
beta3 * X1 .* X2, sigma);
beta0 ~ normal(25, 5);
beta1 ~ normal(0, 37.52);
beta2 ~ normal(0, 0.82);
beta3 ~ normal(0, 0.55);
sigma ~ exponential(0.13);
}
"
MCMC_Regression_SIMU =
stan(model_code = MCMC_Regression_Model,
data = list(n = nrow(weather_WU),
Y = weather_WU[['temp9am']],
X1 = weather_WU[['location']],
X2 = weather_WU[['humidity9am']]
),
chains = 4,
iter = 5000 * 2,
seed = 84735
)这样,我就得到了下面的错误
Error in mod$fit_ptr() :
Exception: variable does not exist; processing stage=data
initialization; variable name=X1; base type=vector_d (in
'model1e9057045768_9ae288549657a6a89a994b0dc81a6d24' at
line 5)这个错误表明variable does not exist,但是,变量在定义中几乎是存在的。
如果你能帮助我正确运行上面的代码,我将不胜感激。
发布于 2021-09-23 21:40:12
我得到了基本上相同的错误(在重新安装rstan之后)-不同的散列,但相同的单词。所以我尝试在cmdstanr中直接做这件事。(虽然我不太使用Stan,但我最近的经验是,通过rstan的直接R-to-Stan接口最近变得非常不稳定。
## if necessary:
install.packages("cmdstanr",
repos = c("https://mc-stan.org/r-packages/",
getOption("repos")))
library(cmdstanr)
set_cmdstan_path("~/.cmdstan/cmdstan-2.27.0/") ## idiosyncratic/ if necessary
writeLines(MCMC_Regression_Model, con="tmpreg.stan")
mod <- cmdstan_model("tmpreg.stan")
fit <- mod$sample(
data = list(n = nrow(weather_WU),
Y = weather_WU[['temp9am']],
X1 = weather_WU[['location']],
X2 = weather_WU[['humidity9am']]
),
chains = 4,
iter_warmup = 5000,
iter_sampling = 5000,
seed = 84735
)缩写会话信息:
R Under development (unstable) (2021-09-23 r80950)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Pop!_OS 20.10
other attached packages:
[1] bayesrules_0.0.1 rstan_2.21.2 ggplot2_3.3.5
[4] StanHeaders_2.21.0-7 cmdstanr_0.4.0 https://stackoverflow.com/questions/69306392
复制相似问题