SSブログ

R stanを実行する方法 モデルを読み込む2つの方法 [データサイエンス、統計モデル]

stanを実行する際に必要なものが2つあります。
・データ
・stanのモデル

stanのモデルを読み込む方法として、
- 外部にテキストで保存してそれを読み込む方法
- Rでモデルを書いてそれを読み込む方法
があります。

?stan
をRで実行するとヘルプが出てくるのですが、それぞれ引数が書かれています。


Usage
stan(file, model_name = "anon_model", model_code = "", fit = NA, 
  data = list(), pars = NA,
  chains = 4, iter = 2000, warmup = floor(iter/2), thin = 1, 
  init = "random", seed = sample.int(.Machine$integer.max, 1), 
  algorithm = c("NUTS", "HMC", "Fixed_param"), 
  control = NULL, sample_file = NULL, diagnostic_file = NULL, 
  save_dso = TRUE, verbose = FALSE, include = TRUE,
  cores = getOption("mc.cores", 1L),
  open_progress = interactive() && !isatty(stdout()) &&
                  !identical(Sys.getenv("RSTUDIO"), "1"),
  ...,
  boost_lib = NULL, eigen_lib = NULL
  )

file
The path to the Stan program to use. file should be a character string file name or a connection that R supports containing the text of a model specification in the Stan modeling language.
A model may also be specified directly as a character string using the model_code argument, but we recommend always putting Stan programs in separate files with a .stan extension.
The stan function can also use the Stan program from an existing stanfit object via the fit argument. When fit is specified, the file argument is ignored.

model_code
A character string either containing the model definition or the name of a character string object in the workspace. This argument is used only if arguments file and fit are not specified.


- 外部にテキストで保存してそれを読み込む方法
file= 引数を使う
res_mcmc_bin <- stan(file="./stan/Binom.stan", data=data_stan_bin)

- Rでモデルを書いてそれを読み込む方法
model_code= 引数を使う
stan_code <- '
data{
int n;
int x;
}

parameters{
real p; } model{ x ~ binomial(n, p); } ' res_mcmc_bin <- stan(model_code=stan_code, data=data_stan_bin) あらかじめRでモデルを書く方法ですが、複数行のコードなので、シングルクォートでくくります。 stan_code <- ' ***** ***** ***** '
nice!(1)  コメント(0) 
共通テーマ:学問

nice! 1

コメント 0