推断两个变量在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);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...