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

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.1263724  2.3036249 -0.4616172 10.2692249  8.7243138 10.7133252
head(list_of_draws$tau)
[1] 4.410711 6.079445 6.677418 4.836641 4.633207 3.860572
head(list_of_draws$theta)
          
iterations      [,1]        [,2]       [,3]       [,4]      [,5]       [,6]
      [1,] -4.193068  4.79873828 -14.359165  1.1697450  4.094143 -3.2124341
      [2,] -2.314343 -0.07199935 -10.026364  1.0891864 -3.595034  6.9353757
      [3,]  4.505927  0.52626423  16.243111  0.7480968 -9.091137 -0.7492486
      [4,] 10.900022  9.44609828  16.772485 12.9169994  6.333015 11.6992029
      [5,] 18.680208 10.86164719   8.197610  5.7849413  9.274406  4.8865952
      [6,] 13.233764 14.07481896   5.815589  8.3642709 -1.846623 13.4647446
          
iterations      [,7]       [,8]
      [1,]  6.157518   2.836315
      [2,] 14.812775   9.772055
      [3,]  9.038573 -11.551830
      [4,] 15.976498   9.243161
      [5,] 15.946928  11.260387
      [6,] 11.814680  14.630290


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,] 14.997056 13.4711065
      [2,] 12.965336 18.4681084
      [3,] 11.808955 13.4459788
      [4,]  9.814731  9.6697438
      [5,] 12.250272 13.3378018
      [6,]  1.103203  0.5517985


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%          50%
mu         7.75436295 0.09989697 4.9308655  -2.1192162   4.4737924   7.78469060
tau        6.42542115 0.13311985 5.2709425   0.2119588   2.6605873   5.25506160
eta[1]     0.41169953 0.01422672 0.9420473  -1.4967882  -0.1967757   0.42531461
eta[2]    -0.00332848 0.01309626 0.8760016  -1.7690355  -0.5696656  -0.01892059
eta[3]    -0.20829748 0.01360612 0.9278240  -1.9754993  -0.8432788  -0.21144545
eta[4]    -0.03551529 0.01303176 0.8935050  -1.7803805  -0.6349247  -0.02297831
eta[5]    -0.36680546 0.01422425 0.8881464  -2.0878929  -0.9456811  -0.38084236
eta[6]    -0.21798707 0.01241444 0.8620107  -1.8721835  -0.7964998  -0.23467044
eta[7]     0.37451472 0.01574868 0.9014496  -1.5124286  -0.2262422   0.39449960
eta[8]     0.05117296 0.01346943 0.9554310  -1.8553761  -0.5742620   0.06143594
theta[1]  11.20036003 0.14215764 8.2216020  -2.3626846   5.8987040  10.17914249
theta[2]   7.68027971 0.09118702 6.2752328  -4.9510251   3.7506557   7.62449962
theta[3]   5.96976709 0.14556229 7.6739634 -11.7155178   1.8366907   6.50863948
theta[4]   7.48985847 0.10627512 6.6166823  -6.3286083   3.3370172   7.69497208
theta[5]   4.92318201 0.09600883 6.3744737  -9.5348234   1.1226374   5.41424810
theta[6]   6.04040019 0.10384137 6.6030264  -8.3930348   2.1459512   6.35342695
theta[7]  10.68486583 0.10756085 6.7479315  -1.1375857   6.2346544  10.17515203
theta[8]   8.35184128 0.13569913 8.1361430  -7.8863396   3.5484296   8.17524571
lp__     -39.57893393 0.07635113 2.5855205 -45.2305045 -41.1165881 -39.31119693
                 75%      97.5%    n_eff      Rhat
mu        11.1205061  17.373882 2436.361 0.9998749
tau        8.8237938  19.841945 1567.801 1.0008246
eta[1]     1.0465453   2.238122 4384.659 0.9999382
eta[2]     0.5625840   1.742759 4474.197 1.0004140
eta[3]     0.4198493   1.604673 4650.103 1.0003147
eta[4]     0.5490500   1.703784 4700.973 1.0001611
eta[5]     0.1892709   1.457781 3898.613 0.9993696
eta[6]     0.3543390   1.510051 4821.375 0.9999530
eta[7]     0.9979202   2.080133 3276.381 1.0000445
eta[8]     0.6943484   1.842100 5031.535 0.9996929
theta[1]  15.2996943  31.015970 3344.818 1.0005573
theta[2]  11.5606732  20.157672 4735.803 0.9999659
theta[3]  10.7527618  19.760597 2779.340 1.0001340
theta[4]  11.4510264  20.999629 3876.300 0.9999220
theta[5]   9.2744407  15.908946 4408.251 0.9999916
theta[6]  10.3232075  18.391333 4043.386 1.0008209
theta[7]  14.5349932  25.878134 3935.799 0.9994434
theta[8]  12.7339468  26.128824 3594.869 1.0002431
lp__     -37.7442866 -35.305428 1146.740 1.0061524

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.754363 0.09989697 4.930866 1.441711 13.89806 2436.361 0.9998749
tau 6.425421 0.13311985 5.270942 1.081737 12.91555 1567.801 1.0008246

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.441711 13.89806
tau 1.081737 12.91555


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.9248156 0.8773792 0.9146442 0.7931583
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.324389

$tau
[1] 2.743607

$eta
[1] -0.5343665  0.1712975 -1.5295120  1.1398812 -1.9593658  0.6131711  1.3240466
[8]  0.3849146

$theta
[1] -2.7904804 -0.8544155 -5.5207691  1.8029980 -6.7001191  0.3579121  2.3082755
[8] -0.2683340


(P)RNG seed

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

print(get_seed(fit))
[1] 1445811692


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.014
chain:2  0.013  0.014
chain:3  0.012  0.013
chain:4  0.016  0.008