Accessing the contents of a stanfit object

Stan Development Team

2016-12-28

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. 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] 0.1918428 2.7525145 2.9338555 2.4851729 2.9938300 6.4762800
head(list_of_draws$tau)
[1]  4.958288  8.162640  5.123909  5.402533  3.523353 13.594075
head(list_of_draws$theta)
          
iterations      [,1]       [,2]        [,3]       [,4]       [,5]     [,6]
      [1,]  3.781077  0.9461683 -0.66575821  6.3953394 -7.7761697 2.792552
      [2,]  3.483947  3.9612480  8.05559747 -1.9883135  0.1219574 9.607624
      [3,]  1.627558  4.4237801 -0.04246828 -0.6903147  0.9148411 4.019601
      [4,]  9.488085  7.8098342 -3.31569480 -1.0968917  8.3659423 6.063906
      [5,]  3.520259  4.9659016 -1.68729992  7.0645555  9.1705344 3.103952
      [6,] 20.978418 11.0378340 16.24589496  8.5292676  5.2703316 1.893699
          
iterations        [,7]       [,8]
      [1,]  0.05130667 -1.3863444
      [2,] -2.12527682  2.9931911
      [3,] 16.58203560  3.3411102
      [4,]  9.03247509  0.5086259
      [5,]  5.12634253  4.5176642
      [6,]  6.63218539  2.2184181


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,]  9.9517932 15.2384913
      [2,] 11.4724031 11.9530087
      [3,] 16.1433788 17.9815749
      [4,] -0.5957746  0.7019507
      [5,]  2.3457693  0.2228519
      [6,]  5.4070436 17.0271083


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.86799800 0.10662963 4.9217422  -1.8354272   4.6332082
tau        6.27764968 0.16113273 5.3965473   0.1959559   2.3914635
eta[1]     0.37674896 0.01640885 0.9473873  -1.5506912  -0.2526270
eta[2]    -0.00323991 0.01380036 0.8619471  -1.7479182  -0.5699341
eta[3]    -0.17614796 0.01640252 0.9307869  -1.9240390  -0.8267083
eta[4]    -0.02970133 0.01473376 0.8951438  -1.7647504  -0.6199526
eta[5]    -0.32765396 0.01566645 0.9112051  -2.0833248  -0.9462620
eta[6]    -0.17648594 0.01556463 0.8938928  -1.9036378  -0.7679067
eta[7]     0.33584465 0.01699721 0.8940393  -1.4871514  -0.2245970
eta[8]     0.04264788 0.01474508 0.9325608  -1.7244342  -0.5931117
theta[1]  11.07381121 0.15387741 8.0601096  -2.5417886   5.8516865
theta[2]   7.97221659 0.09810210 6.2045216  -4.6116895   4.1905999
theta[3]   6.20342501 0.16359209 7.8829909 -11.6570612   2.2628827
theta[4]   7.67135311 0.10052734 6.3579075  -5.1289342   3.8030840
theta[5]   5.35676102 0.10275590 6.4988538  -9.6296949   1.6926472
theta[6]   6.28540642 0.10503208 6.6428123  -8.6823092   2.6027384
theta[7]  10.69707537 0.11851290 6.7923297  -0.9302766   6.1573982
theta[8]   8.32350693 0.14681495 7.9347566  -7.9072642   3.7736639
lp__     -39.64678810 0.07627834 2.6172068 -45.4797958 -41.2508943
                  50%         75%      97.5%    n_eff      Rhat
mu         7.87116112  11.0337688  17.833674 2130.502 1.0006856
tau        5.02653345   8.7631542  19.274861 1121.668 1.0024870
eta[1]     0.39533129   1.0300437   2.156344 3333.488 1.0005870
eta[2]     0.01841221   0.5727731   1.648863 3901.041 0.9998967
eta[3]    -0.19196360   0.4370510   1.651364 3220.175 0.9997577
eta[4]    -0.03592233   0.5524715   1.782602 3691.121 1.0002275
eta[5]    -0.33393119   0.2693459   1.540539 3382.915 0.9995419
eta[6]    -0.20301303   0.4074410   1.679429 3298.324 1.0020175
eta[7]     0.36057610   0.9193941   1.996400 2766.674 0.9998384
eta[8]     0.03356431   0.6835376   1.884688 4000.000 0.9996460
theta[1]   9.92166484  15.0903456  30.473599 2743.672 1.0006287
theta[2]   7.95860025  11.7499337  20.233027 4000.000 0.9999558
theta[3]   6.82238754  10.9143105  20.695641 2321.974 1.0004085
theta[4]   7.54896551  11.5844618  20.451921 4000.000 0.9999093
theta[5]   5.84314303   9.5750732  16.965198 4000.000 0.9996760
theta[6]   6.69842266  10.5520154  18.708159 4000.000 1.0003362
theta[7]   9.95171026  14.6551619  26.037501 3284.780 0.9992323
theta[8]   7.99340717  12.6743689  26.061404 2920.967 1.0007071
lp__     -39.39738459 -37.8189882 -35.223695 1177.263 1.0011848

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.867998 0.1066296 4.921742 1.7927700 14.02136 2130.502 1.000686
tau 6.277650 0.1611327 5.396547 0.9095436 12.86726 1121.668 1.002487

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.7927700 14.02136
tau 0.9095436 12.86726


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.8295204 0.7994754 0.8420772 0.8765889
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 5 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.5629321

$tau
[1] 0.2903741

$eta
[1]  0.4795601  0.4850170 -0.8729951  0.5627613 -0.3524287 -1.7468493
[7] -0.7472970  1.8054111

$theta
[1] -0.42368026 -0.42209569 -0.81642720 -0.39952076 -0.66526822 -1.07017180
[7] -0.77992774 -0.03868748


(P)RNG seed

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

print(get_seed(fit))
[1] 331435434


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.033336 0.025449
chain:2 0.032405 0.021598
chain:3 0.030668 0.034357
chain:4 0.030953 0.031631