gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:28 25 4
gpt4 key购买 nike

我需要对数似然项的后验样本来运行 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)`.

小例子here是这样的 pip 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 拟合模型的对数似然后验样本?

最佳答案

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

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

关于python - 如何从 PyStan 中提取对数似然的后验样本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49147905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com