Accessing the contents of a stanfit object

Stan Development Team

2018-10-15

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 7 divergent transitions after warmup. Increasing adapt_delta above 0.8 may help. See
http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
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]  1.430835  3.504714  9.725051  2.966655  4.303380 -2.387750
head(list_of_draws$tau)
[1] 12.2144136 15.8144305 11.3591926  0.2235964  4.8859030  6.7034105
head(list_of_draws$theta)
          
iterations      [,1]      [,2]       [,3]       [,4]      [,5]        [,6]
      [1,] 22.334163 -2.997976 -2.8776930 -0.8480270  3.459989 -13.1802028
      [2,] 28.089985  3.132455  0.1999556 18.2216965  5.665701   0.7264871
      [3,] 19.936441  1.935211  3.3791490 14.5740874 20.354571   8.4910330
      [4,]  2.852208  3.229695  2.9875979  2.7578578  3.202504   3.0671686
      [5,]  4.967234 -1.237070  6.4082698 10.4861581  3.208666  10.7337528
      [6,] -1.141533 -8.919631  3.1559991 -0.2474029 -5.383388   6.4620609
          
iterations      [,7]      [,8]
      [1,]  7.783433  3.265144
      [2,] 13.091820 15.387439
      [3,] 14.547657 14.912129
      [4,]  3.279478  2.762896
      [5,]  3.441809  4.177468
      [6,]  9.026767  1.142228


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,] -1.146758 18.355191
      [2,]  3.220000 20.902001
      [3,]  1.119717  4.965709
      [4,] -1.844905  4.535402
      [5,] -2.065734  4.047685
      [6,]  4.139765 11.257879


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         7.730108288 0.14459981 5.2790352  -2.6984757   4.5214611
tau        6.560395227 0.15576523 5.4800694   0.2660985   2.5096618
eta[1]     0.381533904 0.01723061 0.9318420  -1.5662024  -0.2411105
eta[2]    -0.003358401 0.01370125 0.8557250  -1.7291088  -0.5588681
eta[3]    -0.180840965 0.01451123 0.9006280  -1.9757967  -0.7915897
eta[4]    -0.021804908 0.01489504 0.8868735  -1.7663254  -0.6045515
eta[5]    -0.324228182 0.01686755 0.8782904  -2.0819417  -0.8969234
eta[6]    -0.195979323 0.01668265 0.9010309  -1.9376042  -0.7872774
eta[7]     0.341379230 0.01541481 0.8847003  -1.4115421  -0.2384917
eta[8]     0.058103989 0.01523697 0.9515448  -1.8133143  -0.5790083
theta[1]  11.418993427 0.17115257 8.4912715  -2.6253925   5.8261816
theta[2]   7.813850430 0.10277459 6.3903433  -5.3102896   3.8984618
theta[3]   6.145704585 0.13057239 7.7285078 -11.4550937   2.0436472
theta[4]   7.697289867 0.10113953 6.6328798  -5.6733243   3.6479767
theta[5]   5.206737769 0.10034706 6.3589070  -8.8386560   1.5225414
theta[6]   6.199496135 0.10355810 6.7144151  -8.7253090   2.3573641
theta[7]  10.551030087 0.12296316 6.8515160  -1.5664597   5.8842680
theta[8]   8.363230638 0.13343344 7.9138340  -7.4963819   3.9057119
lp__     -39.534379697 0.07311720 2.5428709 -45.1117655 -41.1286052
                   50%         75%      97.5%    n_eff      Rhat
mu         7.875041642  11.1832979  17.428528 1332.827 1.0027071
tau        5.301537884   9.0992035  20.283176 1237.745 1.0025941
eta[1]     0.420271014   1.0088080   2.119035 2924.712 1.0031447
eta[2]     0.001063328   0.5648413   1.656638 3900.750 0.9998121
eta[3]    -0.178767421   0.3957549   1.543455 3851.967 1.0001558
eta[4]    -0.019159364   0.5722564   1.744822 3545.196 1.0016175
eta[5]    -0.332673533   0.2391698   1.404413 2711.266 1.0001115
eta[6]    -0.197767904   0.3955593   1.574759 2917.085 0.9999257
eta[7]     0.358434061   0.9289171   2.067275 3293.941 0.9998881
eta[8]     0.067735421   0.6937909   1.941039 3899.969 0.9996248
theta[1]  10.249320615  15.6883767  31.636877 2461.380 1.0007903
theta[2]   7.937282011  11.7585852  19.984375 3866.133 0.9996083
theta[3]   6.767898149  10.7642962  20.147545 3503.391 1.0010309
theta[4]   7.742414107  11.7095840  21.060924 4300.930 0.9999037
theta[5]   5.648341206   9.5043183  16.536599 4015.648 1.0004567
theta[6]   6.624236704  10.4407304  18.516141 4203.860 1.0004547
theta[7]   9.904433956  14.5438293  25.626984 3104.726 1.0012889
theta[8]   8.241043701  12.5224930  24.748478 3517.584 0.9997728
lp__     -39.308604457 -37.7198374 -35.160655 1209.510 1.0023275

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.730108 0.1445998 5.279035 1.3110203 14.21195 1332.827 1.002707
tau 6.560395 0.1557652 5.480069 0.9408529 13.58158 1237.745 1.002594

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.3110203 14.21195
tau 0.9408529 13.58158


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.7476184 0.8172834 0.8701314 0.8468849
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 5 4 5 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] -0.101288

$tau
[1] 2.849633

$eta
[1]  1.6564729 -1.9987074 -0.9162902 -1.9720027  1.7070757  0.7881628
[7]  0.1425916 -1.4028452

$theta
[1]  4.6190525 -5.7968710 -2.7123790 -5.7207726  4.7632517  2.1446871
[7]  0.3050457 -4.0988825


(P)RNG seed

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

print(get_seed(fit))
[1] 1226905799


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.032811 0.031925
chain:2 0.032656 0.021643
chain:3 0.031212 0.030269
chain:4 0.034543 0.022889