12  Bayesian analysis of cohort and case-control studies

Probability logic also provides a basis for recognizing prior distributions as an integral component of statistical analysis, rather than the current misleading practice of pretending that statistics applied to observational data are objective. This basis is important, because the use of realistic priors in a statistical analysis can yield more stringent tests of hypotheses and more accurate estimates than conventional procedures. (Greenland 1998)

When we considered the Bayesian estimation of risks and rates in Chapter 4, we used the beta conjugate distribution for binomial models for risks and the gamma conjugate distribution for exponential or Poisson models for rates. When we are comparing two samples in a cohort or case-control study, there are no simple conjugate distributions for parameters. Instead, there are algorithms for sampling from the posterior distribution, and inferences are based on these samples.

12.1 Prior distributions

A noninformative prior is meant to “let the data speak for itself”, but this generally comes at the price of ignoring existing knowledge about the exposure, the outcome, and the population. With a large sample, Bayesian analysis with noninformative priors produces results similar to maximum likelihood. However, Bayesian methods do not rely on the central limit theorem, so they adapt more easily to small sample sizes.

Although prior distributions are often viewed with suspicion, they are an important advantage of the Bayesian approach to statistical inference. The flat priors implicit in frequentist methods do not imply objectivity. Using a prior distribution that incorporates background knowledge will produce more precise and accurate parameter estimates and predictions than an analysis using noninformative priors.

12.2 Posterior distributions

Without conjugate distributions, deriving the joint posterior distribution for model parameters can be much more difficult. The most common approach is to take samples from the posterior distribution and use these samples to get point and interval estimates of parameters or functions of parameters. Sampling from the posterior is complicated by the fact that we only know the posterior up to a constant of proportionality. If \(\pi(\theta)\) is the prior distribution and \(L(\theta)\) is the likelihood for our data, then \[ \pi(\theta \given{} \data) = \frac{L(\theta) \pi(\theta)}{\pi(\data)} \propto L(\theta) \pi(\theta) \tag{12.1}\] where \(\pi(data)\) is the marginal probability of the data, which is generally difficult or impossible to calculate.

12.2.1 Markov chain Monte Carlo

In Markov chain Monte Carlo (MCMC), we generate a random walk across the set of possible \(\theta\) so that the distribution of points we visit converges to the posterior distribution (Gelman et al. 2014). We choose a starting point \(\theta_0\). At each \(\theta_k\), we propose a \(\theta^*\) from a proposal distribution or jumping distribution \(J(\theta^* \given{} \theta_k)\). In the Metropolis algorithm (Metropolis et al. 1953), the proposal distribution is symmetric in the sense that \[ J(\theta^* \given{} \theta_k) = J(\theta_k \given{} \theta^*) \] for any \(\theta^*\) and \(\theta_k\). We then choose whether to stay at the same place (i.e., \(\theta_{k + 1} = \theta_k\)) or to jump to \(\theta^*\) (i.e., \(\theta_{k + 1} = \theta_*\)). The distribution of points we visit will converge the posterior distribution of \(\theta\) if \[ \pi(\theta_k \given{} \data) \Pr(\text{jump from } \theta_k \text{ to } \theta^*) = \pi(\theta^* \given{} \data) \Pr(\text{jump from } \theta^* \text{ to } \theta^k) \] so that jumps from \(\theta_k\) to \(\theta^*\) happen as often as the reverse jumps from \(\theta^*\) to \(\theta_k\). This is called the detailed balance condition, and the jump probabilities can be replaced with probability densities when the space of possible \(\theta\) is continuous.

Rearranging the detailed balance condition, we get \[ \Pr(\text{jump from } \theta_k \text{ to } \theta^*) = \frac{\pi(\theta^* \given{} \data)}{\pi(\theta_k \given{} \data)} \Pr(\text{jump from } \theta^* \text{ to } \theta_k). \] If we always jump from \(\theta^*\) to \(\theta_k\) when \(\pi(\theta^* \given{} \data) < \pi(\theta_k \given{} \data)\), then the probability of jumping from \(\theta_k\) to \(\theta^*\) must be \[ r = \frac{\pi(\theta^* \given{} \data)}{\pi(\theta_k \given{} \data)} = \frac{L(\theta^*) \pi(\theta^*)}{L(\theta_k) \pi(\theta_k)}, \] where the unknown \(\pi(\data)\) from Equation 12.1 has canceled out. Therefore, we will meet the detailed balance condition if \[ \theta_{k + 1} = \begin{cases} \theta^* &\text{ with probability} \min(r, 1), \\ \theta_k &\text{otherwise}. \end{cases} \] This is not the only rule that will lead to the detailed balance condition, but it is the one used by the Metropolis algorithm.

