Accessing the contents of a stanfit object

2018-11-06

This vignette demonstrates how to access most of data stored in a stanfit object. A stanfit object (an object of class "stanfit") contains the output derived from fitting a Stan model using Markov chain Monte Carlo or one of Stan’s variational approximations (meanfield or full-rank). Throughout the document we’ll use the stanfit object obtained from fitting the Eight Schools example model:

library(rstan)
fit <- stan_demo("eight_schools", refresh = 0)
Warning: There were 5 divergent transitions after warmup. Increasing adapt_delta above 0.8 may help. See
http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
Warning: Examine the pairs() plot to diagnose sampling problems
class(fit)
[1] "stanfit"
attr(,"package")
[1] "rstan"

Posterior draws

There are several functions that can be used to access the draws from the posterior distribution stored in a stanfit object. These are extract, as.matrix, as.data.frame, and as.array, each of which returns the draws in a different format.

extract()

The extract function (with its default arguments) returns a list with named components corresponding to the model parameters.

list_of_draws <- extract(fit)
print(names(list_of_draws))
[1] "mu"    "tau"   "eta"   "theta" "lp__" 

In this model the parameters mu and tau are scalars and theta is a vector with eight elements. This means that the draws for mu and tau will be vectors (with length equal to the number of post-warmup iterations times the number of chains) and the draws for theta will be a matrix, with each column corresponding to one of the eight components:

head(list_of_draws$mu) [1] 0.5447095 4.7252417 3.2569470 -0.8286781 9.6219050 8.2216086 head(list_of_draws$tau)
[1]  8.5346787 17.9086457  0.6533242  7.6947293  0.4868406  0.1776437
head(list_of_draws$theta)  iterations [,1] [,2] [,3] [,4] [,5] [,6] [1,] 6.418424 2.377951 -7.457418 -4.285390 6.260707 4.035662 [2,] 16.200762 20.996226 13.522734 10.804684 -5.715024 1.373639 [3,] 2.730646 2.906606 3.566164 4.272856 3.946449 3.156987 [4,] -9.516586 3.419058 2.609175 2.106274 1.168186 2.333335 [5,] 10.649391 9.347813 8.845197 9.312305 10.572009 8.837870 [6,] 7.779830 8.059589 8.098960 8.071455 8.152695 8.439963 iterations [,7] [,8] [1,] -10.233530 -0.2492004 [2,] 2.659190 20.2856562 [3,] 2.915854 1.8150799 [4,] 10.873250 -8.2252264 [5,] 9.736105 9.5069306 [6,] 8.829198 8.4036264 as.matrix(), as.data.frame(), as.array() The as.matrix, as.data.frame, and as.array functions can also be used to retrieve the posterior draws from a stanfit object: matrix_of_draws <- as.matrix(fit) print(colnames(matrix_of_draws))  [1] "mu" "tau" "eta[1]" "eta[2]" "eta[3]" "eta[4]" [7] "eta[5]" "eta[6]" "eta[7]" "eta[8]" "theta[1]" "theta[2]" [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]" [19] "lp__"  df_of_draws <- as.data.frame(fit) print(colnames(df_of_draws))  [1] "mu" "tau" "eta[1]" "eta[2]" "eta[3]" "eta[4]" [7] "eta[5]" "eta[6]" "eta[7]" "eta[8]" "theta[1]" "theta[2]" [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]" [19] "lp__"  array_of_draws <- as.array(fit) print(dimnames(array_of_draws)) $iterations
NULL

