Accessing the contents of a stanfit object

Stan Development Team

2021-12-18

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

[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:

[1]  6.554848 10.879302  4.767961  7.091465 11.598077  8.824592
[1] 1.9753143 2.8308715 2.0086751 7.0438025 0.5209676 4.2357642
          
iterations      [,1]      [,2]      [,3]      [,4]      [,5]       [,6]
      [1,]  6.932368  7.572674  4.442209  7.592651  6.181902  7.3268903
      [2,] 12.991402 14.318419 14.469276  9.113789  7.996855 12.4656025
      [3,]  4.308271  4.068238  5.603646  4.861883  1.959096  6.2233502
      [4,] 11.805144  9.670199  5.963235 15.424976 -1.048997 -0.5453547
      [5,] 11.460036 11.618142 11.221779 11.180613 11.507045 11.3217328
      [6,]  9.071255 17.486407 10.454534  5.757446  5.554932 10.2528552
          
iterations      [,7]      [,8]
      [1,]  7.521852  6.768620
      [2,] 11.604704 13.064759
      [3,]  4.273146  1.153053
      [4,] 21.521649 21.573500
      [5,] 11.892903 11.935833
      [6,]  4.544958  3.888883


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:

 [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__"    
 [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__"    
$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:

[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:

          parameters
iterations        mu  theta[1]
      [1,] 11.476354 11.987400
      [2,]  6.583719  4.152074
      [3,]  8.852552  4.129850
      [4,]  9.719438  9.810688
      [5,] 12.857846 -6.555618
      [6,]  2.173871  3.257328


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        8.095146e+00 0.10554985 4.9450686  -1.5290577   4.8460441
tau       6.419180e+00 0.12081845 5.1887850   0.2726604   2.4806829
eta[1]    3.723954e-01 0.01622394 0.9304303  -1.5547601  -0.2369301
eta[2]    1.196977e-04 0.01450894 0.8793101  -1.8049784  -0.5722443
eta[3]   -1.938925e-01 0.01494160 0.9301305  -1.9973315  -0.8223719
eta[4]   -4.059413e-02 0.01541570 0.9132912  -1.8401685  -0.6214927
eta[5]   -3.645885e-01 0.01351489 0.8464365  -1.9808282  -0.9164138
eta[6]   -2.298886e-01 0.01412263 0.9029597  -1.9850630  -0.8462805
eta[7]    3.267748e-01 0.01575200 0.8860387  -1.4595246  -0.2501635
eta[8]    4.398813e-02 0.01532998 0.9134137  -1.7955457  -0.5628526
theta[1]  1.127084e+01 0.16070596 8.3548496  -2.1899064   5.7850634
theta[2]  8.013534e+00 0.09342645 6.2723732  -4.2089577   4.1194903
theta[3]  6.168829e+00 0.12267226 7.6701653 -11.2881964   2.0863364
theta[4]  7.618574e+00 0.10407996 6.5832855  -5.9182770   3.6575513
theta[5]  5.295129e+00 0.09545041 6.1427861  -8.2825279   1.7181637
theta[6]  6.237075e+00 0.10433033 6.7302407  -8.2310974   2.3346128
theta[7]  1.066255e+01 0.11252315 6.7534758  -0.8561660   6.1477640
theta[8]  8.528176e+00 0.14352514 7.8200861  -6.5229000   3.8604302
lp__     -3.952885e+01 0.06918529 2.6001889 -45.4844208 -41.0198749
                   50%         75%      97.5%    n_eff      Rhat
mu         8.134528355  11.2659350  17.533474 2194.974 1.0018091
tau        5.218440764   8.9490206  19.350858 1844.441 1.0040045
eta[1]     0.384869916   1.0130492   2.147796 3288.935 0.9998700
eta[2]     0.005790372   0.5675280   1.734495 3672.929 1.0001346
eta[3]    -0.205436574   0.4094293   1.699155 3875.197 1.0000872
eta[4]    -0.059782907   0.5659284   1.807864 3509.879 1.0010325
eta[5]    -0.380345013   0.1785562   1.334400 3922.507 1.0008008
eta[6]    -0.228018685   0.3725595   1.565871 4087.950 0.9997998
eta[7]     0.349062364   0.8971504   2.037931 3163.982 1.0004335
eta[8]     0.064644526   0.6483807   1.837463 3550.194 1.0005606
theta[1]  10.040698374  15.5729343  31.803133 2702.796 1.0016773
theta[2]   7.982452967  11.8823876  20.561867 4507.379 0.9997661
theta[3]   6.782816780  10.7072869  20.102904 3909.460 0.9992899
theta[4]   7.643989454  11.6943431  20.612114 4000.839 1.0006629
theta[5]   5.733505094   9.4299539  16.373705 4141.667 0.9993261
theta[6]   6.644205690  10.4644879  18.688780 4161.405 0.9999100
theta[7]   9.863163690  14.6163322  26.251924 3602.226 1.0002105
theta[8]   8.298559954  12.7272161  25.281569 2968.705 1.0016566
lp__     -39.241205965 -37.7056949 -35.118793 1412.480 1.0041082

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  8.095146 0.1055499 4.945069 1.928551 14.25629 2194.974 1.001809
tau 6.419180 0.1208185 5.188785 1.065932 13.39661 1844.441 1.004005

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.928551 14.25629
tau 1.065932 13.39661


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.8496154 0.9120332 0.7621930 0.8155829
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  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] -0.3476812

$tau
[1] 5.652987

$eta
[1] -1.530235497 -0.453686364  0.788929216 -1.401105924  0.096354611
[6]  0.495461709  0.006045316  0.427174026

$theta
[1] -8.9980828 -2.9123644  4.1121256 -8.2681150  0.1970102  2.4531575 -0.3135071
[8]  2.0671281


(P)RNG seed

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

print(get_seed(fit))
[1] 1581454425


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.037437 0.036507
chain:2 0.035699 0.040421
chain:3 0.037202 0.024540
chain:4 0.034002 0.028611