The Metropolis-Hastings algorithm (Hastings 1970) allows the proposal distribution to be asymmetric. In that case, the procedure is the same except that \[ r = \frac{\pi(\theta^* \given{} \data) / J(\theta^* \given{} \theta_k)} {\pi(\theta_k \given{} \data) / J(\theta_k \given{} \theta^*)}. \] This allows much greater flexibility in proposal distributions. A good proposal distribution should be easy to sample from, make it easy to calculate \(r\), propose jumps that are not too big and not too small (Gelman et al. 2014). If the proposed jumps are too small, the space of possible \(\theta\) will not be explored effectively by the MCMC random walk even if we accept most jumps. If the proposed jumps are too large, the proposed \(\theta^*\) will be rejected too often and the MCMC random walk will get stuck.

The initial samples in an MCMC have a distribution that has not yet converged to the posterior distribution of \(\theta\). This period is called burn-in or warm-up, and early samples are generally discarded. Even after burn-in, the samples produced by an MCMC can be highly correlated, so the effective sample size is much less than the actual number of samples. This correlation can be reduced by thinning the chain by keeping, for example, every 10th sample. To monitor convergence, it is common to start several chains in different places and calculate the variation within chains and between chains for each component of \(\theta\). When convergence is reached, the variation within chains is similar to the variation between chains.

12.2.2 Hamiltonian Monte Carlo

Hamiltonian Monte Carlo (HMC) adapts methods from physics to tune the proposed jumps in an MCMC (Duane et al. 1987; Neal 1996), allowing the random walk to explore the posterior distribution more efficiently. HMC treats \(\theta\) as a position and adds a momentum variable \(\phi\) that has the same dimension (i.e., number of components) as \(\theta\). Starting from \((\theta_k, \phi_k)\), both \(\theta\) and \(\phi\) are updated multiple times in leapfrog steps to generate a proposal \((\theta^*, \phi^*)\). At the end of the leapfrog steps, a Metropolis-Hastings step decides whether to stay at \((\theta_k, \phi_k)\) or jump to \((\theta^*, \phi^*)\). Usually, these steps are rejected with much lower probability than the proposed jumps in an MCMC.

The momentum is used to nudge \(\theta\) toward values of \(\theta\) with higher posterior density. If \(\theta\) takes a path with decreasing posterior density, its momentum \(\phi\) starts to decrease and eventually point in the opposite direction, pulling \(\theta\) back toward a region with higher posterior density. If \(\theta\) takes a path with increasing posterior density, its momentum \(\phi\) will increase in that direction until it crosses a peak and the posterior density starts to decrease again (Gelman et al. 2014). The size of the jumps acts like kinetic energy, and \(-\ln \pi(\theta \given{} \data)\) acts like the potential energy. The random walk is attracted to regions of low potential energy (i.e., high posterior density) like a marble rolling around a bowl, but the conservation of energy ensures that the marble does not get stuck at the bottom.

12.2.3 Laplace approximation

12.2.4 Inference with samples from the posterior

12.3 Cohort studies

12.3.1 Risk ratios

Main messages:

  • Specifying an informative prior based on background knowledge can improve precision.

  • Samples from the posterior can be used for inference about parameters and functions of parameters.

riskratio-Bayes.R
## Bayesian estimation of risk ratios

# load packages
# The rats data is from:
# Mantel, Bohidar, and Ciminera (1977). Cancer Research 37: 3863-3868.
library(rstanarm)               # Bayesian regression models
library(survival)               # rats data

# GLMs in rstanarm are "stanreg" objects
? stan_glm
? coef.stanreg

# binomial GLM with log link (log-binomial model) for the RR
RRglm <- glm(status ~ rx, family = binomial(link = "log"), data = rats)
exp(coef(RRglm))                # estimated risk (x = 0) and RR
exp(confint(RRglm))             # likelihood ratio CIs

# Bayesian GLM with log link fit using a flat prior for coefficients
# Use "prior = NULL" to specify a flat prior.
# Samples four chains with 2000 iteractions each by default.
# In each chain, the first 1000 samples are warmup and the last 1000 are kept.
RRbayes_non <- stan_glm(status ~ rx, data = rats,
                        family = binomial(link = "log"), prior = NULL)
