Accessing the contents of a stanfit object

Stan Development Team

2024-03-04

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 3 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]  0.4833887 11.6850005 -3.3141669 -1.1598781  3.3806820 12.5507635
[1] 20.736801  6.002451 25.372611  2.666828  3.549650  1.078036
          
iterations      [,1]      [,2]        [,3]      [,4]       [,5]      [,6]
      [1,] 38.990737 16.287114 -11.8025114 11.063405 -4.3885999  6.387578
      [2,] 16.285434  5.575360   7.9333888 14.673914 10.4915338  1.639833
      [3,]  8.857648 11.587368  -5.3230698 -7.071244 -2.1626789  8.525583
      [4,] -4.051336 -3.206878   0.1157556 -9.633611 -0.6574029 -1.550585
      [5,]  8.429137  8.525984   3.2993868  4.504439  4.9565802 -2.691472
      [6,] 12.133429 12.197865  13.2499500 10.900420 12.2274181 13.234744
          
iterations      [,7]      [,8]
      [1,]  9.880457 13.516355
      [2,]  7.966316  9.850148
      [3,] -4.982988 14.041399
      [4,] -3.021736 -2.028627
      [5,]  6.112344  4.727819
      [6,] 15.015829 13.191878


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,]  7.680122  5.583360
      [2,]  6.146427  8.391114
      [3,]  3.345247  2.542456
      [4,] 11.190611 11.095583
      [5,]  7.331734 23.847581
      [6,]  1.999966  3.777700


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.75110327 0.11134056 5.1990038  -2.2690969   4.5036953   7.80630187
tau        6.80641050 0.17855223 6.0449436   0.2290198   2.4957338   5.33699182
eta[1]     0.38292109 0.01558869 0.9436183  -1.5917143  -0.2250060   0.41195951
eta[2]     0.01411281 0.01322934 0.8296821  -1.6041115  -0.5396589   0.01679256
eta[3]    -0.17201770 0.01307911 0.9337684  -1.9874583  -0.7838333  -0.17804855
eta[4]    -0.03832025 0.01475776 0.8836022  -1.8015636  -0.6169327  -0.03233633
eta[5]    -0.35330329 0.01488249 0.8715506  -2.0323830  -0.9046659  -0.37269697
eta[6]    -0.21318850 0.01432068 0.9109311  -2.0291215  -0.8150952  -0.23610678
eta[7]     0.36716141 0.01439726 0.8720225  -1.4001385  -0.1821243   0.36158066
eta[8]     0.06580386 0.01476528 0.9218926  -1.7831869  -0.5582930   0.05984778
theta[1]  11.30444959 0.16160030 8.3047480  -1.9758066   5.9323694  10.14824454
theta[2]   7.87409595 0.09331812 6.4029748  -4.6162975   3.8291169   7.76465969
theta[3]   6.12071272 0.14485185 8.2006024 -12.7047078   1.8579539   6.71433061
theta[4]   7.51752790 0.10077931 6.6291889  -6.0346728   3.5520111   7.57325747
theta[5]   4.92856284 0.11424483 6.5009916  -9.3626269   1.3123434   5.40143868
theta[6]   5.95562792 0.10429274 6.8094646  -8.8829227   2.0466017   6.32496123
theta[7]  10.63617997 0.11707419 6.8528602  -1.2758797   6.1083484  10.05169282
theta[8]   8.43429294 0.13356869 7.9117638  -6.4603252   3.6971623   8.19147859
lp__     -39.53080073 0.07796845 2.6531224 -45.5173608 -41.1490148 -39.27273980
                 75%      97.5%    n_eff      Rhat
mu        10.9648821  17.998741 2180.387 1.0008978
tau        9.3110793  21.826483 1146.183 1.0019109
eta[1]     1.0229613   2.181206 3664.151 0.9999360
eta[2]     0.5667655   1.639260 3933.211 0.9997361
eta[3]     0.4343433   1.688982 5097.084 0.9994307
eta[4]     0.5558925   1.738362 3584.862 0.9999318
eta[5]     0.1911258   1.480976 3429.526 0.9998895
eta[6]     0.3905723   1.634791 4046.167 1.0001813
eta[7]     0.9432225   2.084443 3668.563 0.9998580
eta[8]     0.6712317   1.886720 3898.316 0.9996972
theta[1]  15.3699317  31.735854 2641.001 0.9996094
theta[2]  11.8883959  20.818955 4707.948 0.9996209
theta[3]  11.0223594  20.971858 3205.114 1.0015387
theta[4]  11.6591670  20.769237 4326.912 0.9991702
theta[5]   9.2160925  16.331576 3238.069 0.9998848
theta[6]  10.2769144  18.871329 4263.024 0.9998840
theta[7]  14.6033579  26.065618 3426.269 0.9995218
theta[8]  12.6438700  25.611631 3508.628 0.9998167
lp__     -37.6609821 -35.118680 1157.915 1.0042178

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.751103 0.1113406 5.199004 1.3286256 14.03575 2180.387 1.000898
tau 6.806410 0.1785522 6.044944 0.9572097 14.48271 1146.183 1.001911

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.3286256 14.03575
tau 0.9572097 14.48271


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.7871779 0.9503414 0.9439005 0.8549200
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  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.465461

$tau
[1] 0.4536848

$eta
[1]  1.80765657  1.96017502 -1.64586306 -0.06034084  1.58046455 -1.08906201
[7] -1.02607606  0.73341405

$theta
[1] 2.2855675 2.3547628 0.7187580 1.4380854 2.1824939 0.9713702 0.9999460
[8] 1.7982000


(P)RNG seed

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

print(get_seed(fit))
[1] 2115685401


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.040  0.027
chain:2  0.037  0.043
chain:3  0.038  0.044
chain:4  0.038  0.035