Load packages
library(tidyr)
library(dplyr)
library(rstan)
library(rstanarm)
options(mc.cores = 1)
library(loo)
library(shinystan)
library(ggplot2)
library(bayesplot)
theme_set(bayesplot::theme_default(base_family = "sans"))
library(ggdist)
library(gridExtra)
library(rprojroot)
root<-has_file(".BDA_R_demos_root")$make_fix_file()
SEED <- 48927 # set random seed for reproducability
This notebook contains several examples of how to use Stan in R with rstanarm. This notebook assumes basic knowledge of Bayesian inference and MCMC. The examples are related to Bayesian data analysis course.
Note that you can easily analyse Stan fit objects returned by stan_glm()
with a ShinyStan package by calling launch_shinystan(fit)
.
The models are not exactly equal to the models at rstan_demo.Rmd, but rather serve as examples of how to implement similar models with rstanarm.
Toy data with sequence of failures (0) and successes (1). We would like to learn about the unknown probability of success.
data_bern <- data.frame(y = c(1, 1, 1, 0, 1, 1, 1, 0, 1, 0))
Uniform prior (beta(1,1)) is achieved by setting the prior to NULL, which is not recommended in general. y ~ 1 means y depends only on the intercept term
fit_bern <- stan_glm(y ~ 1, family = binomial(), data = data_bern,
prior_intercet = NULL, seed = SEED, refresh = 0)
You can use ShinyStan examine and diagnose the fitted model is to call shinystan in R terminal as launch_shinystan(fit_bern)
Monitor provides summary statistics and diagnostics
monitor(fit_bern$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat Bulk_ESS Tail_ESS
(Intercept) -0.2 0.8 2.1 0.9 0.7 1.01 1449 1151
mean_PPD 0.3 0.7 1.0 0.7 0.2 1.00 2243 4000
log-posterior -10.0 -8.3 -8.0 -8.5 0.8 1.01 1373 1268
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
To see the parameter values on the ouput space, do the inverse logistic transformation (plogis in R) on the intercept
draws <- as.data.frame(fit_bern)
mean(draws$`(Intercept)`)
[1] 0.8606056
Probability of success
draws$theta <- plogis(draws$`(Intercept)`)
mean(draws$theta)
[1] 0.683932
Histogram of theta
mcmc_hist(draws, pars='theta') + xlab('theta')
We next compare the result to using the default prior which is normal(0, 2.5) on logit probability. Visualize the prior by drawing samples from it
prior_mean <- 0
prior_sd <- 2.5
prior_intercept <- normal(location = prior_mean, scale = prior_sd)
prior_samples <- data.frame(
theta = plogis(rnorm(20000, prior_mean, prior_sd)))
mcmc_hist(prior_samples)
fit_bern <- stan_glm(y ~ 1, family = binomial(), data = data_bern,
seed = SEED, refresh = 0)
monitor(fit_bern$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat Bulk_ESS Tail_ESS
(Intercept) -0.2 0.8 2.1 0.9 0.7 1.01 1449 1151
mean_PPD 0.3 0.7 1.0 0.7 0.2 1.00 2243 4000
log-posterior -10.0 -8.3 -8.0 -8.5 0.8 1.01 1373 1268
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
To see the parameter values on the ouput space, do the inverse logistic transformation (plogis in R) on the intercept
draws <- as.data.frame(fit_bern)
mean(draws$`(Intercept)`)
[1] 0.8606056
Probability of success
draws$theta <- plogis(draws$`(Intercept)`)
mean(draws$theta)
[1] 0.683932
Histogram of theta
mcmc_hist(draws, pars='theta') + xlab('theta')
As the number of observations is small, there is small change in the posterior mean when the prior is changed. You can experiment with different priors and varying the number of observations.
Instead of sequence of 0’s and 1’s, we can summarize the data with the number of experiments and the number successes. Binomial model with a approximately uniform prior for the probability of success. The prior is specified in the ‘latent space’. The actual probability of success, theta = plogis(alpha), where plogis is the inverse of the logistic function.
Visualize the prior by drawing samples from it
prior_mean <- 0
prior_sd <- 1.5
prior_intercept <- normal(location = prior_mean, scale = prior_sd)
prior_samples <- data.frame(
theta = plogis(rnorm(20000, prior_mean, prior_sd)))
mcmc_hist(prior_samples)
Binomial model (we are not able to replicate the Binomial example in rstan_demo exactly, as stan_glm
does not accept just one observation, so the Bernoulli is needed for the same model, and Binomial will be demonstrated first with other data).
data_bin <- data.frame(N = c(5,5), y = c(4,3))
fit_bin <- stan_glm(y/N ~ 1, family = binomial(), data = data_bin,
prior_intercept = prior_intercept, weights = N,
seed = SEED, refresh = 0)
monitor(fit_bin$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat Bulk_ESS Tail_ESS
(Intercept) -0.2 0.7 1.8 0.8 0.6 1 1245 1219
mean_PPD 1.5 3.5 5.0 3.4 1.0 1 1996 4000
log-posterior -5.5 -3.9 -3.7 -4.1 0.7 1 1355 1070
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
draws <- as.data.frame(fit_bin)
mean(draws$`(Intercept)`)
[1] 0.7585508
Probability of success
draws$theta <- plogis(draws$`(Intercept)`)
mean(draws$theta)
[1] 0.667661
Histogram of theta
mcmc_hist(draws, pars='theta') + xlab('theta')
Re-run the model with a new data dataset.
data_bin <- data.frame(N = c(5,5), y = c(4,5))
fit_bin <- update(fit_bin, data = data_bin)
monitor(fit_bin$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat Bulk_ESS Tail_ESS
(Intercept) 0.6 1.7 3.0 1.7 0.7 1 1321 1346
mean_PPD 3.0 4.5 5.0 4.2 0.7 1 2373 4000
log-posterior -5.5 -3.9 -3.7 -4.2 0.7 1 1517 1474
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
Probability of success
draws <- as.data.frame(fit_bern)
draws$theta <- plogis(draws$`(Intercept)`)
mean(draws$theta)
[1] 0.683932
Histogram of theta
mcmc_hist(draws, pars='theta') + xlab('theta')
An experiment was performed to estimate the effect of beta-blockers on mortality of cardiac patients. A group of patients were randomly assigned to treatment and control groups:
Data, where grp2 is a dummy variable that captures the differece of the intercepts in the first and the second group.
data_bin2 <- data.frame(N = c(674, 680), y = c(39,22), grp2 = c(0,1))
To analyse whether the treatment is useful, we can use Binomial model for both groups and compute odds-ratio.
fit_bin2 <- stan_glm(y/N ~ grp2, family = binomial(), data = data_bin2,
weights = N, seed = SEED, refresh = 0)
monitor(fit_bin2$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat Bulk_ESS Tail_ESS
(Intercept) -3.1 -2.8 -2.5 -2.8 0.2 1 2843 2658
grp2 -1.1 -0.6 -0.2 -0.6 0.3 1 2008 1785
mean_PPD 22.0 30.5 39.5 30.6 5.3 1 3180 3287
log-posterior -11.7 -9.4 -8.8 -9.7 1.0 1 1784 1709
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
Plot odds ratio
draws_bin2 <- as.data.frame(fit_bin2) %>%
mutate(theta1 = plogis(`(Intercept)`),
theta2 = plogis(`(Intercept)` + grp2),
oddsratio = (theta2/(1-theta2))/(theta1/(1-theta1)))
mcmc_hist(draws_bin2, pars='oddsratio')
The following file has Kilpisjärvi summer month temperatures 1952-2013:
data_kilpis <- read.delim('kilpisjarvi-summer-temp.csv', sep = ';')
data_lin <-data.frame(year = data_kilpis$year,
temp = data_kilpis[,5])
Plot the data
ggplot() +
geom_point(aes(year, temp), data = data.frame(data_lin), size = 1) +
labs(y = 'Summer temp. @Kilpisjärvi', x= "Year") +
guides(linetype = "none")
To analyse has there been change in the average summer month temperature we use a linear model with Gaussian model for the unexplained variation. rstanarm uses by default scaled priors.
y ~ x means y depends on the intercept and x
fit_lin <- stan_glm(temp ~ year, data = data_lin, family = gaussian(),
seed = SEED, refresh = 0)
The default priors for the linear model are
prior_summary(fit_lin)
Priors for model 'fit_lin'
------
Intercept (after predictors centered)
Specified prior:
~ normal(location = 9.3, scale = 2.5)
Adjusted prior:
~ normal(location = 9.3, scale = 2.9)
Coefficients
Specified prior:
~ normal(location = 0, scale = 2.5)
Adjusted prior:
~ normal(location = 0, scale = 0.16)
Auxiliary (sigma)
Specified prior:
~ exponential(rate = 1)
Adjusted prior:
~ exponential(rate = 0.86)
------
See help('prior_summary.stanreg') for more details
You can use ShinyStan (launch_shinystan(fit_lin)
) to look at the divergences, treedepth exceedences, n_eff, Rhats, and joint posterior of alpha and beta. In the corresponding rstan_demo notebook we observed some treedepth exceedences leading to slightly less efficient sampling, but rstanarm has slightly different model and performs better.
Instead of interactive ShinyStan, we can also check the diagnostics as follows
monitor(fit_lin$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat Bulk_ESS Tail_ESS
(Intercept) -57.1 -31.1 -5.3 -31.1 15.8 1 3893 2708
year 0.0 0.0 0.0 0.0 0.0 1 3891 2708
sigma 1.0 1.1 1.3 1.1 0.1 1 3210 2640
mean_PPD 9.0 9.3 9.6 9.3 0.2 1 4074 3778
log-posterior -101.2 -98.5 -97.4 -98.8 1.2 1 1950 2505
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
check_hmc_diagnostics(fit_lin$stanfit)
Divergences:
Tree depth:
Energy:
Plot data and the fit
draws_lin <- as.data.frame(fit_lin)
mean(draws_lin$year>0) # probability that beta > 0
[1] 0.99375
mu_draws <- tcrossprod(cbind(1, data_lin$year),
cbind(draws_lin$`(Intercept)`,draws_lin$year))
mu <- apply(mu_draws, 1, quantile, c(0.05, 0.5, 0.95)) %>%
t() %>% data.frame(x = data_lin$year, .) %>% gather(pct, y, -x)
pfit <- ggplot() +
geom_point(aes(year, temp), data = data.frame(data_lin), size = 1) +
geom_line(aes(x, y, linetype = pct), data = mu, color = 'red') +
scale_linetype_manual(values = c(2,1,2)) +
labs(x = '', y = 'Summer temp. @Kilpisjärvi') +
guides(linetype = "none")
phist <- mcmc_hist(draws_lin) + ggtitle('parameters')
grid.arrange(pfit, phist)
Prediction for year 2016
predict(fit_lin, newdata = data.frame(year = 2016), se.fit = TRUE)
$fit
1
9.993771
$se.fit
1
0.2971878
# or sample from the posterior predictive distribution and
# plot the histogram
ypred <- posterior_predict(fit_lin, newdata = data.frame(year = 2016))
mcmc_hist(ypred) + xlab('avg-temperature prediction for the summer 2016')
The temperatures used in the above analyses are averages over three months, which makes it more likely that they are normally distributed, but there can be extreme events in the feather and we can check whether more robust Student’s t observation model woul give different results.
Currently, rstanarm does not yet support Student’s t likelihood. Below we use brms package, which supports similar model formulas as rstanarm with more options, but doesn’t have pre-compiled models (be aware also that the default priors are not necessary the same).
library(brms)
fit_lin_t <- brm(temp ~ year, data = data_lin, family = student(), seed = SEED,
refresh = 1000)
summary(fit_lin_t)
brms package generates Stan code which we can extract as follows. By saving this code to a file you can extend the model, beyond the models supported by brms.
stancode(fit_lin_t)
// generated with brms 2.16.1
functions {
/* compute the logm1 link
* Args:
* p: a positive scalar
* Returns:
* a scalar in (-Inf, Inf)
*/
real logm1(real y) {
return log(y - 1);
}
/* compute the inverse of the logm1 link
* Args:
* y: a scalar in (-Inf, Inf)
* Returns:
* a positive scalar
*/
real expp1(real y) {
return exp(y) + 1;
}
}
data {
int<lower=1> N; // total number of observations
vector[N] Y; // response variable
int<lower=1> K; // number of population-level effects
matrix[N, K] X; // population-level design matrix
int prior_only; // should the likelihood be ignored?
}
transformed data {
int Kc = K - 1;
matrix[N, Kc] Xc; // centered version of X without an intercept
vector[Kc] means_X; // column means of X before centering
for (i in 2:K) {
means_X[i - 1] = mean(X[, i]);
Xc[, i - 1] = X[, i] - means_X[i - 1];
}
}
parameters {
vector[Kc] b; // population-level effects
real Intercept; // temporary intercept for centered predictors
real<lower=0> sigma; // dispersion parameter
real<lower=1> nu; // degrees of freedom or shape
}
transformed parameters {
}
model {
// likelihood including constants
if (!prior_only) {
// initialize linear predictor term
vector[N] mu = Intercept + Xc * b;
target += student_t_lpdf(Y | nu, mu, sigma);
}
// priors including constants
target += student_t_lpdf(Intercept | 3, 9.4, 2.5);
target += student_t_lpdf(sigma | 3, 0, 2.5)
- 1 * student_t_lccdf(0 | 3, 0, 2.5);
target += gamma_lpdf(nu | 2, 0.1)
- 1 * gamma_lccdf(1 | 2, 0.1);
}
generated quantities {
// actual population-level intercept
real b_Intercept = Intercept - dot_product(means_X, b);
}
We can use leave-one-out cross-validation to compare the expected predictive performance.
Let’s use LOO to compare whether Student’s t model has better predictive performance.
loo1 <- loo(fit_lin)
loo2 <- loo(fit_lin_t)
loo_compare(loo1, loo2)
elpd_diff se_diff
fit_lin 0.0 0.0
fit_lin_t -0.4 0.3
There is no practical difference between Gaussian and Student’s t models.
Let’s compare the temperatures in three summer months.
data_kilpis <- read.delim('kilpisjarvi-summer-temp.csv', sep = ';')
data_grp <- data.frame(month = rep(6:8, nrow(data_kilpis)),
temp = c(t(data_kilpis[,2:4])))
Weakly informative prior for the common mean
prior_intercept <- normal(10, 10)
To use no (= uniform) prior, prior_intercept could be set to NULL
y ~ 1 + (1 | x) means y depends on common intercept and group speficific intercepts (grouping determined by x)
fit_grp <- stan_lmer(temp ~ 1 + (1 | month), data = data_grp,
prior_intercept = prior_intercept, refresh = 0)
Warning: There were 2 divergent transitions after warmup. See
https://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
to find out why this is a problem and how to eliminate them.
Warning: Examine the pairs() plot to diagnose sampling problems
# launch_shinystan(fit_grp)
monitor(fit_grp$stanfit)
Inference for the input samples (4 chains: each with iter = 2000; warmup = 0):
Q5 Q50 Q95 Mean SD Rhat
(Intercept) 7.2 9.3 11.2 9.3 1.3 1.00
b[(Intercept) month:6] -3.7 -1.7 0.3 -1.7 1.3 1.00
b[(Intercept) month:7] -0.3 1.6 3.8 1.7 1.3 1.00
b[(Intercept) month:8] -1.8 0.1 2.2 0.2 1.3 1.00
b[(Intercept) month:_NEW_month] -3.5 0.0 3.5 0.0 2.3 1.00
sigma 1.4 1.5 1.7 1.5 0.1 1.00
Sigma[month:(Intercept),(Intercept)] 0.9 3.1 17.1 5.4 6.8 1.01
mean_PPD 9.1 9.3 9.6 9.3 0.2 1.00
log-posterior -357.3 -353.2 -350.9 -353.5 2.0 1.01
Bulk_ESS Tail_ESS
(Intercept) 924 943
b[(Intercept) month:6] 956 1014
b[(Intercept) month:7] 909 967
b[(Intercept) month:8] 941 989
b[(Intercept) month:_NEW_month] 2582 1766
sigma 2480 1607
Sigma[month:(Intercept),(Intercept)] 1065 1401
mean_PPD 3981 3739
log-posterior 1295 1949
For each parameter, Bulk_ESS and Tail_ESS are crude measures of
effective sample size for bulk and tail quantities respectively (an ESS > 100
per chain is considered good), and Rhat is the potential scale reduction
factor on rank normalized split chains (at convergence, Rhat <= 1.05).
Average temperature over all months. monthly deviations from the mean, residual sigma and hierarchical prior sigma
mcmc_hist(as.data.frame(fit_grp))
A density estimates of the posterior for each month
temps <- (as.matrix(fit_grp)[,1] + as.matrix(fit_grp)[, 2:4]) %>%
as.data.frame() %>% setNames(c('June','July','August')) %>% gather(month, temp)
ggplot(temps, aes(y=month, x=temp)) +
stat_slab() + labs(y='Month', x='Temperature')
Probabilities that June is hotter than July, June is hotter than August and July is hotter than August:
combn(unique(temps$month), 2, function(months, data) {
mean(subset(data, month == months[1])$temp > subset(data, month == months[2])$temp)
}, data = temps) %>% setNames(c('TJune>TJuly', 'TJune>TAugust', 'TJuly>TAugust'))
TJune>TJuly TJune>TAugust TJuly>TAugust
0 0 1