首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从PyStan中提取对数似然的后验样本?

如何从PyStan中提取对数似然的后验样本?
EN

Stack Overflow用户
提问于 2018-03-07 09:06:46
回答 2查看 1.2K关注 0票数 3

我需要对数似然项的后验样本来运行PSIS 这里,以便

代码语言:javascript
复制
log_lik : ndarray
    Array of size n x m containing n posterior samples of the log likelihood
    terms :math:`p(y_i|\theta^s)`.

其中的小示例这里是这样的,pip install pystan

代码语言:javascript
复制
import pystan
schools_code = """
data {
    int<lower=0> J; // number of schools
    real y[J]; // estimated treatment effects
    real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
    real mu;
    real<lower=0> tau;
    real eta[J];
}
transformed parameters {
    real theta[J];
    for (j in 1:J)
    theta[j] = mu + tau * eta[j];
}
model {
    eta ~ normal(0, 1);
    y ~ normal(theta, sigma);
}
"""

schools_dat = {'J': 8,
               'y': [28,  8, -3,  7, -1,  1, 18, 12],
               'sigma': [15, 10, 16, 11,  9, 11, 10, 18]}

sm = pystan.StanModel(model_code=schools_code)
fit = sm.sampling(data=schools_dat, iter=1000, chains=4)

如何获得PyStan拟合模型的对数似然后验样本?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-09 13:28:08

您可以通过You:logp = fit.extract()['lp__']获得对数似然的后验样本。

票数 3
EN

Stack Overflow用户

发布于 2018-11-16 09:58:26

我相信在这种情况下计算日志可能性的正确方法如下:

代码语言:javascript
复制
generated quantities {
    vector[J] log_lik;
    for (i in 1:J)
        log_lik[i] = normal_lpdf(y[i] | theta, sigma);
}

之后,您可以运行psis如下:

代码语言:javascript
复制
loo, loos, ks = psisloo(fit['log_lik'])
print('PSIS-LOO value: {:.2f}'.format(loo))

然后,完整的代码将变成:

代码语言:javascript
复制
import pystan
from psis import psisloo
schools_code = """
data {
    int<lower=0> J;            // number of schools
    real y[J];                 // estimated treatment effects
    real<lower=0> sigma[J];    // s.e. of effect estimates
}
parameters {
    real mu;
    real<lower=0> tau;
    real eta[J];
}
transformed parameters {
    real theta[J];
    for (j in 1:J)
       theta[j] = mu + tau * eta[j];
}
model {
    eta ~ normal(0, 1);
    y ~ normal(theta, sigma);
}
generated quantities {
    vector[J] log_lik;
    for (i in 1:J)
         log_lik[i] = normal_lpdf(y[i] | theta, sigma);
}
"""

schools_dat = {'J': 8,
               'y': [28,  8, -3,  7, -1,  1, 18, 12],
               'sigma': [15, 10, 16, 11,  9, 11, 10, 18]}

sm = pystan.StanModel(model_code=schools_code) 
fit = sm.sampling(data=schools_dat, iter=1000, chains=4)
loo, loos, ks = psisloo(fit['log_lik'])
print('PSIS-LOO value: {:.2f}'.format(loo))
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49147905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档