Define a basic numerical (finite difference) approach to a line search:
fd_deriv <- function(f,x){
# Make sure we're not multiplying by 0 or something small
eps <- abs(sqrt(.Machine$double.eps))
h <- max(eps*x, eps)
(f(x+h) - f(x))/h
}
f.min <- function(f, x0, gradFunc = fd_deriv, tol = 1e-8,...){
# Starting derivative
df <- gradFunc(f,x0,...)
# Starting objective value
f0 <- f(x0)
# Starting change in objective
fd <- Inf
# Check for absolute and relative tolerance
while(abs(df) > tol && fd > tol){
#cat("f'(", x0, ") = ", df, "\n")
# Propose next step:
x1 <- x0 - df
# Evaluate function
f1 <- f(x1)
# Check if we've gone too far:
while (f1 > f0){
df <- df/2
x1 <- x0 - df
f1 <- f(x1)
}
x0 <- x1
df <- gradFunc(f,x0,...)
fd <- abs(f1-f0)
f0 <- f1
}
return(x1)
}
Let’s try it out on an example function:
# Which one of the following is preferable?
obj.fun <- function(u){
-log(dnorm(19, mean = u, sd = 4))
}
obj.fun <- function(u){
-dnorm(19, mean = u, sd = 4, log = TRUE)
}
obj.fun(1)
## [1] 12.43023
fd_deriv(obj.fun, -1)
## [1] -1.25
fd_deriv(obj.fun, 19)
## [1] 7.842716e-09
# Try the following with and without diagnostic information printing
f.min(f = obj.fun, x0 = -1)
## [1] 18.99848
Let’s make this a visual example:
f.min.visualize <- function(f, x0, gradFunc = fd_deriv, tol = 1e-8,...){
# Starting derivative
df <- gradFunc(f,x0,...)
# Starting objective value
f0 <- f(x0)
# Starting change in objective
fd <- Inf
# Check for absolute and relative tolerance
while(abs(df) > tol && fd > tol){
#cat("f'(", x0, ") = ", df, "\n")
# Propose next step:
x1 <- x0 - df
# Evaluate function
f1 <- f(x1)
# Check if we've gone too far:
while (f1 > f0){
df <- df/2
x1 <- x0 - df
f1 <- f(x1)
}
x0 <- x1
df <- gradFunc(f,x0,...)
fd <- abs(f1-f0)
f0 <- f1
{
par(mfrow = c(1,2))
par(bg = "white")
plot(seq(0,40,0.1), f(seq(0,40,0.1)),
type = "l", main = paste0("Objective Function\n x = ",
round(x1, 3), ", f(x) = ", round(f1, 3)),
xlab = "X", ylab = "f(x)")
points(x1, f(x1), col ="blue")
par(bg = "white")
plot(seq(0,40,0.1), gradFunc(f, seq(0,40,0.1)),
type = "l", main = paste0("Derivative\n df = ",
round(df, 3), ", change-f = ", round(fd, 3)),
xlab = "X", ylab = "f'(x)")
points(x1, gradFunc(f, x1), col ="blue")
}
}
return(x1)
}
f.min.visualize(f = obj.fun, x0 = -1)
## [1] 18.99848
How does this change if we use other numerical derivatives, or alternate optimization routines?
install.packages("numDeriv")
library(numDeriv)
system.time(replicate(100, {r1 <- f.min(f = obj.fun, gradFunc = fd_deriv, x0 = rnorm(1,0,1))}))
## user system elapsed
## 0.11 0.00 0.11
system.time(replicate(100, {r2 <- f.min(f = obj.fun, gradFunc = numDeriv::grad, x0 = rnorm(1,0,1))}))
## user system elapsed
## 1.14 0.00 1.16
system.time(replicate(100, {r3 <- f.min(f = obj.fun, gradFunc = numDeriv::grad, x0 = rnorm(1,0,1), method = "simple")}))
## user system elapsed
## 0.29 0.00 0.28
system.time(replicate(100, {r4 <- optimize(obj.fun, interval = c(-20,200), maximum = FALSE)}))
## user system elapsed
## 0.01 0.00 0.01
## See also: 'deriv'
What are the performance concerns here?
# Make the problem more challenging
X <- rnorm(100000, mean = 25, sd = 4)
obj.fun2 <- function(u){
-sum(dnorm(X, mean = u, sd = 4, log = TRUE))
}
x0 <- 0
system.time({r1 <- f.min(f = obj.fun2, gradFunc = fd_deriv, x0 = x0, tol = 1e-4)})
## user system elapsed
## 1.58 0.13 1.70
system.time({r2 <- f.min(f = obj.fun2, gradFunc = fd_deriv, x0 = x0, tol = 1e-8)})
## user system elapsed
## 1.90 0.07 1.98
system.time({r3 <- f.min(f = obj.fun2, gradFunc = numDeriv::grad, x0 = x0)})
## user system elapsed
## 2.85 0.15 2.99
system.time({r4 <- f.min(f = obj.fun2, gradFunc = numDeriv::grad, x0 = x0, method = "simple")})
## user system elapsed
## 1.61 0.04 1.67
system.time({r5 <- optimize(obj.fun2, interval = c(-20,200), maximum = FALSE)})
## user system elapsed
## 0.03 0.00 0.04
Perhaps we should investigate how many evaluations are being done:
f.min <- function(f, x0, gradFunc = fd_deriv, tol = 1e-8,...){
# Performance information
st <- Sys.time()
itrs <- 0
halving_steps <- 0
# Starting derivative
df <- gradFunc(f,x0,...)
# Starting objective value
f0 <- f(x0)
# Starting change in objective
fd <- Inf
# Check for absolute and relative tolerance
while(abs(df) > tol && fd > tol){
itrs <- itrs + 1
#cat("f'(", x0, ") = ", df, "\n")
# Propose next step:
x1 <- x0 - df
# Evaluate function
f1 <- f(x1)
# Check if we've gone too far:
while (f1 > f0){
halving_steps <- halving_steps + 1
df <- df/2
x1 <- x0 - df
f1 <- f(x1)
}
x0 <- x1
df <- gradFunc(f,x0,...)
fd <- abs(f1-f0)
f0 <- f1
}
return(list(x=x1, obj = f(x1), itrs = itrs, halving_steps = halving_steps, runtime = Sys.time() - st))
}
system.time(r1.small <- f.min(f = obj.fun, x0 = rnorm(1,0,1), tol = 1e-4))
## user system elapsed
## 0.02 0.00 0.01
system.time(r1.large <- f.min(f = obj.fun2, gradFunc = fd_deriv, x0 = rnorm(1,0,1), tol = 1e-4))
## user system elapsed
## 1.47 0.07 1.53
r1.small
## $x
## [1] 18.84966
##
## $obj
## [1] 2.305939
##
## $itrs
## [1] 76
##
## $halving_steps
## [1] 0
##
## $runtime
## Time difference of 0.0009839535 secs
r1.large
## $x
## [1] 25.02863
##
## $obj
## [1] 280433.3
##
## $itrs
## [1] 20
##
## $halving_steps
## [1] 240
##
## $runtime
## Time difference of 1.539191 secs
options(digits = 22)
as.numeric(r1.small$runtime*1000/(r1.small$itrs + r1.small$halving_steps))
## [1] 0.012946756262528268
as.numeric(r1.large$runtime*1000/(r1.large$itrs + + r1.large$halving_steps))
## [1] 5.9199654139005222
options(digits = 4)
We’ll do more with “profiling” in a future lecture, but for now it’s pretty clear that the major issue is (time per iteration)*(number of iterations) - in other words, if we want to make things faster, we can improve how quickly the objective function runs, or reduce the total number of function evaluations. This includes derivative evaluations.
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)
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
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
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
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)
}