如何解决推断两个变量在STAN中受其和约束的后验
动机:回答以下问题:两个男人的身高之和为4米,每个男人最可能的身高是多少?
我正在尝试使用STAN对此进行建模(对于本用例来说可能有点过时了,但是目标是要有一个可以扩展的通用框架),并且我假设人们的身高是Normal(1.8,0.2 )。
我提出了以下.stan代码,但是当我查看结果时,似乎未考虑总和的约束。我在做什么错了?
experiment.stan
data {
}
parameters {
real y1;
real y2;
}
transformed parameters {
real S;
S = y1+y2;
S = 4;
}
model {
y1 ~ normal(1.8,0.2);
y2 ~ normal(1.8,0.2);
}
experiment.R
#load libraries
library(rstan)
library(coda)
#the model
heights<-stan(file="experiment.stan",pars = c("y1","y2","S"))
#plotting the posterior distribution for the parameters
post_beta<-As.mcmc.list(heights,pars=c("y1","S"))
plot(post_beta)
解决方法
一种选择是使用Unit Simplex,就像一个向量,其中元素之和等于1。然后,您可以通过将generated quantities
部分中的所有内容乘以4来重新缩放(一直向下滚动以获取相关策略):
stan_program <- "
parameters {
simplex[2] height;
}
model {
height ~ normal(.45,.05);
}
generated quantities {
vector[2] height_scale;
height_scale = height * 4;
}
"
library(rstan)
library(coda)
mod <- stan(model_code=stan_program)
post_beta <- As.mcmc.list(mod,pars=c("height_scale"))
plot(post_beta)
编辑:一种类似的方法是
parameters {
simplex[2] height_constrained;
}
transformed parameters {
vector[2] height;
height = height_constrained * 4;
}
model {
height_constrained ~ normal(.45,.05);
}
,
在参数之间创建约束的简单解决方案是将其中一个参数表示为另一个参数的转换。这种解决方案使事情变得非常简单和灵活:
experiment.stan
data {
}
parameters {
real y1;
}
transformed parameters {
real y2;
y2 = 4-y1;
}
model {
y1 ~ normal(1.8,0.2);
y2 ~ normal(1.8,0.2);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。