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 6 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] 16.7171106 7.0089327 13.8497856 8.1877739 16.2616201 0.2744798
head(list_of_draws$tau)
[1] 9.364586 5.827724 2.750543 5.755315 17.285360 6.519455
head(list_of_draws$theta)
iterations [,1] [,2] [,3] [,4] [,5] [,6]
[1,] 28.453957 12.419106 15.516747 2.5574035 2.263467 8.472571
[2,] 4.528674 6.499778 5.451932 9.0888057 7.729877 15.774053
[3,] 12.771530 15.425695 14.692907 15.6969563 11.451342 13.361527
[4,] 16.865500 10.286443 6.221658 3.1859018 10.620816 7.234169
[5,] 6.162221 -2.495423 2.672620 11.7757129 11.302094 2.235750
[6,] -1.771098 3.133499 -7.037659 0.4147378 -5.067782 7.350022
iterations [,7] [,8]
[1,] 10.275118 7.109640
[2,] 9.786837 13.275637
[3,] 14.179742 16.037178
[4,] 1.655779 8.505250
[5,] 40.527431 39.129386
[6,] -1.817790 -1.918773
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,] 0.6756168 5.195072
[2,] -7.2571368 4.375244
[3,] 15.3683884 23.374643
[4,] 8.0645033 8.885693
[5,] 17.1224076 18.788788
[6,] 5.0349269 4.160703
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.867437257 0.15892994 5.2322650 -3.0169813 4.7147520
tau 6.626935741 0.19019763 5.7613092 0.1737095 2.4807924
eta[1] 0.396827865 0.01627226 0.9275331 -1.5256002 -0.2000294
eta[2] -0.006368546 0.01328615 0.8402902 -1.6991468 -0.5450760
eta[3] -0.191327564 0.01481920 0.9372484 -2.0228163 -0.8124606
eta[4] -0.035986863 0.01656904 0.8881159 -1.7745613 -0.6244789
eta[5] -0.332255738 0.01540108 0.8833728 -1.9872840 -0.9283984
eta[6] -0.224296508 0.01463412 0.8984994 -1.9776206 -0.8261355
eta[7] 0.350649240 0.01609166 0.8699195 -1.4356473 -0.1846289
eta[8] 0.047486827 0.01480290 0.9208317 -1.7850992 -0.5754983
theta[1] 11.464238735 0.16626091 8.1151701 -1.6475632 6.2056897
theta[2] 7.915108292 0.09978144 6.3107324 -4.9134723 4.0150828
theta[3] 6.021132930 0.18111965 8.2309200 -13.3073636 1.8506294
theta[4] 7.596581797 0.10619192 6.7161669 -6.6137648 3.6826139
theta[5] 5.201923246 0.09964162 6.3018894 -8.6581500 1.4164270
theta[6] 6.062592547 0.10705827 6.7709598 -9.2353176 2.1205098
theta[7] 10.738499073 0.12872914 6.8079375 -1.2781340 6.2858491
theta[8] 8.356702760 0.15623191 8.0433969 -8.2129703 3.7558798
lp__ -39.535694262 0.08164855 2.6859544 -45.4302715 -41.1898997
50% 75% 97.5% n_eff Rhat
mu 7.942005114 11.2095766 17.572268 1083.8471 1.0031900
tau 5.281556602 9.1208956 21.038118 917.5551 1.0018634
eta[1] 0.412384312 1.0109350 2.185451 3249.1016 1.0005115
eta[2] -0.005741722 0.5352601 1.681856 4000.0000 1.0001097
eta[3] -0.195891532 0.4293761 1.720477 4000.0000 0.9991624
eta[4] -0.035225155 0.5493171 1.755505 2873.0589 1.0008162
eta[5] -0.340544223 0.2113004 1.498730 3289.9223 0.9998935
eta[6] -0.252501676 0.3734116 1.588361 3769.6616 1.0002139
eta[7] 0.356383153 0.9084446 2.102802 2922.5146 0.9997448
eta[8] 0.065672990 0.6594844 1.874076 3869.6055 1.0001271
theta[1] 10.176985161 15.4002992 31.315389 2382.4016 1.0006378
theta[2] 7.948040116 11.8865137 20.772755 4000.0000 0.9992118
theta[3] 6.734007130 11.0056881 21.062308 2065.2167 1.0000704
theta[4] 7.708573058 11.6103918 21.004689 4000.0000 1.0001788
theta[5] 5.636407514 9.5517247 16.167929 4000.0000 0.9998475
theta[6] 6.415524998 10.4281735 18.544505 4000.0000 1.0000755
theta[7] 10.138860417 14.6122868 26.070278 2796.9029 0.9995220
theta[8] 8.171516672 12.5619846 25.653657 2650.5713 1.0003065
lp__ -39.295331540 -37.6222979 -35.046677 1082.1820 0.9994835
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.867437 0.1589299 5.232265 1.7343878 14.28952 1083.8471 1.003190
tau 6.626936 0.1901976 5.761309 0.8959336 14.01834 917.5551 1.001863
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.7343878 14.28952
tau 0.8959336 14.01834
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.7646803 0.7679597 0.8134928 0.9248611
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 5 4 5 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] -1.02428
$tau
[1] 1.65887
$eta
[1] 1.4258287 1.5160555 -1.1737508 0.7662169 -0.6876157 -1.9135261
[7] 0.6225471 -0.8279610
$theta
[1] 1.340984517 1.490659059 -2.971380411 0.246774095 -2.164945397
[6] -4.198571598 0.008444555 -2.397760033
The get_seed
function returns the (P)RNG seed as an integer:
print(get_seed(fit))
[1] 1987613865
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.031084 0.031025
chain:2 0.030385 0.019742
chain:3 0.032238 0.025778
chain:4 0.032997 0.034627