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] -6.276047 1.344294 8.091338 5.845875 16.083310 8.809855
head(list_of_draws$tau)
[1] 14.466417 12.872911 2.893916 2.388616 2.097061 11.031117
head(list_of_draws$theta)
iterations [,1] [,2] [,3] [,4] [,5] [,6]
[1,] 5.707907 -0.9795315 -4.199733 -5.823531 2.339937 4.174895
[2,] 35.564288 14.3393385 4.981956 2.204640 -7.215463 -2.636363
[3,] 6.886516 7.5936778 9.653965 12.435257 8.749012 6.151100
[4,] 7.432308 7.3584593 5.066040 3.404748 5.472732 5.907813
[5,] 14.732808 19.1843788 19.712371 16.500432 16.023648 16.363377
[6,] 12.721456 2.8025802 -1.730896 14.235220 -4.710246 8.978773
iterations [,7] [,8]
[1,] -0.9001932 -14.083084
[2,] 10.4235365 18.043883
[3,] 12.0276013 5.215260
[4,] 4.8086414 3.950983
[5,] 13.8665682 17.950000
[6,] 13.0247363 13.324270
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,] 8.744491 10.562647
[2,] 9.264328 10.577506
[3,] 12.903461 14.225632
[4,] 2.497118 1.758754
[5,] 4.440796 4.997625
[6,] 2.698263 20.556200
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.86148438 0.12753266 4.8300820 -1.7918963 4.7395162
tau 6.70219563 0.20248791 5.8637199 0.2405171 2.4213348
eta[1] 0.40149342 0.01706681 0.9230680 -1.4830596 -0.2023921
eta[2] 0.01600963 0.01765975 0.8846990 -1.7946696 -0.5291555
eta[3] -0.19293569 0.01644593 0.9051616 -1.9009074 -0.7946193
eta[4] -0.03283513 0.01602812 0.8498627 -1.7092759 -0.5941565
eta[5] -0.32996610 0.01683348 0.8801782 -2.0606766 -0.9079760
eta[6] -0.19577950 0.01612268 0.8829878 -1.8808660 -0.7855079
eta[7] 0.36916393 0.01634350 0.8764093 -1.4596656 -0.1963864
eta[8] 0.06898149 0.01639530 0.9119306 -1.7240897 -0.5396663
theta[1] 11.47748706 0.19620483 8.2440392 -1.8344491 6.1344852
theta[2] 7.95813571 0.11554857 6.1351284 -4.2937514 4.0588714
theta[3] 6.15629071 0.16611638 7.6195301 -11.2085573 2.1053873
theta[4] 7.58466638 0.12148665 6.4207187 -5.7696422 3.6277495
theta[5] 5.25450571 0.12688708 6.3283230 -8.9697851 1.7963793
theta[6] 6.17292946 0.12990543 6.5788951 -8.3914389 2.3333373
theta[7] 10.75411164 0.13107078 6.8167513 -1.0224569 6.1671136
theta[8] 8.54754978 0.16433606 7.7975178 -6.3983668 3.9458986
lp__ -39.42947571 0.09285406 2.7205017 -45.4879247 -41.0359810
50% 75% 97.5% n_eff Rhat
mu 7.78673083 10.8842143 17.697507 1434.3864 1.0022771
tau 5.23758504 9.2925211 22.169299 838.5872 1.0003869
eta[1] 0.43778629 1.0126995 2.154365 2925.2493 1.0010929
eta[2] 0.02959815 0.5850834 1.762342 2509.7023 1.0001635
eta[3] -0.20654996 0.3985029 1.631534 3029.2514 0.9997509
eta[4] -0.03929304 0.5109211 1.705013 2811.4619 1.0008490
eta[5] -0.33496118 0.2447991 1.406535 2733.9666 1.0009429
eta[6] -0.20335847 0.3686788 1.590020 2999.4048 1.0010229
eta[7] 0.36826321 0.9431162 2.096983 2875.5688 1.0006684
eta[8] 0.07803420 0.6887811 1.837870 3093.7481 0.9993515
theta[1] 10.34254458 15.5393405 31.703320 1765.4714 1.0013003
theta[2] 7.99937064 11.7496168 20.074333 2819.1499 1.0003666
theta[3] 6.69155893 10.8130326 20.219917 2103.9308 0.9997129
theta[4] 7.71296081 11.5527007 19.954796 2793.2523 1.0013579
theta[5] 5.82814753 9.4746726 16.312806 2487.3817 1.0010898
theta[6] 6.60229859 10.4192578 18.275167 2564.7871 1.0009509
theta[7] 10.11041201 14.5051106 26.508891 2704.8496 0.9999300
theta[8] 8.19844696 12.8313910 26.528845 2251.3707 0.9998565
lp__ -39.18117470 -37.5653508 -34.843985 858.4129 0.9998218
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.861484 0.1275327 4.830082 1.8573775 13.99563 1434.3864 1.002277
tau 6.702196 0.2024879 5.863720 0.8820313 14.14015 838.5872 1.000387
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.8573775 13.99563
tau 0.8820313 14.14015
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.8040218 0.7913391 0.8099770 0.8366751
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 4 4 4 3
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.8231868
$tau
[1] 0.6438974
$eta
[1] 1.8225687 -1.5903694 -1.4833296 -1.5002977 0.1629245 -0.4686030
[7] -1.7340126 -0.4329439
$theta
[1] 0.3503605 -1.8472214 -1.7782988 -1.7892246 -0.7182801 -1.1249190
[7] -1.9397129 -1.1019582
The get_seed
function returns the (P)RNG seed as an integer:
print(get_seed(fit))
[1] 404490918
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.063096 0.061737
chain:2 0.064230 0.061255
chain:3 0.063495 0.080767
chain:4 0.062865 0.053319