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"
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.
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.3559109 3.3331417 4.2407457 6.7061639 7.4720038 0.9842034
head(list_of_draws$tau)
[1] 11.130762 1.163653 3.680448 19.289687 5.666112 3.338461
head(list_of_draws$theta)
iterations [,1] [,2] [,3] [,4] [,5]
[1,] 8.081323 -3.918504 9.0107586 13.7323836 -0.06071589
[2,] 2.745870 3.677658 4.0679999 3.2913520 4.89525176
[3,] 3.498343 1.573327 7.5134680 3.5478246 1.07504959
[4,] 10.343637 7.862416 -13.0101002 8.6707177 5.41591951
[5,] 14.709990 12.052368 8.4509238 3.6110559 4.68663520
[6,] 3.655390 -1.025292 0.2423516 0.6763032 3.46692764
iterations [,6] [,7] [,8]
[1,] -5.890430 8.379563 9.5778049
[2,] 2.521620 3.801042 4.1368544
[3,] 7.000340 4.444265 3.1837312
[4,] -2.523182 13.884803 5.8598612
[5,] 6.999736 11.322394 9.0130259
[6,] -5.633402 5.920665 -0.5789636
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,] 6.9733497 7.553633
[2,] 9.5525316 11.873146
[3,] 7.2138405 10.612248
[4,] 9.0137472 8.736418
[5,] -0.8058458 -2.810238
[6,] 10.3836470 10.138774
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.846542762 0.14615856 5.3190259 -2.6803802 4.6217651
tau 6.932599456 0.18179919 5.9843464 0.2717122 2.4800830
eta[1] 0.404974010 0.01417665 0.8966101 -1.4274458 -0.1938848
eta[2] -0.004890166 0.01430011 0.8742810 -1.8062763 -0.5557743
eta[3] -0.196734029 0.01408642 0.8909032 -1.9249173 -0.8178789
eta[4] -0.041306242 0.01377117 0.8709653 -1.7581837 -0.6042931
eta[5] -0.360647064 0.01399609 0.8851906 -2.0980445 -0.9400794
eta[6] -0.235000282 0.01422827 0.8998746 -1.8833527 -0.8481258
eta[7] 0.372005707 0.01357671 0.8586666 -1.4192038 -0.1487462
eta[8] 0.073874236 0.01441419 0.9116332 -1.6960532 -0.5372830
theta[1] 11.633081162 0.16814021 8.4326706 -1.7307603 6.0923453
theta[2] 7.726511401 0.10134299 6.4094934 -5.7499602 3.8947145
theta[3] 6.116920047 0.12464651 7.8833375 -11.9644983 1.7602485
theta[4] 7.547009168 0.10523050 6.6553611 -6.3861525 3.4728090
theta[5] 4.950749219 0.10136998 6.4112003 -9.0215309 1.0783388
theta[6] 5.811924165 0.10812357 6.8383351 -8.8410130 1.7347031
theta[7] 10.808776298 0.10812598 6.8384876 -1.1130679 6.2740376
theta[8] 8.654318898 0.13023385 7.8389272 -6.6224774 4.1250026
lp__ -39.379479754 0.07373413 2.5901266 -45.0529221 -40.9437841
50% 75% 97.5% n_eff Rhat
mu 7.86550904 11.0609287 17.795680 1324.389 1.0003605
tau 5.43311961 9.7618125 22.123107 1083.552 1.0022535
eta[1] 0.43709280 0.9992745 2.117800 4000.000 0.9996055
eta[2] -0.00743516 0.5455471 1.729069 3737.862 1.0012465
eta[3] -0.20509782 0.4144429 1.558685 4000.000 1.0004173
eta[4] -0.03933943 0.5226822 1.668647 4000.000 0.9996956
eta[5] -0.36541065 0.1975692 1.461931 4000.000 0.9997249
eta[6] -0.23975670 0.3632226 1.595606 4000.000 0.9995472
eta[7] 0.38514584 0.9178377 2.051558 4000.000 0.9999284
eta[8] 0.07095319 0.6855648 1.867764 4000.000 0.9996976
theta[1] 10.43539693 15.6759276 32.208523 2515.284 1.0004353
theta[2] 7.89254605 11.6013072 20.748211 4000.000 0.9998008
theta[3] 6.55518011 10.8617492 20.818931 4000.000 1.0005869
theta[4] 7.64125065 11.5874215 21.251021 4000.000 1.0002740
theta[5] 5.50005862 9.3085293 16.313939 4000.000 1.0012418
theta[6] 6.27358416 10.1837568 18.433044 4000.000 0.9996915
theta[7] 10.09494442 14.5924190 26.599472 4000.000 1.0009547
theta[8] 8.41222625 12.8495589 25.847198 3622.977 0.9998804
lp__ -39.16157657 -37.5208839 -35.035028 1233.971 1.0011261
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.846543 0.1461586 5.319026 1.439409 14.35236 1324.389 1.000360
tau 6.932599 0.1817992 5.984346 1.017692 14.60643 1083.552 1.002253
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.439409 14.35236
tau 1.017692 14.60643
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.8560590 0.7566069 0.7889185 0.8808886
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 4 5 5 5
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);
}
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.6774625
$tau
[1] 0.2142801
$eta
[1] 0.9833222 0.5412117 -1.7869726 -1.7783460 1.8677055 -0.8653542
[7] -0.8731875 -1.7979350
$theta
[1] 0.8881689 0.7934334 0.2945499 0.2963984 1.0776746 0.4920343 0.4903558
[8] 0.2922009
The get_seed
function returns the (P)RNG seed as an integer:
print(get_seed(fit))
[1] 834064332
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.031789 0.040296
chain:2 0.032003 0.023117
chain:3 0.027203 0.023861
chain:4 0.029420 0.041187