Accessing the contents of a stanfit object

Stan Development Team

2022-04-08

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]  4.907648  8.727050 15.783106 12.586313  9.884403 11.586465
[1] 10.873088  7.155413  7.140602  6.055600  6.341230 10.964064
          
iterations      [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
      [1,] 11.307802 24.613525 -8.319838  6.252491 -4.149550 -7.123672
      [2,]  9.065953  3.856298 11.897451  5.669981  9.294551  7.899273
      [3,] 15.197806 12.964396  7.995638 12.271958 13.406672 10.429795
      [4,]  9.297685 13.035339 -7.813169 17.604805  6.781981 12.016717
      [5,] -1.134324 22.988234  2.705344  9.889411 11.240321  8.685885
      [6,] 14.787721 12.492520 21.756074 23.490745  4.457762 13.134247
          
iterations      [,7]      [,8]
      [1,] 24.416761  5.037623
      [2,]  4.795870  2.222219
      [3,] 20.369619 19.079338
      [4,] 14.767485 -4.356055
      [5,] 12.270619 13.272563
      [6,]  9.711187  8.529641


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,] 14.1955661 19.0113830
      [2,] 13.1343525 21.1267805
      [3,] 10.5131757 23.3201809
      [4,] 15.4221705 24.9375946
      [5,]  2.3589062  1.2938977
      [6,] -0.1226935 -0.9721329


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.88763675 0.10174355 4.8725695  -1.6334352   4.6168343   7.88390830
tau        6.39963596 0.13062575 5.1084106   0.2421601   2.5406477   5.17092123
eta[1]     0.39874704 0.01694202 0.9454198  -1.5392437  -0.2077704   0.43504485
eta[2]     0.02187903 0.01509872 0.8595177  -1.6581677  -0.5256461   0.02738767
eta[3]    -0.19303848 0.01567759 0.9363480  -1.9986915  -0.8248729  -0.19460532
eta[4]    -0.04024082 0.01492173 0.9085991  -1.8622029  -0.6211694  -0.04918630
eta[5]    -0.34893913 0.01491647 0.8611373  -1.9869294  -0.8968783  -0.37885267
eta[6]    -0.22818945 0.01530444 0.8975948  -2.0149189  -0.8226240  -0.22841540
eta[7]     0.34627407 0.01678637 0.9036232  -1.4799548  -0.2455455   0.35932664
eta[8]     0.08117311 0.01468410 0.9452070  -1.7748226  -0.5544617   0.07122163
theta[1]  11.41351094 0.15788770 8.1510302  -2.0244325   6.0065441  10.38526766
theta[2]   8.00593503 0.10002544 6.2610371  -4.5518025   4.1083872   7.93763593
theta[3]   6.08133277 0.14957634 7.8216683 -11.4131635   1.8077092   6.68531411
theta[4]   7.63543053 0.10080308 6.4630306  -5.8754534   3.6742169   7.74179802
theta[5]   5.19892713 0.09451408 6.2679789  -8.8059150   1.4825604   5.68988458
theta[6]   6.22008052 0.11232597 6.7275134  -8.2405912   2.3680631   6.48150993
theta[7]  10.66885827 0.11522201 6.6731675  -1.1683853   6.1360834  10.06907657
theta[8]   8.49262429 0.13972780 7.9722370  -7.3359293   4.0151967   8.37105298
lp__     -39.57847695 0.07973052 2.6653984 -45.5576011 -41.1417123 -39.39687089
                 75%      97.5%    n_eff      Rhat
mu        11.1884603  17.555841 2293.519 1.0006637
tau        9.1039684  18.351291 1529.375 0.9999780
eta[1]     1.0221692   2.156661 3114.001 1.0000146
eta[2]     0.5751222   1.788922 3240.631 1.0008842
eta[3]     0.4338887   1.671562 3567.107 1.0003171
eta[4]     0.5661027   1.798295 3707.713 0.9998958
eta[5]     0.1846316   1.420011 3332.827 0.9994787
eta[6]     0.3476539   1.613537 3439.740 0.9995833
eta[7]     0.9424768   2.151903 2897.753 1.0002707
eta[8]     0.7055036   1.971079 4143.423 1.0001472
theta[1]  15.6516565  30.350440 2665.192 0.9993375
theta[2]  12.0088361  20.642301 3918.065 1.0006025
theta[3]  11.0010793  20.528775 2734.469 1.0008197
theta[4]  11.6542028  20.140606 4110.786 0.9996873
theta[5]   9.4469263  16.152555 4398.069 0.9995133
theta[6]  10.4505290  18.858406 3587.144 1.0000941
theta[7]  14.5783058  25.717159 3354.232 0.9996433
theta[8]  12.7767027  25.373095 3255.328 1.0009119
lp__     -37.6458422 -35.160523 1117.571 1.0008905

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.887637 0.1017435 4.872570 1.543267 14.02951 2293.519 1.000664
tau 6.399636 0.1306257 5.108411 1.030058 13.47771 1529.375 0.999978

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.543267 14.02951
tau 1.030058 13.47771


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.7664522 0.9271903 0.7488337 0.8348065
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.8065645

$tau
[1] 1.364928

$eta
[1] -1.0553911  1.6514577 -1.7294842 -1.8510384 -0.8368269 -1.6044617 -1.7214629
[8]  1.9203917

$theta
[1] -2.247097  1.447556 -3.167186 -3.333099 -1.948773 -2.996539 -3.156237
[8]  1.814632


(P)RNG seed

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

print(get_seed(fit))
[1] 222908970


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.039216 0.024394
chain:2 0.036035 0.040466
chain:3 0.035534 0.030702
chain:4 0.037088 0.032023