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

时间:2018-03-07 09:06:46

标签: python cross-validation bayesian stan pystan

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

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

其中小示例herepip install pystan

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拟合模型的Log似然的后验样本?

2 个答案:

答案 0 :(得分:3)

您可以通过执行以下操作获取Log-Likelihood的后验样本:logp = fit.extract()['lp__']

答案 1 :(得分:0)

我相信在这种情况下,计算对数似然的正确方法如下:

generated quantities {
    vector[J] log_lik;
    for (i in 1:J)
        log_lik[i] = normal_lpdf(y[i] | theta, sigma);
}

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

loo, loos, ks = psisloo(fit['log_lik'])
print('PSIS-LOO value: {:.2f}'.format(loo))

完整代码将变为:

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))