Accessing the contents of a stanfit object

Stan Development Team

2020-07-07

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.

[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.3674916  4.8055566  0.8586466 10.4966519  8.6989270 22.7688271
[1] 21.056801  2.080090  7.455668  4.503218  8.687556 25.213384
          
iterations      [,1]      [,2]      [,3]      [,4]      [,5]       [,6]
      [1,] 35.117318 11.211347  3.740578 -2.290273  4.512699 -7.0189318
      [2,]  5.784649  3.729776  4.508673  5.172839  5.272331  4.1914991
      [3,] 14.126243  7.238635 -9.234627  7.150078 11.397865  0.8500157
      [4,] 11.998398 13.119916  6.342323  8.479728  9.908833  7.5249413
      [5,] 17.915690  3.069502 -4.774833 -2.543817  4.067050  8.1231432
      [6,] 24.312153 -3.229884 14.224530 -4.397999 -5.231247 27.7578656
          
iterations      [,7]      [,8]
      [1,] 21.169473 12.411438
      [2,]  6.880652  5.828343
      [3,]  8.200449 -8.202977
      [4,] 10.167705 12.911613
      [5,] 17.233071 12.911214
      [6,] 16.331640 14.835067


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,] 22.243776  9.629561
      [2,] 22.329405 12.482998
      [3,]  8.590096 19.362906
      [4,]  7.042518  6.650096
      [5,] 10.689951 27.181187
      [6,] 10.617443 12.961224


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.13015954 0.12633837 5.1412739  -1.9174226   4.8667793
tau        6.87948078 0.18383266 6.1938312   0.2673477   2.6580489
eta[1]     0.39124119 0.01523796 0.9429156  -1.5031586  -0.2243996
eta[2]    -0.01029833 0.01342757 0.8562558  -1.7408243  -0.5647123
eta[3]    -0.19460112 0.01443218 0.9292162  -2.0109437  -0.7971363
eta[4]    -0.02621013 0.01348622 0.8828441  -1.7534899  -0.6082770
eta[5]    -0.37279879 0.01511920 0.8915325  -2.0972039  -0.9583312
eta[6]    -0.22964731 0.01349422 0.8735572  -2.0002377  -0.7921455
eta[7]     0.32113311 0.01491034 0.9128165  -1.5189056  -0.2553084
eta[8]     0.04561311 0.01343260 0.9159175  -1.7880569  -0.5365728
theta[1]  11.81110022 0.17226288 8.6163900  -2.0084034   6.0350519
theta[2]   8.01528621 0.09691527 6.3577277  -4.4838734   4.0055602
theta[3]   6.16796655 0.13197803 7.7358656 -11.4344984   2.0849247
theta[4]   7.66330253 0.10222368 6.8012285  -6.0293202   3.6078848
theta[5]   5.09051916 0.09330949 6.4360001  -8.6828535   1.2272099
theta[6]   6.13995377 0.09911885 6.5924569  -8.3917489   2.2203573
theta[7]  10.78296246 0.10717509 6.8559536  -1.0898332   6.1128682
theta[8]   8.54151489 0.14221037 8.0309288  -7.7172080   4.1078509
lp__     -39.49045486 0.07657030 2.6969716 -45.4478817 -41.0968887
                   50%         75%      97.5%    n_eff      Rhat
mu         8.012283475  11.3673404  18.431165 1656.041 0.9999173
tau        5.496411425   9.4834550  21.416289 1135.203 1.0012626
eta[1]     0.418583232   1.0254544   2.207682 3829.060 0.9995658
eta[2]     0.005363322   0.5343232   1.682875 4066.421 0.9993742
eta[3]    -0.215123681   0.3932733   1.686361 4145.431 0.9999895
eta[4]    -0.043764185   0.5621351   1.723550 4285.363 1.0000768
eta[5]    -0.387870769   0.1786616   1.447767 3477.095 1.0003724
eta[6]    -0.233960768   0.3408725   1.529396 4190.707 0.9996282
eta[7]     0.334682772   0.9230759   2.138267 3747.931 1.0001207
eta[8]     0.047048543   0.6408598   1.897547 4649.356 0.9997369
theta[1]  10.480622258  16.3914188  32.213197 2501.885 1.0000761
theta[2]   7.951131811  11.9417092  20.851119 4303.477 0.9995413
theta[3]   6.748519817  10.9345292  20.024568 3435.695 1.0008765
theta[4]   7.674607133  11.8092121  21.722970 4426.615 0.9993618
theta[5]   5.561938574   9.3999718  16.903329 4757.518 0.9997990
theta[6]   6.408003674  10.3951839  18.564395 4423.664 0.9997094
theta[7]  10.155310396  14.6876213  25.886587 4092.117 1.0004937
theta[8]   8.191065641  12.8037763  26.371176 3189.106 0.9997644
lp__     -39.217500158 -37.5748855 -34.945426 1240.601 1.0005075

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.130160 0.1263384 5.141274 1.901618 14.39876 1656.041 0.9999173
tau 6.879481 0.1838327 6.193831 1.016426 14.12134 1135.203 1.0012626

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.901618 14.39876
tau 1.016426 14.12134


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.8797518 0.9005388 0.9563192 0.8599441
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 4 4 5 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.7792279

$tau
[1] 6.642912

$eta
[1] -1.42777653  1.98938637 -0.01290542 -1.40126202  1.18456739 -1.34379760
[7]  0.81329273  0.94846507

$theta
[1] -8.7053654 13.9945457  0.6934983 -8.5292318  8.6482043 -8.1475008  6.1818596
[8]  7.0797975


(P)RNG seed

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

print(get_seed(fit))
[1] 200168961


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.037767 0.034136
chain:2 0.029538 0.030275
chain:3 0.034916 0.054101
chain:4 0.034591 0.035638