Grid Search Example

grid.search.1d <- function(f, xmin, xmax, gridpts = 10, tol = 1e-8){
  # Base case: check if we're converged
  if (xmax - xmin <= tol){
    x1 <- (xmax + xmin)/2
    return(list(x=x1, obj = f(x1)))
  }
  
  # Recursive case - build grid and search
  grid <- seq(xmin, xmax, length = gridpts)
  f.x <- vapply(X = grid, FUN = f, FUN.VALUE = 0.0)
  min.idx <- which.min(f.x)
  # Get indices bounding best point:
  idx <- c(min.idx - 1, min.idx, min.idx + 1)
  # Restrict to valid indices:
  idx <- idx[idx >= 1 & idx <= length(grid)]
  
  return(grid.search.1d(f, xmin = grid[min(idx)], xmax = grid[max(idx)], 
                        gridpts = gridpts, tol = tol))
}

system.time({grid.search.1d(obj.fun, xmin = -100, xmax = 100)})
##    user  system elapsed 
##    0.02    0.00    0.02

This function can be easily parallelized:

# Recall our more difficult example:
X <- rnorm(200000, mean = 25, sd = 20)
obj.fun2 <- function(u){
  -sum(dnorm(X, mean = u, sd = 4))
}



library(parallel)
grid.search.1d.par <- function(cl, f, xmin, xmax, gridpts = 10, tol = 1e-8){
  # Base case: check if we're converged
  if (xmax - xmin <= tol){
    x1 <- (xmax + xmin)/2
    return(list(x=x1, obj = f(x1)))
  }
  
  # Recursive case - build grid and search
  grid <- seq(xmin, xmax, length = gridpts)
  f.x <- as.numeric(parLapply(cl, X = grid, fun = f))
  min.idx <- which.min(f.x)
  # Get indices bounding best point:
  idx <- c(min.idx - 1, min.idx, min.idx + 1)
  # Restrict to valid indices:
  idx <- idx[idx >= 1 & idx <= length(grid)]
  
  return(grid.search.1d.par(cl, f, xmin = grid[min(idx)], xmax = grid[max(idx)], 
                        gridpts = gridpts, tol = tol))
}


cl <- makeCluster(8)
clusterExport(cl, varlist = "X")

system.time({r1 <- grid.search.1d.par(cl, f = obj.fun2, xmin = -100, xmax = 100, gridpts = length(cl))})
##    user  system elapsed 
##    0.12    0.01    0.84
system.time({r2 <- grid.search.1d(f = obj.fun2, xmin = -100, xmax = 100, gridpts = length(cl))})
##    user  system elapsed 
##    3.05    0.05    3.16
system.time({r2 <- f.min(f = obj.fun2, gradFunc = fd_deriv, x0 = rnorm(1,0,1))})
##    user  system elapsed 
##    0.89    0.02    0.91
stopCluster(cl)

Convexity Again

Consider the following function:

# Mixture distribution:
obj.func.nonconvex <- function(x){
  0.25*dnorm(x, mean = 1, sd = 1.8) + 0.75*dnorm(x, mean = 5, sd = 1)
}

xpoints <- seq(-2,8, length = 100)
plot(xpoints, obj.func.nonconvex(xpoints), type= "l")

grid.search.1d(f = function(x){-1.0*obj.func.nonconvex(x)}, xmin = -100, xmax = 100, gridpts = 10)
## $x
## [1] 4.98
## 
## $obj
## [1] -0.304
f.min(f = function(x){-1.0*obj.func.nonconvex(x)}, x0 = -1)
## $x
## [1] 1.02
## 
## $obj
## [1] -0.05551
## 
## $itrs
## [1] 381
## 
## $halving_steps
## [1] 0
## 
## $runtime
## Time difference of 0.009993 secs
f.min(f = function(x){-1.0*obj.func.nonconvex(x)}, x0 = 9)
## $x
## [1] 4.98
## 
## $obj
## [1] -0.304
## 
## $itrs
## [1] 755
## 
## $halving_steps
## [1] 0
## 
## $runtime
## Time difference of 0.01899 secs

Multiple Dimensions

Here’s a brief example of how we might perform coordinate descent:

library(mvtnorm)

obj.fun.2d <- function(x){
  -1.0*dmvnorm(x, mean = c(1,2), sigma = matrix(c(2,0.5,0.5,2), nrow = 2, byrow = TRUE), 
               log = TRUE)
}

# Create iterated version of line search:
coord.descent <- function(f,x0,tol = 1e-8, ...){
  converged <- FALSE
  x.current <- x0
  f1 <- Inf
  f0 <- f(x0)
  # Get one dimensional objective functions
  objectives <- lapply(1:length(x0), function(idx){
    function(x){
      x.current[idx] <- x
      f(x.current)
    }
  })
  
  while (!converged){
    # iterate
    for (idx in 1:length(x.current)){
      x.current[idx] <- f.min(objectives[[idx]], x0 = x.current[idx], 
                       gradFunc = fd_deriv, tol = 1e-8,...)$x
      #print(x.current)
    }
    f1 <- f(x.current)
    converged <- abs(f1 - f0) <= tol
    f0 <- f1
  }
  x.current
}
coord.descent(obj.fun.2d, c(-10,10))
## [1] 1 2

