```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## Regression Example ```{r} set.seed(123123) N <- 500 P1 <- 5 P2 <- 100 P <- P1+P2 sgma <- 2 beta_sigma <- 0.5 X <- matrix(rnorm(N*(P1+P2)), nrow = N) beta <- c(rnorm(P1, sd = 2), rep(0, P2)) Y <- rnorm(rep(1,N), mean = X%*%beta, sgma) ``` By computing the gradient, we can set up an HMC sampler: ```{r} # Potential Energy Function, positively correlated multivariate normal: f <- function(q, X, Y, scale = 1){ beta <- q[1:P] n <- length(Y) sigmaSq <- q[length(q)] e <- Y - X %*% beta out <- scale*(-(n/2)*log(sigmaSq) - (1/(2*sigmaSq))*(t(e) %*% e) - sum((beta^2))/(beta_sigma) -sigmaSq) ifelse(is.finite(out), out, -Inf) } f.grad <- function(q, X, Y, scale = 1){ beta <- q[1:P] sigmaSq <- q[length(q)] n <- length(Y) betapart <- (1/sigmaSq)*(t(Y) %*% X - t(beta) %*% t(X) %*% X) - t(beta)/(beta_sigma) e <- Y - X %*% beta sigmapart <- -n/(2*sigmaSq) + (0.5/(sigmaSq^2))*(t(e) %*% e) - 1 c(betapart, sigmapart)*scale } ## Auxilliary distributions for MH g <- function(from, to, sd_prop){ sum(dnorm(to, from, rep(sd_prop, length(to)), log = TRUE)) } g.s <- function(from, sd_prop){ rnorm(rep(1, length(from)), mean = from, sd = rep(sd_prop, length(from))) } #f.grad(c(beta, sgma), X, Y) ## Define HMC update function HMC_update = function (f, f.grad, epsilon, L, current_q, Y,X) { q = current_q # Randomly generate a momentum vector p = rnorm(length(q),0,1) current_p = p # Make a half step for momentum at the beginning p = p - epsilon * f.grad(q = q, X = X, Y = Y, scale = -1) / 2 # Alternate full steps for position and momentum for (i in 1:L) { # Make a full step for the position q = q + epsilon * p # Make a full step for the momentum, except at end of trajectory if (i!=L){ p = p - epsilon * f.grad(q = q, X = X, Y = Y, scale = -1) } } # Make a half step for momentum at the end. p=p- epsilon * f.grad(q = q, X = X, Y = Y, scale = -1) / 2 # Negate momentum at end of trajectory to make the proposal symmetric p = -p # Evaluate potential and kinetic energies at start and end of trajectory current_f = f(current_q,Y=Y,X=X, scale = -1) current_K = sum(current_p^2) / 2 proposed_f = f(q,Y=Y,X=X, scale = -1) proposed_K = sum(p^2) / 2 # Accept or reject the state at end of trajectory, returning either # the position at the end of the trajectory or the initial position criterion <- current_f-proposed_f+current_K-proposed_K if (is.finite(criterion) && log(runif(1)) < criterion) { return (q) # accept } else { return (current_q) # reject } } ## Define MH Update function MH_update <- function(param, f, g, g.sample, sd_prop, log = TRUE,...) { x0 <- param x1 <- g.sample(x0,sd_prop=sd_prop) if (log) { a <- (f(x1, ...) - f(x0, ...)) + g(x1, x0,sd_prop=sd_prop) - g(x0, x1,sd_prop=sd_prop) u <- log(runif(1, 0, 1)) } else { a <- (f(x1, ...)/f(x0, ...)) * (g(x1, x0,sd_prop=sd_prop)/g(x0, x1,sd_prop=sd_prop)) u <- runif(1, 0, 1) } if (u < a) { return(x1) } return(x0) } ## Define function to run MH chain MH_Chain <- function(n,x0, f, g, g.s,sd_prop, log, ...){ out <- matrix(NA, ncol = length(x0), nrow = n) out[1,] <- x0 for (i in 2:n){ out[i,] <- MH_update(f = f, param = out[i-1,], g=g, g.sample = g.s, sd_prop=sd_prop,log = log,...) } out } ## Define function to run HMC chain HMC_Chain <- function(n,x0, f, fgrad, eps, L, log, ...){ out <- matrix(NA, ncol = length(x0), nrow = n) out[1,] <- x0 for (i in 2:n){ if (i %% 100 == 0){ print(i) } out[i,] <- HMC_update(f,f.grad = fgrad, epsilon=eps, L = L, current_q = out[i-1,] ,...) } out } ## MH Version set.seed(123123) MH_Time <- system.time({ MH_Output <- MH_Chain(10000, c(rnorm(P), rgamma(1,1)), f, g, g.s, sd_prop=0.1, log=TRUE, Y = Y,X=X) MH_Output.samples <- MH_Chain(n=10000, x0 = MH_Output[nrow(MH_Output),], f, g, g.s, sd_prop=0.04, log=TRUE, Y = Y,X=X) }) plot(MH_Output.samples[,1], type = "l") #system.time({HMC_Output <- HMC_Chain(1000, c(beta, sgma), f, fgrad = f.grad, eps = 1e-2, L = 10, log = TRUE, Y=Y,X=X)}) # Warmup set.seed(123123) HMC_Time <- system.time({ HMC_Output <- HMC_Chain(2000, c(rnorm(P), rgamma(1,1)), f, fgrad = f.grad, eps = 1e-3, L = 5, log = TRUE, Y=Y,X=X) HMC_Output.samples <- HMC_Chain(1000, HMC_Output[nrow(HMC_Output), ], f, fgrad = f.grad, eps = 1e-2, L = 10, log = TRUE, Y=Y,X=X) }) plot(HMC_Output.samples[,1], type = "l") plot(apply(MH_Output.samples, 2, mean), apply(HMC_Output.samples,2, mean)) ## Samples per second? nrow(MH_Output.samples)/MH_Time[3] nrow(HMC_Output.samples)/HMC_Time[3] ## Effective Samples Per Second? library(coda) MH_ESS_SEC <- apply(MH_Output.samples, 2, effectiveSize)/MH_Time[3] hist(MH_ESS_SEC) HMC_ESS_SEC <- apply(HMC_Output.samples, 2, effectiveSize)/HMC_Time[3] hist(HMC_ESS_SEC) ``` ## High Dimensional Example: In higher dimensons, things are more difficult - it may be worth breaking this up into a Gibbs sampler, with different blocks of betas each getting their own HMC update step. ```{r} set.seed(123123) N <- 500 P1 <- 5 P2 <- 1000 P <- P1+P2 sgma <- 2 beta_sigma <- 0.5 X <- matrix(rnorm(N*(P1+P2)), nrow = N) beta <- c(rnorm(P1, sd = 2), rep(0, P2)) Y <- rnorm(rep(1,N), mean = X%*%beta, sgma) #system.time({HMC_Output <- HMC_Chain(1000, c(beta, sgma), f, fgrad = f.grad, eps = 1e-2, L = 10, log = TRUE, Y=Y,X=X)}) # Warmup set.seed(123123) HMC_Time <- system.time({ HMC_Output <- HMC_Chain(500, c(rnorm(P), rgamma(1,1)), f, fgrad = f.grad, eps = 0.0005, L = 10, log = TRUE, Y=Y,X=X) HMC_Output2 <- HMC_Chain(500, HMC_Output[nrow(HMC_Output), ], f, fgrad = f.grad, eps = 0.001, L = 10, log = TRUE, Y=Y,X=X) HMC_Output3 <- HMC_Chain(1000, HMC_Output2[nrow(HMC_Output2), ], f, fgrad = f.grad, eps = 0.005, L = 10, log = TRUE, Y=Y,X=X) HMC_Output4 <- HMC_Chain(1000, HMC_Output3[nrow(HMC_Output3), ], f, fgrad = f.grad, eps = 0.01, L = 10, log = TRUE, Y=Y,X=X) }) plot(HMC_Output4[,4]) ## Stan Approach stanmodel <- " data{ int N; int P; vector[N] Y; matrix[N,P] X; } parameters{ vector[P] beta; real ssq; } model { Y ~ normal(X*beta, ssq); beta ~ normal(0,0.5); ssq ~ gamma(1,1); } " library(rstan) standata <- list(N = nrow(X), P = ncol(X), Y = Y, X=X) smod <- stan_model(model_code = stanmodel, auto_write = TRUE) result <- sampling(smod, data = standata, chains = 1, pars = c("beta", "ssq"), warmup = 500, iter = 1000) samples <- extract(result, permute = FALSE) plot(samples[,,1], type = "l") ```