prior_summary(RRbayes_non)      # summary of prior distributions
summary(RRbayes_non)            # summary of model fit (look for Rhat = 1)
coef(RRbayes_non)               # posterior medians (linear predictor scale)
posterior_interval(RRbayes_non) # 90% credible intervals (default)
posterior_interval(RRbayes_non, prob = 0.95)      # 95% credible intervals
exp(coef(RRbayes_non))          # posterior medians for risk (rx = 0) and RR
exp(posterior_interval(RRbayes_non, prob = 0.95)) # 95% credible intervals

# data frame of samples from the posterior distribution
# This allows you to calculate posterior means and functions of coefficients.
# Use double quotes for variable names with non-letters, like (Intercept).
post_non <- as.data.frame(RRbayes_non)
median(post_non$"(Intercept)")  # equals intercept from coef()
median(post_non$rx)             # equals rx coefficient from coef()
mean(post_non$rx)               # posterior mean log RR
quantile(post_non$rx, 0.025)    # lower 95% credible interval for log RR
quantile(post_non$rx, 0.975)    # upper 95% credible interval for log RR
quantile(post_non$rx, c(0.025, 0.975))

# point estimates and credible intervals for risk in the treated
post_non$lnrisk1 <- post_non$"(Intercept)" + post_non$rx
post_non$risk1 <- exp(post_non$lnrisk1)
median(post_non$lnrisk1)        # posterior median log risk in treated rats
median(post_non$risk1)          # posterior median risk in treated rats
quantile(post_non$risk1, c(0.025, 0.975)) # 95% credible interval for risk

# histogram of samples from posterior distribution of log(risk0)
# Use freq = FALSE to get probability densities instead of counts
post_non$lnrisk0 <- post_non$"(Intercept)"      # rename for convenience
summary(post_non$lnrisk0)
post_non$risk0 <- exp(post_non$lnrisk0)
hist(post_non$lnrisk0, freq = FALSE, xlab = "Log risk in untreated rats")
grid()
# add kernel density estimate
lines(density(post_non$lnrisk0), lty = "dashed")
# add approximate normal distribution of MLE
lnp0 <- seq(-4, -1.5, by = 0.01)
lines(lnp0, dnorm(lnp0, mean = coef(RRglm)[1], sd = sqrt(vcov(RRglm)[1, 1])))

# plot of empirical CDF and normal CDF for MLE of risk in untreated rats
# For transformations, comparing CDFs does not require the delta method.
plot(ecdf(post_non$risk0), main = NULL,
     xlab = "Risk in untreated rats",
     ylab = "Cumulative distribution function")
lines(exp(lnp0), pnorm(lnp0, mean = coef(RRglm)[1],
                       sd = sqrt(vcov(RRglm)[1, 1])),
      lty = "dashed")
grid()

# histogram of samples from posterior distribution of log(risk ratio)
summary(post_non$rx)
hist(post_non$rx, freq = FALSE, ylim = c(0, 1.4),
     xlab = "Log risk ratio (treated / untreated)")
grid()
lnrr <- seq(-0.3, 1.7, by = 0.01)
lines(density(post_non$rx), lty = "dashed")
lines(lnrr, dnorm(lnrr, coef(RRglm)[2], sqrt(vcov(RRglm)[2, 2])))

# plot of empirical CDF and normal CDF for MLE of risk ratio
# For transformations, comparing CDFs does not require the delta method.
post_non$rr <- exp(post_non$rx)
plot(ecdf(post_non$rr), main = NULL, lty = "dotted",
     xlab = "Risk ratio (treated / untreated)",
     ylab = "Cumulative distribution function")
lines(exp(lnrr), pnorm(lnrr, mean = coef(RRglm)[2],
                       sd = sqrt(vcov(RRglm)[2, 2])),
      lty = "dashed")
grid()

# using the default prior (weakly informative normal distributions)
# You can use the chains and iter arguments to change the sampling.
# The first half of each chain is warmup, and the last half is kept as samples.
RRbayes_def <- stan_glm(status ~ rx, data = rats, family = binomial(link = "log"),
                        iter = 1500, chains = 6)
prior_summary(RRbayes_def)
summary(RRbayes_def)
exp(coef(RRbayes_def))          # posterior medians for risk (rx = 0) and RR
exp(posterior_interval(RRbayes_def, prob = 0.95)) # 95% credible intervals
post_def <- as.data.frame(RRbayes_def)

