Accessing the contents of a stanfit object

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 16 divergent transitions after warmup. See
https://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
to find out why this is a problem and how to eliminate them.
Warning: Examine the pairs() plot to diagnose sampling problems
Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable.
Running the chains for more iterations may help. See
https://mc-stan.org/misc/warnings.html#tail-ess
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] -2.294597 16.766078  8.317774  4.711895  9.703029  9.898252
head(list_of_draws$tau)
[1] 13.396839  1.670215  1.835704  1.087312  9.774975 13.506516
head(list_of_draws$theta)
          
iterations      [,1]       [,2]      [,3]       [,4]      [,5]      [,6]
      [1,] 17.089557 -0.5230537  7.703668 -13.304894  1.051298  9.801762
      [2,] 16.798478 16.1297354 17.608264  16.922820 19.126652 16.280950
      [3,]  8.536762  8.8787899  6.465309  10.649288  8.236661  6.421047
      [4,]  4.990828  4.5700937  3.983041   4.211009  3.665930  4.777658
      [5,]  9.067547 -1.3238784  6.068246   9.872118  7.320029 11.069132
      [6,] 38.453110 13.2224993  4.145060  15.237521  3.926288  2.141124
          
iterations       [,7]       [,8]
      [1,] -1.5118792  0.0118178
      [2,] 16.2536644 18.9399682
      [3,]  9.8407780  8.8920731
      [4,]  4.4796195  2.7576694
      [5,] 19.7866835 28.7900503
      [6,]  0.9040454 -3.0325054


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,]  2.112825 -0.4910757
      [2,]  2.112825 -0.4910757
      [3,]  5.394902  7.7399157
      [4,]  9.779360 10.7625922
      [5,]  8.522380  8.9432516
      [6,] 18.528566 26.1166452


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.693103791 0.25021500 5.6331475  -3.8650593   4.5638173
tau        6.801083331 0.20255978 5.7113001   0.2517851   2.5802065
eta[1]     0.414722679 0.01971034 0.9361992  -1.5231246  -0.1781229
eta[2]     0.007834778 0.01578079 0.8668020  -1.7310369  -0.5739909
eta[3]    -0.193018884 0.01821972 0.9428932  -2.0178686  -0.8296233
eta[4]    -0.022673659 0.01541529 0.8810288  -1.7324867  -0.6070801
eta[5]    -0.344798139 0.01709781 0.8761698  -2.0039129  -0.9290280
eta[6]    -0.205009139 0.01496519 0.8787261  -1.9350547  -0.7999981
eta[7]     0.356513821 0.01920812 0.8980874  -1.4922050  -0.2339265
eta[8]     0.086516600 0.01605777 0.9494833  -1.7425856  -0.5517805
theta[1]  11.620586821 0.18265439 8.4995740  -1.8673411   6.0225542
theta[2]   7.897682929 0.10270213 6.2001339  -4.3387314   3.9453036
theta[3]   6.003123893 0.17752597 7.8405625 -11.1807282   1.7619008
theta[4]   7.631320211 0.12722644 6.7478546  -6.1618941   3.6074719
theta[5]   5.067904160 0.10536586 6.2082158  -8.1739527   1.3640336
theta[6]   5.878601504 0.18317337 6.7243111  -9.2776784   2.0071996
theta[7]  10.826760377 0.14124775 6.8706547  -1.1175887   6.1561055
theta[8]   8.372261685 0.17442596 8.0009415  -7.2457166   3.5993458
lp__     -39.493418089 0.07754112 2.6415428 -45.3397798 -41.0809214
                  50%         75%      97.5%     n_eff      Rhat
mu         7.73222858  11.1276453  18.733232  506.8455 1.0097551
tau        5.44639295   9.5203597  21.091896  794.9934 1.0054861
eta[1]     0.42746880   1.0378197   2.234278 2256.0475 1.0009954
eta[2]     0.01945174   0.5887305   1.702495 3017.0473 1.0007314
eta[3]    -0.18377135   0.4456242   1.636653 2678.1909 1.0001371
eta[4]    -0.02609765   0.5579808   1.723103 3266.4576 1.0008565
eta[5]    -0.36757797   0.2424307   1.384902 2626.0062 1.0012801
eta[6]    -0.21804335   0.3579060   1.562957 3447.8032 1.0005356
eta[7]     0.36927263   0.9609093   2.106555 2186.0877 1.0009070
eta[8]     0.09520800   0.7056154   1.960917 3496.2647 0.9995146
theta[1]  10.34121466  15.9594188  32.544210 2165.3799 1.0022614
theta[2]   7.90371337  11.8261516  20.944389 3644.5443 1.0000255
theta[3]   6.51986175  10.6289504  20.435446 1950.6108 1.0012634
theta[4]   7.70954446  11.7117323  21.201013 2813.0449 0.9998947
theta[5]   5.47169282   9.2255345  16.470041 3471.6326 1.0001012
theta[6]   6.40022048  10.2861638  18.168487 1347.6308 1.0015689
theta[7]  10.18908773  14.7714486  26.519941 2366.1005 1.0002795
theta[8]   8.14720081  12.8262583  25.671761 2104.0688 1.0027335
lp__     -39.25619633 -37.6087662 -35.147120 1160.5160 1.0015005

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.693104 0.2502150 5.633148 1.1041579 14.36102 506.8455 1.009755
tau 6.801083 0.2025598 5.711300 0.9907942 14.30823 794.9934 1.005486

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.1041579 14.36102
tau 0.9907942 14.30823


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.8119845 0.7173610 0.8894170 0.8307214
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 4 4 4 4


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  array[J] real y;               // estimated treatment effects\n  array[J] real<lower=0> sigma;  // 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
  array[J] real y;               // estimated treatment effects
  array[J] real<lower=0> sigma;  // 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.003638

$tau
[1] 0.6382434

$eta
[1] -1.29797430 -1.34637933  0.49329270 -1.17032510 -1.70227906 -1.55689064
[7]  0.69356742  0.08848479

$theta
[1] -1.8320616 -1.8629558 -0.6887973 -1.7505903 -2.0901064 -1.9973132 -0.5609733
[8] -0.9471632


(P)RNG seed

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

print(get_seed(fit))
[1] 1225805009


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.012  0.008
chain:2  0.011  0.011
chain:3  0.011  0.011
chain:4  0.011  0.009