# NOT RUN {
# Generate a dataset from N(0,1)
N <- 100
y <- rnorm(N, 0, 1)
# Suppose we have three models for y:
# 1) y ~ N(-1, sigma)
# 2) y ~ N(0.5, sigma)
# 3) y ~ N(0.6,sigma)
#
stan_code <- "
data {
int N;
vector[N] y;
real mu_fixed;
}
parameters {
real<lower=0> sigma;
}
model {
sigma ~ exponential(1);
y ~ normal(mu_fixed, sigma);
}
generated quantities {
vector[N] log_lik;
for (n in 1:N) log_lik[n] = normal_lpdf(y[n]| mu_fixed, sigma);
}"
mod <- stan_model(model_code = stan_code)
fit1 <- sampling(mod, data=list(N=N, y=y, mu_fixed=-1))
fit2 <- sampling(mod, data=list(N=N, y=y, mu_fixed=0.5))
fit3 <- sampling(mod, data=list(N=N, y=y, mu_fixed=0.6))
# use the loo method for stanfit objects
loo1 <- loo(fit1, pars = "log_lik")
print(loo1)
# which is equivalent to
LL <- as.array(fit1, pars = "log_lik")
r_eff <- loo::relative_eff(exp(LL))
loo1b <- loo::loo.array(LL, r_eff = r_eff)
print(loo1b)
# compute loo for the other models
loo2 <- loo(fit2)
loo3 <- loo(fit3)
# stacking weights
wts <- loo::loo_model_weights(list(loo1, loo2, loo3), method = "stacking")
print(wts)
# }
Run the code above in your browser using DataLab