This is a logistic regression problem with subject specific random intercepts:
Likelihood:
\(Y_{ij} \overset{ind}{\sim} binom(1, \pi_{ij}),\ i=1,...,N;\ j=1,...,N_i\)
Probability structure:
\(\mbox{logit}(\pi_{ij}) = {\bf X}_i\boldsymbol{\beta} + \gamma_i\)
Vague prior on coefficients:
\(\beta_k \overset{iid}{\sim} N(0, 10),\ k=1,...,K\)
Prior on random effects:
\(\gamma_i \overset{iid}{\sim} N(0, \sigma^2_\gamma),\ i=1,...,N\)
Our task is to factor out full-conditional distributions, and then implement a Gibbs sampler. Rather than look for known full-conditional distributions, here we’re going to perform our Gibbs updates with slice sampling:
# Slice sampling function from Brian Smith
slice <- function(x0, f, width, log=FALSE, ...) {
n <- length(x0)
y <- ifelse(log, f(x0, ...) - rgamma(1, 1, 1), runif(1, 0, f(x0, ...)))
l <- x0 - runif(n, 0, width)
r <- l + width
repeat {
x1 <- runif(n, l, r)
if(f(x1, ...) > y) return(x1)
else {
idx <- (x1 < x0)
l[idx] <- x1[idx]
r[!idx] <- x1[!idx]
}
}
}
You can read more about slice sampling on Wikipedia, but in general it’s based on some of the same ideas as the rejection and adaptive rejection samplers.
Let’s simulate some data according to this model:
## Generate Data:
# Number of subjects
N <- 100
# Number of observations per subject
Ni <- rpois(N, lambda = 20)
# Random effects
gamma <- rnorm(N, mean = 0, sd = 2)
# Number of columns of X
K <- 5
# True parameter values
beta <- rnorm(K, mean = 0, sd = 5)
# Design matrix (combined)
X <- cbind(1, matrix(rnorm((K-1)*sum(Ni), mean = 0, sd = 2), ncol = K-1))
eta <- X %*% beta + rep(gamma, Ni)
ilogit <- function(x){1/(1+exp(-x))}
Y <- rbinom(length(eta), size = 1, prob = ilogit(eta))
We now need to factor out our full conditionals from the joint posterior, and implement them as R functions:
fc_Beta <- function(beta, gamma, Y, X){
pi <- ilogit(X %*% beta + rep(gamma, Ni))
out <- sum(dbinom(Y, size = 1, prob = pi, log = TRUE)) +
sum(dnorm(beta, mean = 0, sd = 10, log = TRUE))
ifelse(is.finite(out), out, -Inf)
}
fc_gamma <- function(gamma, beta, sigma_gamma, Y, X){
pi <- ilogit(X %*% beta + rep(gamma, Ni))
out <- sum(dbinom(Y, size = 1, prob = pi, log = TRUE)) +
sum(dnorm(gamma, mean = 0, sd = sigma_gamma, log = TRUE))
ifelse(is.finite(out), out, -Inf)
}
fc_sigma_gamma <- function(sigma_gamma, gamma){
if (sigma_gamma <=0){
return(-Inf)
}
out <- sum(dnorm(gamma, mean = 0, sd = sigma_gamma, log = TRUE)) +
dgamma(sigma_gamma, 1, 1, log = TRUE)
ifelse(is.finite(out), out, -Inf)
}
Now we can set up our MCMC sampler. In this example, we’ll write our samples to a CSV file. This can be very useful:
# Starting Values:
# total MCMC samples
nsamples <- 5000
# How often to output?
stride <- 25
# Initial value for beta
b0 <- rnorm(K)
# Initial values for gamma
g0 <- rnorm(N)
# Initial value for sigma-gamma
sig.g <- rgamma(1,1,1)
# Outut file
outFile <- "samples.csv"
# Print information on iteration progress?
verbose = FALSE
# Tuning parameters for slice sampler:
beta_width <- 2
gamma_width <- 2
sigma_g_width <- 3
# Function to write samples
writeSample <- function(beta, gamma, sigmag){
cat(paste0(c(beta,gamma,sigmag), collapse = ","), "\n", file = outFile, append = TRUE)
}
# Initialize file
cat(paste0(c(paste0("beta", 1:K), paste0("gamma", 1:N), "sigma_gamma"), collapse = ","), "\n", file = outFile)
writeSample(b0,g0,sig.g)
## Main loop:
for (i in 1:nsamples){
if (i %% stride == 0){
# write output
writeSample(b0,g0,sig.g)
if (verbose){cat("Iteration ", i, "/",nsamples, "\n")}
}
b0 <- slice(b0, fc_Beta, width = rep(beta_width,length(b0)), log=TRUE, gamma = g0, Y=Y,X=X)
g0 <- slice(g0, fc_gamma, width = rep(gamma_width, length(g0)), log = TRUE, beta = b0, sigma_gamma=sig.g, Y=Y, X = X)
sig.g <- slice(sig.g, fc_sigma_gamma, width = sigma_g_width, log = TRUE, gamma = g0)
}
Generally, we’d run multiple chains to assess convergence, but here let’s just take a simple look at whether the chains are converging to our known true values:
samples <- read.csv("./samples.csv")
plot(samples$beta1, type = "l")
abline(h = beta[1], col = "blue")
plot(samples$beta2, type = "l")
abline(h = beta[2], col = "blue")
plot(samples$beta3, type = "l")
abline(h = beta[3], col = "blue")
plot(samples$beta4, type = "l")
abline(h = beta[4], col = "blue")
plot(samples$beta5, type = "l")
abline(h = beta[5], col = "blue")
pm <- apply(samples[1:nrow(samples) > nrow(samples)/2,], 2, mean)
plot(gamma, pm[startsWith(names(pm), "gamma")], xlab = "True RE", ylab = "Posterior Mean RE")