我想学习如何在stan中使用Dirichlet发行版。
我有一张表格,其中包含因子变量的六个等级中每个等级的观察总数:
counts n factor_var
-------- ------ ------------
3710 4386 level 1
252 4386 level 2
332 4386 level 3
59 4386 level 4
29 4386 level 5
4 4386 level 6
我想简单地估计dirichlet参数,即a值来自给定级别的概率。我知道它可以在R(gtools::rdirichlet(number_of_samples, df$counts)
)中轻松完成,但我最终的目标是基于估计的分层模型。
这是我到目前为止的stan模型。该模型没有编译,因为分类分布的结果是来自< 1,n_levels>的离散数字。
data {
int<lower=1> n_levels;
int counts[n_levels];
}
parameters {
vector<lower=0>[n_levels] priors;
simplex[n_levels] level_p;
}
model {
level_p ~ dirichlet(priors);
counts ~ categorical_logit(level_p);
}
这是R代码:
df <-
data.frame(
counts=c(3710, 252, 332, 59, 29, 4),
n = c(4386, 4386, 4386, 4386, 4386, 4386),
factor_var = factor(1:6, labels=paste0('level ', 1:6)))
data<-list(
n_levels=6,
counts<-df$counts
)
fit1<-stan(
file='model.stan')
运行时,编译后,我收到以下错误:
SAMPLING FOR MODEL 'model' NOW (CHAIN 1).
Rejecting initial value:
Error evaluating the log probability at the initial value.
Exception: categorical_logit_lpmf: categorical outcome out of support is 3710, but must be in the interval [1, 6] (in 'model6fffc8dd594_proba_stan' at line 13)
...
Initialization between (-2, 2) failed after 100 attempts.
Try specifying initial values, reducing ranges of constrained values, or reparameterizing the model.
[1] "Error in sampler$call_sampler(args_list[[i]]) : Initialization failed."
error occurred during calling the sampler; sampling not done
答案 0 :(得分:1)
您需要使用多项分发。
categorical_logit
假定日志赔率参数,而不是单纯形参数。
有一些如何在手册中安装Dirichlet的例子,包括一些广义的先验。