用python语法编程stan模型的一种表面语言
yaps的Python项目详细描述
yaps
yaps是一种新的面向Stan的表面语言。它让
用户使用python语法编写stan程序。例如,考虑
以下是斯坦计划,该计划的模型投掷带有偏压的硬币x
:
data{int<lower=0,upper=1>x[10];}parameters{real<lower=0,upper=1>theta;}model{theta~uniform(0,1);for(iin1:10)x[i]~bernoulli(theta);}
它可以用python重写如下:
importyapsfromyaps.libimportint,real,uniform,bernoulli@yaps.modeldefcoin(x:int(lower=0,upper=1)[10]):theta:real(lower=0,upper=1)<~uniform(0,1)foriinrange(1,11):x[i]<~bernoulli(theta)
装饰符@yaps.model
表示它后面的函数
是一个斯坦程序。在语法上是python
语义上重新解释为斯坦。
函数的参数对应于data
块。这个
必须声明数据的类型。在这里,您可以看到x
是
在0
和1
(int(lower=0, upper=1)[10]
)之间的10个整数数组。
参数声明为变量,其类型在
功能。它们的先验值可以使用采样运算符定义
<~
(或is
)。
函数体对应于stan模型。python语法
用于模型的命令式构造,如for
在示例中循环。运算符<~
用于表示采样
以及x.T[a,b]
用于截断分布。
注意,stan数组是基于1的。因此循环的范围是range(1, 11)
,
那是1,2,…10个。
可以使用python的with
语法引入其他stan块。
例如,以前的程序也可以按如下方式编写:
@yaps.modeldefcoin(x:int(lower=0,upper=1)[10]):withparameters:theta:real(lower=0,upper=1)withmodel:theta<~uniform(0,1)foriinrange(1,11):x[i]<~bernoulli(theta)
使用print
函数可以显示相应的stan程序:
print(coin)
最后,可以对应用于某些数据的定义模型进行贝叶斯推理。 与stan推理机的通信基于PyCmdStan。
flips=np.array([0,1,0,0,0,0,0,0,0,1])constrained_coin=coin(x=flips)constrained_coin.sample(data=constrained_coin.data)
请注意,数组必须转换为numpy数组(请参阅pycmdstan文档)。
经过推理,约束模型的属性posterior
是一个对象,具有用于潜在模型参数的字段:
theta_mean=constrained_coin.posterior.theta.mean()print("mean of theta: {:.3f}".format(theta_mean))
yaps为stan程序提供了更轻松的语法。由于yaps使用python语法,用户可以利用python工具 用于语法突出显示、缩进、错误报告…
安装
yaps取决于以下python包:
- 阿斯特
- 图形
- antlr4-python3-runtime
- Pycmdstan
要安装yaps及其所有依赖项,请运行:
pip install yaps
要从源安装,请首先克隆repo,然后:
pip install .
默认情况下,与stan推理引擎的通信基于PyCmdStan。要运行推断,首先需要安装CmdStan,并将CMDSTAN环境变量设置为指向CMDSTAN目录。
export CMDSTAN=/path/to/cmdstan
工具
我们提供了一个将stan文件编译为yaps语法的工具。
例如,如果path/to/coin.stan
包含开头显示的stan模型,则:
stan2yaps path/to/coin.stan
输出:
# -------------
# tests/stan/coin.stan
# -------------
@yaps.model
def stan_model(x: int(lower=0, upper=1)[10]):
theta: real
theta is uniform(0.0, 1.0)
for i in range(1, 10 + 1):
x[(i),] is bernoulli(theta)
print(x)
也可以使用以下函数以编程方式调用从yaps到stan和从stan到yaps的编译器:
yaps.from_stan(code_string=None,code_file=None)# Compile a Stan model to Yapsyaps.to_stan(code_string=None,code_file=None)# Compile a Yaps model to Stan
文档
完整的文档可在https://yaps.readthedocs.io找到。您可以在下面的article中找到更多详细信息:
@article{2018-yaps-stan,
author = {Baudart, Guillaume and Hirzel, Martin and Kate, Kiran and Mandel, Louis and Shinnar, Avraham},
title = "{Yaps: Python Frontend to Stan}",
journal = {arXiv e-prints},
year = 2018,
month = Dec,
url = {https://arxiv.org/abs/1812.04125},
}
许可证
Yaps是根据Apache2.0许可证的条款发布的,请参见 LICENSE.txt
贡献
Yaps仍处于开发的早期阶段,我们欢迎 贡献。贡献者需要提交一个 原产地证书',可在DCO1.1.txt中找到。