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)
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]  5.151101  4.836601  6.352782  7.404076  3.353498 10.306771
head(list_of_draws$tau)
[1]  9.827773  1.495332  2.024528 13.602553  3.715481  4.965341
head(list_of_draws$theta)
          
iterations      [,1]      [,2]      [,3]       [,4]      [,5]      [,6]
      [1,]  6.142308 15.465806 -3.662220 -2.1282790 3.4860289 -3.276228
      [2,]  3.818226  4.567863  5.086946  4.0224599 5.9517931  3.365201
      [3,]  2.664512  4.810741  5.508332  6.8922565 6.0616244  6.906382
      [4,] 19.466712 -3.471547  6.330541 -0.1882146 0.6861186 -9.290331
      [5,]  4.714033  7.363503  7.203225  4.7806992 7.7952070  8.321691
      [6,] 12.222900 13.433627 13.155492  4.5137576 8.6141022  8.658490
          
iterations      [,7]      [,8]
      [1,] 12.295998  4.232844
      [2,]  5.056985  3.313534
      [3,]  7.200743  7.208455
      [4,]  8.401335 16.631807
      [5,]  4.568814  8.606746
      [6,]  8.858009 12.296126


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.436640  6.938731
      [2,] 14.596305 17.458342
      [3,] -1.205228 -1.192152
      [4,]  5.120868 21.103146
      [5,] 17.584307  3.223563
      [6,] 13.614861 25.487721


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.88576544 0.10612245 5.0915059  -2.080604   4.6040276   7.82270818
tau        6.57514092 0.13853617 5.4470425   0.234598   2.4723579   5.31971838
eta[1]     0.40595795 0.01359203 0.9381593  -1.523055  -0.2008532   0.42874418
eta[2]    -0.01565285 0.01362424 0.8585989  -1.688866  -0.5720190  -0.02442547
eta[3]    -0.19708126 0.01335135 0.9348336  -1.992501  -0.8413882  -0.21145581
eta[4]    -0.01867972 0.01335173 0.8884166  -1.756388  -0.6007796  -0.02090354
eta[5]    -0.34693379 0.01464640 0.8647228  -2.032436  -0.9235234  -0.36713264
eta[6]    -0.20820764 0.01300214 0.8981912  -1.957232  -0.8092195  -0.22485712
eta[7]     0.34862721 0.01331477 0.8961210  -1.584377  -0.2074924   0.37145177
eta[8]     0.05451488 0.01419511 0.9486228  -1.748799  -0.6065559   0.05013302
theta[1]  11.40840739 0.14711498 8.4349778  -2.206374   5.8725220  10.32793166
theta[2]   7.77541396 0.08274959 6.1735254  -4.699755   3.9915501   7.76093894
theta[3]   6.07671254 0.12860520 7.9167891 -11.937913   2.0721694   6.62696234
theta[4]   7.67938286 0.09446259 6.5152953  -5.523839   3.7649013   7.72612744
theta[5]   5.15275013 0.09692941 6.3263821  -9.038978   1.3562559   5.56462558
theta[6]   6.04907398 0.10090125 6.9031658  -9.151907   2.1255389   6.51425111
theta[7]  10.72599576 0.10535483 6.7468001  -1.009178   6.1467118  10.04324676
theta[8]   8.20910316 0.13176080 7.9060904  -7.803945   3.5529484   8.00553271
lp__     -39.55967674 0.07367432 2.7016385 -45.628079 -41.1960640 -39.28625655
                 75%      97.5%    n_eff      Rhat
mu        11.1296936  17.933419 2301.855 1.0013353
tau        9.1378881  19.872780 1545.949 1.0031965
eta[1]     1.0254985   2.185951 4764.138 1.0002416
eta[2]     0.5559867   1.665973 3971.513 0.9998803
eta[3]     0.4187812   1.715261 4902.509 0.9994278
eta[4]     0.5481243   1.765195 4427.497 0.9995790
eta[5]     0.2095587   1.449096 3485.714 0.9996390
eta[6]     0.3658847   1.621667 4772.084 1.0000531
eta[7]     0.9330814   2.027340 4529.667 0.9999682
eta[8]     0.7051458   1.866920 4465.903 1.0001118
theta[1]  15.4497806  31.419674 3287.412 1.0022790
theta[2]  11.5635763  20.497102 5565.892 0.9993984
theta[3]  10.7691537  20.758137 3789.493 0.9997359
theta[4]  11.6365620  21.281938 4757.169 0.9993749
theta[5]   9.4348125  16.771748 4259.903 1.0007186
theta[6]  10.4166329  18.420472 4680.622 1.0004774
theta[7]  14.6650949  26.055385 4100.972 1.0001600
theta[8]  12.5570847  25.049819 3600.403 1.0005214
lp__     -37.6848772 -35.036931 1344.690 1.0008574

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.885765 0.1061225 5.091506 1.5374587 14.30311 2301.855 1.001335
tau 6.575141 0.1385362 5.447043 0.9804941 13.92671 1545.949 1.003196

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.5374587 14.30311
tau 0.9804941 13.92671


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.8091113 0.9133983 0.9391819 0.9116711
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 4 4 4 5


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] 0.2502151

$tau
[1] 5.252418

$eta
[1] -0.2221003  1.3458764 -0.1199722 -1.0650360  1.7317776 -1.9053836 -0.1820232
[8] -0.6494678

$theta
[1] -0.9163484  7.3193210 -0.3799289 -5.3437994  9.3462352 -9.7576563 -0.7058470
[8] -3.1610616


(P)RNG seed

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

print(get_seed(fit))
[1] 1877720004


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.021  0.015
chain:2  0.025  0.027
chain:3  0.023  0.038
chain:4  0.025  0.027