$chains [1] "chain:1" "chain:2" "chain:3" "chain:4"$parameters
[1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
[7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
[13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
[19] "lp__"    

The as.matrix and as.data.frame methods essentially return the same thing except in matrix and data frame form, respectively. The as.array method returns the draws from each chain separately and so has an additional dimension:

print(dim(matrix_of_draws))
print(dim(df_of_draws))
print(dim(array_of_draws))
[1] 4000   19
[1] 4000   19
[1] 1000    4   19

By default all of the functions for retrieving the posterior draws return the draws for all parameters (and generated quantities). The optional argument pars (a character vector) can be used if only a subset of the parameters is desired, for example:

mu_and_theta1 <- as.matrix(fit, pars = c("mu", "theta[1]"))
head(mu_and_theta1)
          parameters
iterations       mu  theta[1]
[1,] 7.834656 14.658213
[2,] 8.602845  8.707589
[3,] 6.683328  6.059371
[4,] 1.136996 16.144736
[5,] 3.099223 12.282279
[6,] 9.837489  9.743201

Posterior summary statistics and convergence diagnostics

Summary statistics are obtained using the summary function. The object returned is a list with two components:

fit_summary <- summary(fit)
print(names(fit_summary))
[1] "summary"   "c_summary"

In fit_summary$summary all chains are merged whereas fit_summary$c_summary contains summaries for each chain individually. Typically we want the summary for all chains merged, which is what we’ll focus on here.

The summary is a matrix with rows corresponding to parameters and columns to the various summary quantities. These include the posterior mean, the posterior standard deviation, and various quantiles computed from the draws. The probs argument can be used to specify which quantiles to compute and pars can be used to specify a subset of parameters to include in the summary.

For models fit using MCMC, also included in the summary are the Monte Carlo standard error (se_mean), the effective sample size (n_eff), and the R-hat statistic (Rhat).

print(fit_summary$summary)  mean se_mean sd 2.5% 25% mu 7.863884583 0.13700508 5.2321964 -2.0422915 4.6269794 tau 6.599095132 0.16046573 5.7085456 0.2345065 2.4116847 eta[1] 0.375229911 0.01514060 0.9381203 -1.5313749 -0.2151492 eta[2] 0.004147385 0.01559322 0.8790939 -1.7521281 -0.5766739 eta[3] -0.199061848 0.01522928 0.9134201 -1.9233541 -0.8049536 eta[4] -0.039406372 0.01362912 0.8479632 -1.7511187 -0.6066509 eta[5] -0.370246352 0.01655953 0.8932633 -2.0846894 -0.9660010 eta[6] -0.204209067 0.01498057 0.8799825 -1.9172993 -0.7788366 eta[7] 0.348635042 0.01697559 0.9111550 -1.4979758 -0.2043391 eta[8] 0.062709382 0.01502139 0.9282725 -1.7781836 -0.5482978 theta[1] 11.335275863 0.15664699 8.4281621 -2.2940551 5.8620102 theta[2] 7.883719928 0.10284132 6.3925801 -5.1356249 3.9948330 theta[3] 6.036301960 0.15676490 7.8803570 -12.3008577 1.8278046 theta[4] 7.575273541 0.10199717 6.4364544 -5.3897602 3.6837216 theta[5] 4.886665484 0.10579500 6.4088014 -9.6346894 1.1328775 theta[6] 6.251944264 0.10720494 6.5528113 -7.7144651 2.3897055 theta[7] 10.610438309 0.12460629 6.9284417 -1.4690289 6.0211123 theta[8] 8.514287880 0.14635666 7.9547517 -7.1063146 3.9007457 lp__ -39.537150705 0.07642424 2.6232606 -45.3329098 -41.1098461 50% 75% 97.5% n_eff Rhat mu 7.77626346 11.0972178 18.581425 1458.461 1.0039599 tau 5.28591218 9.1108242 21.028160 1265.571 1.0041627 eta[1] 0.39427914 0.9970109 2.247871 3839.112 1.0009535 eta[2] 0.01655031 0.5600328 1.726874 3178.329 1.0029754 eta[3] -0.22392990 0.4167847 1.647382 3597.346 1.0011706 eta[4] -0.03390189 0.5365456 1.591477 3870.958 0.9998946 eta[5] -0.39030913 0.2051930 1.449781 2909.800 1.0006403 eta[6] -0.21086457 0.3779280 1.597726 3450.575 1.0007759 eta[7] 0.34287287 0.9354712 2.147667 2880.942 1.0003174 eta[8] 0.06297143 0.6578275 1.961969 3818.832 1.0007991 theta[1] 10.18327621 15.4053555 31.995808 2894.820 1.0005149 theta[2] 7.84386632 11.8243242 20.981496 3863.822 1.0001433 theta[3] 6.63421295 10.8045881 20.371353 2526.935 1.0009286 theta[4] 7.63718913 11.4798972 20.620087 3982.146 1.0001086 theta[5] 5.41247224 9.1606172 16.289103 3669.639 1.0011515 theta[6] 6.65775950 10.4060349 18.794605 3736.162 1.0004816 theta[7] 9.97535487 14.5480351 26.003608 3091.656 1.0004385 theta[8] 8.17189454 12.5817082 25.800651 2954.121 1.0009291 lp__ -39.27056233 -37.6887982 -35.097643 1178.204 1.0064082 If, for example, we wanted the only quantiles included to be 10% and 90%, and for only the parameters included to be mu and tau, we would specify that like this: mu_tau_summary <- summary(fit, pars = c("mu", "tau"), probs = c(0.1, 0.9))$summary
print(mu_tau_summary)
        mean   se_mean       sd       10%      90%    n_eff     Rhat
mu  7.863885 0.1370051 5.232196 1.6079465 14.39235 1458.461 1.003960
tau 6.599095 0.1604657 5.708546 0.9589362 13.54728 1265.571 1.004163

Since mu_tau_summary is a matrix we can pull out columns using their names:

mu_tau_80pct <- mu_tau_summary[, c("10%", "90%")]
print(mu_tau_80pct)
          10%      90%
mu  1.6079465 14.39235
tau 0.9589362 13.54728

Sampler diagnostics

For models fit using MCMC the stanfit object will also contain the values of parameters used for the sampler. The get_sampler_params function can be used to access this information.

The object returned by get_sampler_params is a list with one component (a matrix) per chain. Each of the matrices has number of columns corresponding to the number of sampler parameters and the column names provide the parameter names. The optional argument inc_warmup (defaulting to TRUE) indicates whether to include the warmup period.

sampler_params <- get_sampler_params(fit, inc_warmup = FALSE)
sampler_params_chain1 <- sampler_params[[1]]
colnames(sampler_params_chain1)
[1] "accept_stat__" "stepsize__"    "treedepth__"   "n_leapfrog__"
[5] "divergent__"   "energy__"     

To do things like calculate the average value of accept_stat__ for each chain (or the maximum value of treedepth__ for each chain if using the NUTS algorithm, etc.) the sapply function is useful as it will apply the same function to each component of sampler_params:

mean_accept_stat_by_chain <- sapply(sampler_params, function(x) mean(x[, "accept_stat__"]))
print(mean_accept_stat_by_chain)
[1] 0.8623579 0.8631091 0.8363789 0.8016998
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 5 5 5 6

Model code

The Stan program itself is also stored in the stanfit object and can be accessed using get_stancode:

code <- get_stancode(fit)

The object code is a single string and is not very intelligible when printed:

print(code)
[1] "data {\n  int<lower=0> J;          // number of schools \n  real y[J];               // estimated treatment effects\n  real<lower=0> sigma[J];  // s.e. of effect estimates \n}\nparameters {\n  real mu; \n  real<lower=0> tau;\n  vector[J] eta;\n}\ntransformed parameters {\n  vector[J] theta;\n  theta = mu + tau * eta;\n}\nmodel {\n  target += normal_lpdf(eta | 0, 1);\n  target += normal_lpdf(y | theta, sigma);\n}"
attr(,"model_name2")
[1] "schools"

A readable version can be printed using cat:

cat(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;
vector[J] eta;
}
transformed parameters {
vector[J] theta;
theta = mu + tau * eta;
}
model {
target += normal_lpdf(eta | 0, 1);
target += normal_lpdf(y | theta, sigma);
}

Initial values

The get_inits function returns initial values as a list with one component per chain. Each component is itself a (named) list containing the initial values for each parameter for the corresponding chain:

inits <- get_inits(fit)
inits_chain1 <- inits[[1]]
print(inits_chain1)
$mu [1] 1.001$tau
[1] 0.1748375

$eta [1] -0.96097895 -0.48769618 0.53046695 0.90459315 -0.04889237 1.22326686 [7] -0.88752200 1.48297866$theta
[1] 0.8329847 0.9157323 1.0937454 1.1591567 0.9924517 1.2148728 0.8458278
[8] 1.2602802

(P)RNG seed

The get_seed function returns the (P)RNG seed as an integer:

print(get_seed(fit))
[1] 699847790

Warmup and sampling times

The get_elapsed_time function returns a matrix with the warmup and sampling times for each chain:

print(get_elapsed_time(fit))
          warmup   sample
chain:1 0.038175 0.029291
chain:2 0.037047 0.033903
chain:3 0.033255 0.032134
chain:4 0.030956 0.026188