# compare distributions of RR under noninformative and default priors
post_def$rr <- exp(post_def$rx)
plot(ecdf(post_def$rr), main = NULL,
     xlab = "Risk ratio (treated / untreated)",
     ylab = "Cumulative distribution function")
lines(ecdf(post_non$rr), col = "darkgray")
grid()
legend("bottomright", bg = "white", lty = "solid",
       col = c("black", "darkgray"),
       legend = c("Weakly informative prior", "Noninformative prior"))

# specifying an informative prior
# For the intercept, we use normal with mean -ln(0.1) and sd = ln(1.5).
# For the coefficient on rx, we use a Laplace (double exponential).
RRbayes <- stan_glm(status ~ rx, data = rats, family = binomial(link = "log"),
                    prior_intercept = normal(location = -log(0.2),
                                             scale = log(2)),
                    prior = normal(location = 0, scale = log(2)))
summary(RRbayes)
prior_summary(RRbayes)
exp(coef(RRbayes))              # posterior medians for risk (rx = 0) and RR
exp(posterior_interval(RRbayes, prob = 0.95)) # 95% credible intervals
post <- as.data.frame(RRbayes)
post$lnrisk1 <- post$"(Intercept)" + post$rx
post$risk1 <- exp(post$lnrisk1)
median(post$risk1)              # posterior median risk in treated rats
quantile(post$risk1, c(0.025, 0.975))   # 95% credible interval for risk
quantile(post$rx, c(0.025, 0.975))      # compare to GLM 95% CI for rx coef

12.3.2 Odds ratios

Main messages:

  • The regression model does not dictate the measure of association. Here, we get risks and risk ratios out of a logistic regression model, which is specified in terms of odds and odds ratios.

  • Using samples from the posterior distribution is easier and more accurate than using the delta method.

oddsratio-Bayes.R
## Bayesian estimation of odds ratios

# load packages
# The rats data is from:
# Mantel, Bohidar, and Ciminera (1977). Cancer Research 37: 3863-3868.
library(rstanarm)               # Bayesian regression models
library(survival)               # rats data

# GLMs in rstanarm are "stanreg" objects
? stan_glm
? coef.stanreg

# binomial GLM with log link (log-binomial model) for the RR
ORglm <- glm(status ~ rx, family = binomial(link = "log"), data = rats)
exp(coef(ORglm))                # estimated odds (x = 0) and OR
exp(confint(ORglm))             # likelihood ratio CIs

# Bayesian GLM with identity link fit using a flat prior for coefficients
# Use "prior = NULL" to specify a flat prior.
# Samples four chains with 2000 iteractions each by default.
# In each chain, the first 1000 samples are warmup and the last 1000 are kept.
ORbayes_non <- stan_glm(status ~ rx, data = rats,
                        family = binomial(link = "logit"), prior = NULL)
prior_summary(ORbayes_non)      # summary of prior distributions
summary(ORbayes_non)            # summary of model fit (look for Rhat = 1)
coef(ORbayes_non)               # posterior medians (linear predictor scale)
posterior_interval(ORbayes_non) # 90% credible intervals (default)
posterior_interval(ORbayes_non, prob = 0.95)      # 95% credible intervals
exp(coef(ORbayes_non))          # posterior medians for odds (rx = 0) and OR
exp(posterior_interval(ORbayes_non, prob = 0.95)) # 95% credible intervals

# data frame of samples from the posterior distribution
# This allows you to calculate posterior means and functions of coefficients.
post_non <- as.data.frame(ORbayes_non)

# point estimates and credible intervals for pdds in the treated
post_non$lnodds1 <- post_non$"(Intercept)" + post_non$rx
post_non$odds1 <- exp(post_non$lnodds1)
median(post_non$lnodds1)        # posterior median log odds in treated rats
median(post_non$odds1)          # posterior median odds in treated rats
quantile(post_non$odds1, c(0.025, 0.975)) # 95% credible interval for odds

# point estimates and credible intervals for risks and risk ratios
expit <- function(v) 1 / (1 + exp(-v))
post_non$risk0 <- expit(post_non$"(Intercept)")
post_non$risk1 <- expit(post_non$lnodds1)
post_non$oddsratio <- exp(post_non$rx)
post_non$riskratio <- post_non$risk1 / post_non$risk0
median(post_non$riskratio)
quantile(post_non$riskratio, c(0.025, 0.975))

12.3.3 Accelerated failure time models

12.3.4 Proportional hazards models

12.4 Case-control studies

12.4.1 Conditional logistic regression