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"
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) function 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] -2.084350 3.260267 8.745208 6.170586 11.195565 11.152329
head(list_of_draws$tau)
[1] 8.370224 12.943845 19.370003 3.120488 14.901105 1.290637
head(list_of_draws$theta)
iterations [,1] [,2] [,3] [,4] [,5]
[1,] 15.210256 -1.852729 0.66484946 3.0329038 -12.015565
[2,] 14.358175 1.825837 -9.32030583 0.9541714 -2.354849
[3,] 25.853763 7.747521 13.92746846 2.3013293 -8.742198
[4,] 3.701011 9.017647 0.08693733 6.0868513 8.065210
[5,] 15.504647 -3.415650 5.34605564 15.9829446 2.784469
[6,] 12.401836 10.325730 10.05556904 11.1593639 10.976051
iterations [,6] [,7] [,8]
[1,] 2.055806 0.372758 2.568031
[2,] -10.415389 29.835874 3.545465
[3,] -3.997713 19.977181 10.521570
[4,] 7.581508 5.717939 9.269729
[5,] 7.911253 10.967054 -6.481475
[6,] 8.690259 11.083815 10.537022
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,] 3.477189 10.516983
[2,] 10.279402 6.357327
[3,] 9.991988 6.532370
[4,] 5.648669 6.544317
[5,] 15.432545 9.488765
[6,] 3.772203 6.452969
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.660630530 0.12670159 4.8986649 -1.9012523 4.4740177
tau 6.378119795 0.15381056 5.4170982 0.2127316 2.3287640
eta[1] 0.376734130 0.01664676 0.9243349 -1.5254877 -0.2353968
eta[2] 0.011411499 0.01412896 0.8566048 -1.7152716 -0.5371076
eta[3] -0.179014908 0.01453097 0.9190193 -2.0064361 -0.7948001
eta[4] 0.003489828 0.01499329 0.8659118 -1.6707630 -0.5583425
eta[5] -0.316543779 0.01570160 0.8583787 -2.0146666 -0.8730942
eta[6] -0.210541272 0.01497987 0.8593656 -1.8802686 -0.7843831
eta[7] 0.337534699 0.01643547 0.8630937 -1.4379886 -0.2373123
eta[8] 0.048367864 0.01620119 0.9239220 -1.7298459 -0.5694289
theta[1] 10.948680427 0.16137617 7.9471018 -1.9321403 5.8146691
theta[2] 7.780490561 0.09862214 6.2374120 -4.3974203 3.8500355
theta[3] 6.033941343 0.14495472 7.6297296 -11.3226605 1.9074771
theta[4] 7.513045436 0.11229283 6.4397480 -5.5255597 3.5428951
theta[5] 5.086693879 0.09889334 6.2545641 -8.5810771 1.4726241
theta[6] 6.016150530 0.11288859 6.4588830 -7.8911233 2.2079590
theta[7] 10.234893232 0.11511377 6.4599922 -1.3880187 5.9217927
theta[8] 8.113033994 0.12655558 7.4593450 -6.8547356 3.8413985
lp__ -39.407715347 0.07611112 2.5483874 -45.2178690 -40.9161446
50% 75% 97.5% n_eff Rhat
mu 7.61294100 10.7289393 17.428330 1494.828 1.0025865
tau 5.20555343 8.9588378 20.226884 1240.398 1.0045107
eta[1] 0.38686554 1.0050612 2.164465 3083.181 1.0007988
eta[2] 0.01101529 0.5780660 1.691733 3675.702 0.9996258
eta[3] -0.18790317 0.4148696 1.668176 4000.000 0.9998477
eta[4] -0.02209771 0.5634043 1.718963 3335.442 1.0012894
eta[5] -0.32233547 0.2240705 1.431428 2988.617 0.9996588
eta[6] -0.22579288 0.3611567 1.496558 3291.093 1.0001976
eta[7] 0.36179695 0.9123188 1.999456 2757.730 1.0012209
eta[8] 0.04790445 0.6744077 1.857211 3252.197 0.9999573
theta[1] 9.89797009 14.9031719 29.555109 2425.151 1.0012430
theta[2] 7.82695756 11.4363461 20.993767 4000.000 0.9998802
theta[3] 6.57483454 10.7139365 20.583467 2770.471 1.0021669
theta[4] 7.72119996 11.4672507 20.154463 3288.772 1.0009829
theta[5] 5.55722333 9.3457024 16.218718 4000.000 1.0004978
theta[6] 6.45955803 10.3485025 17.712019 3273.518 1.0008193
theta[7] 9.67721824 14.0474831 24.879937 3149.267 1.0012385
theta[8] 7.97749869 12.1665368 23.872224 3474.072 0.9994894
lp__ -39.17676469 -37.6529163 -35.129276 1121.075 1.0046112
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.660631 0.1267016 4.898665 1.4446260 13.89384 1494.828 1.002586
tau 6.378120 0.1538106 5.417098 0.9553664 13.16897 1240.398 1.004511
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.4446260 13.89384
tau 0.9553664 13.16897
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.9004148 0.9079614 0.8067289 0.8771056
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 4 4 4 4
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.3266236
$tau
[1] 0.2621781
$eta
[1] -1.1920366 -1.3056395 -0.8993741 0.7011695 0.6477077 -0.2637617
[7] 1.8353844 1.9857074
$theta
[1] 0.01409769 -0.01568647 0.09082741 0.51045481 0.49643832 0.25747104
[7] 0.80782109 0.84723250
The get_seed
function returns the (P)RNG seed as an integer:
print(get_seed(fit))
[1] 311726855
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.029005 0.034145
chain:2 0.026610 0.054124
chain:3 0.043405 0.027770
chain:4 0.035490 0.032698