loo (version 1.0.0)

extract_log_lik: Extract log-likelihood from a Stan model

Description

Convenience function for extracting the pointwise log-likelihood from a fitted Stan model.

Usage

extract_log_lik(stanfit, parameter_name = "log_lik")

Arguments

stanfit
A stanfit object (rstan package).
parameter_name
A character string naming the parameter (or generated quantity) in the Stan model corresponding to the log-likelihood.

Value

An $S$ by $N$ matrix of (post-warmup) extracted draws, where $S$ is the size of the posterior sample and $N$ is the number of data points.

Details

Stan does not automatically compute and store the log-likelihood. It is up to the user to incorporate it into the Stan program if it is to be extracted after fitting the model. In a Stan model, the pointwise log likelihood can be coded as a vector in the transformed parameters block (and then summed up in the model block) or it can be coded entirely in the generated quantities block. We recommend using the generated quantities block so that the computations are carried out only once per iteration rather than once per HMC leapfrog step.

For example, the following is the generated quantities block for computing and saving the log-likelihood for a linear regression model with N data points, outcome y, predictor matrix X, coefficients beta, and standard deviation sigma:

vector[N] log_lik;

for (n in 1:N) log_lik[n] = normal_lpdf(y[n] | X[n] * beta, sigma);

References

Stan Development Team (2016). The Stan C++ Library, Version 2.10.0. http://mc-stan.org/documentation/

Stan Development Team (2016). RStan: the R interface to Stan, Version 2.10.1. http://mc-stan.org/interfaces/rstan.html