Misc. Topics in C++

f <- function(n){
  out <- 0.0
  for (i in 1:n){
    out <- out + i
  }
  out
}

system.time({f(100000)})
##    user  system elapsed 
##       0       0       0
library(Rcpp); 

sum_some_stuff_R <- function(n){
  out <- 0.0
  for (i in 0:(n-1)){
    out <- out + i
  }
  out
}

cppFunction(code = "
double sum_some_stuff(int n){
  double out = 0;
  int i;
  for (i = 0; i < n; i++){
    out += i; 
  }
  return(out);
}")


cppFunction(code = "
double sum_some_stuff(int n){
  double out = 0;
  int i;
  for (i = 0; i < n; i++){
    out += i; 
  }
  return(out);
}")



system.time({print(sum_some_stuff(1e8))})
## [1] 5e+15
##    user  system elapsed 
##    0.08    0.00    0.08
system.time({print(sum_some_stuff_R(1e8))})
## [1] 5e+15
##    user  system elapsed 
##    2.75    0.00    2.75
library(BIOS7330)

system.time(print(nth_prime(10000)))
## [1] 104723
##    user  system elapsed 
##    7.78    0.00    7.79
system.time(print(nth_prime_cpp(10000)))
## [1] 104723
##    user  system elapsed 
##    0.14    0.00    0.14
cppFunction(code = "
double sum_some_stuff(int n){
  
  Rcpp::NumericVector MyVec = Rcpp::NumericVector(10);
  int i;
  for (i = 0; i < MyVec.size(); i++){
    MyVec[i] = i;
  }
  
  /*
  for (i = 0; i < n; i++){
    Rcpp::Rcout << MyVec[i] << std::endl;
  }
  */
  return(0);
}", depends = "Rcpp")


sum_some_stuff(200)
## [1] 0

Trees and Ensembles

The following (inefficient but illustrative) examples illustrate several algorithmic model fitting approaches.

X <- runif(1000, -10,10)
Y <- 1/(1+0.25*X^2)*cos(X) + rnorm(length(X), sd = 0.01)
plot(X,Y)

dat <- data.frame(X =X,Y=Y)

## Option 1: hand-construct an appropriate basis:
library(splines)
lm.out <- lm(Y~ns(X, df = 20))
Xpred <- seq(-10,10, length = 100)
lines(Xpred, predict(lm.out, newdata = data.frame(X=Xpred)), 
      col = "red", type = "l", lwd = 2)

## Option 2: build a functional estimate algorithmically 

##A: Decision Tree
library(rpart)
treemod <- rpart(Y ~ X, 
                 control = rpart.control(minsplit = 20,
                                         maxdepth = 30))
plot(X,Y)
lines(Xpred, predict(treemod, newdata = data.frame(X=Xpred)), 
      col = "red", type = "l")

##B: Bagged Trees/RF
getRFTree <- function(){
  dat.smp <- dat[sample(1:nrow(dat), 
                        size = floor(nrow(dat)/4), 
                        replace = TRUE),]
  rpart(Y ~ X, 
        data= dat.smp,
        control = rpart.control(minsplit = 20, cp= 0))
}

rf <- lapply(1:1000, function(i){getRFTree()})

preds <- Reduce("+", lapply(1:length(rf), function(i){
  predict(rf[[i]], newdata = data.frame(X=Xpred))
}))/length(rf)


plot(X,Y)
lines(Xpred, preds, col = "red", lwd = 2)

## C: Gradient boosted trees

growNext <- function(x,y){
  dat <- data.frame(X=x,Y=y)
  modFit <- rpart(Y ~ X, data = dat,
                  control=rpart.control(minsplit = 20, 
                                        cp= 1e-4, 
                                        maxdepth = 2))
  function(x){
    predict(modFit, newdata = data.frame(X=x))
  }
}


# (inefficient) Example univariate gradient booster with squared error loss
gradboost <- function(X, Y, alpha = 0.1, itrs=100){
  y.idx <- 1:length(Y)
  r <- matrix(NA, nrow = itrs, ncol = length(Y))
  yhat <- matrix(NA, nrow = itrs, ncol = length(Y))
  flist <- lapply(1:itrs, function(x){NA})
  
  idx <- sample(y.idx, replace = TRUE)
  flist[[1]] <- growNext(X[idx], Y[idx]) 

  # Initial residuals
  yhat[1,] <- flist[[1]](X)
  r[1,] <- (Y-yhat[1,])
  for (i in 2:itrs){
    idx <- sample(y.idx, replace = TRUE)
    flist[[i]] <- growNext(X[idx], r[i-1,idx])
    yhat[i,] <- yhat[i-1,] + alpha * flist[[i]](X)
    r[i,] <- (Y-yhat[i,])
  }
  list(r=r, yhat = yhat, funcs = flist, alpha = alpha)
}


fhat <- gradboost(X,Y, itrs = 100)
for (iteration in round(seq(2, length(fhat$funcs), length = 100))){
  plot(X,Y)  
  preds <- fhat$funcs[[1]](data.frame(X=Xpred))
  for (i in 2:iteration){
    preds <- preds + fhat$alpha *fhat$funcs[[i]](data.frame(X=Xpred)) 
  }
  lines(Xpred, preds, col = "red", lwd = 2)
}