Optimization

Optimization is one of the fundamental tools of statistics, data science, and just about every other data oriented subfield of science and engineering. At its core, optimization is very simple: for a given function \(f({\boldsymbol\theta})\), find the value(s) of \(\bf{\theta}\) such that \(f(\boldsymbol\theta)\) is minimized or maximized.

Introduction

For additional information, make sure to read through the corresponding in class notes, as well as the lecture slides.

For simple functions, we can do this analytically:

\(f(\theta) = -2(\theta-2)^2\), so we can easily see that \(\frac{\partial{}}{\partial{\theta}}f(\theta) = -4(\theta-2)\), which is maximized at \(\theta = 2\)

This single dimensional problem is also solvable via a line search, provided we specify some reasonable bounds:

f <- function(x){
  -2*(x-2)^2
}

optimize(f, interval = c(-10, 10), maximum=TRUE)
## $maximum
## [1] 2
## 
## $objective
## [1] 0

This is known as a ‘global maximum’, since it is the maximum value the function takes on over the whole parameter space. Many functions also have ‘local maxima’ or minima, and may or may not have global ones:

f <- function(x){2*x^3 - 5*x}
curve(f, from = -3, to = 3)

Asking for a global extreme for such a function is not a well defined question, but this is not always apparent in practice until you attempt to optimize the function. This is particularly true as the dimension of \(\boldsymbol\theta\) increases, and things become more difficult to visualize.

There also might be infinite global extremes:

curve(sin, from = -10, to = 10, main = "Sine Function")

Or infinite local extremes, and no global extremes (minimum in this case):

f <- function(x){2*cos(x) - abs(x)}
curve(f, from = -20, to = 20, main = "Sine Function")

Functions can be differentiable, or not. Functions can be finite in their range, or not. Functions can have bounded, or unbounded domain, and the domain can be a well behaved convex set, or something messier. You might be interested in optimizing a function globally, or subject to particular constraints. In short, optimization is a complex and diverse topic, with different algorithms and techniques available depending on the nature of the problem to be solved.

Making Grids

One of the simplest useful approaches to optimization is based on ‘grids’. A grid is a collection of points in \(\mathcal{R}^n\) which are equally spaced along each dimension. For example, a single dimensional grid can be constructed via the ‘seq’ function:

gd <- seq(-20,20,by = 0.5)

We can learn about a curve or surface by simply evaluating it over the points specified by the grid:

f.gd <- sapply(gd, f)
plot(f.gd ~ gd)

gd[which.max(f.gd)]
## [1] 0

In this example, one of our grid points happened to exactly fall on the global maximum, so we were able to find it immediately. For other functions, this is going to simply be a point estimate (of varying quality)

f <- function(x){z <- x -0.22134; 2*cos(z) - abs(z)}
f.gd <- sapply(gd, f)
plot(f.gd ~ gd)
abline(v =  0.22134, lty = 2)

abserr <- abs(gd[which.max(f.gd)] - 0.22134)
print(paste0("Estimate is: ", gd[which.max(f.gd)], ", absolute error is: ", abserr))
## [1] "Estimate is: 0, absolute error is: 0.22134"

In this case, we’re still close, but how well we do depends on the fineness of the grid:

gd <- seq(-20,20,by = 0.005)
f.gd <- sapply(gd, f)
plot(f.gd ~ gd)
abline(v =  0.22134, lty = 2)

abserr <- abs(gd[which.max(f.gd)] - 0.22134)
print(paste0("Estimate is: ", gd[which.max(f.gd)], ", absolute error is: ", abserr))
## [1] "Estimate is: 0.219999999999999, absolute error is: 0.00134000000000115"

As you can imagine, choosing a sufficient number of grid points can be very challenging! Fortunately, there are a number of ways we can approach the problem iteratively.

Grid Search in One Dimension

The following function implements a recursive grid search of a function (called “objective”) between two bounds. It is designed to look for a maximum. Read through the code and make sure you understand how it works:

grid.search.1d <- function(objective, 
                           LB, 
                           UB, 
                           npts=10, 
                           tolerance = 1e-8,
                           show.plots=TRUE,
                           verbose=TRUE, ...){
  # Is the region small enough to return an answer?
  if (abs(UB - LB) <= tolerance){
    return((UB+LB)/2)
  }
  
  if (verbose){
    # print verbose output
    cat(paste0("Grid search: [",  LB, ", ", UB, "]\n"))
  }
  
  # Create Grid
  x <- seq(LB, UB, length = npts)
  d.x <- x[2]-x[1]
  f.x <- objective(x, ...)
  max.idx <- which.max(f.x)
  
  if (show.plots){
    plot(x,f.x, col = ifelse(1:length(x) == max.idx, "red", "black"), pch = 16)
  }
  return(grid.search.1d(objective, 
                        LB = x[max.idx] - 2*d.x, 
                        UB =  x[max.idx] + 2*d.x, 
                        npts = npts,
                        tolerance = tolerance, 
                        show.plots = show.plots,
                        ...))
}


grid.search.1d(f, -20, 20)
## Grid search: [-20, 20]

## Grid search: [-6.66666666666667, 11.1111111111111]

## Grid search: [-4.69135802469136, 3.20987654320988]

## Grid search: [-1.17969821673525, 2.33196159122085]

## Grid search: [-0.399329370522786, 1.16140832190215]

## Grid search: [-0.0524987722061341, 0.64116242442717]

## Grid search: [0.101648160379045, 0.409942025549402]

## Grid search: [0.135903034286862, 0.272922529918132]

## Grid search: [0.19680058790076, 0.257698141514658]

## Grid search: [0.210333377592737, 0.237398956976692]

## Grid search: [0.216347950789172, 0.22837709718204]

## Grid search: [0.219021094432031, 0.224367381717751]

## Grid search: [0.220209158273302, 0.222585285955844]

## Grid search: [0.2207371866472, 0.221793243394997]

## Grid search: [0.221089205563133, 0.221558564117709]

## Grid search: [0.221245658414658, 0.221454262216692]

## Grid search: [0.22129201481511, 0.221384727616014]

## Grid search: [0.221322919082078, 0.221364124771369]

## Grid search: [0.22133207590192, 0.221350389541605]

## Grid search: [0.221336145599628, 0.221344284995043]

## Grid search: [0.221337954354165, 0.221341571863238]

## Grid search: [0.221339160190523, 0.221340767972333]

## Grid search: [0.221339696117793, 0.221340410687486]

## Grid search: [0.221339854911058, 0.221340172497588]

## Grid search: [0.221339925485843, 0.221340066635412]

## Grid search: [0.221339972535699, 0.221340035268841]

## Grid search: [0.221339986476397, 0.221340014357793]

## Grid search: [0.221339992672263, 0.221340005063995]

## [1] 0.22134

This technique is obviously not foolproof. The function to be optimized needs to be sufficiently smooth relative to the fineness of the grid such that extrema are not missed in the interstices. Nevertheless, this is a very general technique. In fact, grid search is easily extended to multiple dimensions, though its efficiency can suffer greatly due to the curse of dimensionality.

In R, it’s easy to create multidimensional grids from unidimensional ones:

x1 <- seq(-10,10,1)
x2 <- seq(2,4,0.1)
gd <- expand.grid(x1,x2)
plot(gd[,1], gd[,2])

It’s also straightforward to evaluate functions over these grids:

f.2d <- function(par){
  d1 <- (par - c(5,3))
  d2 <- (par - c(-5,2))
  exp(-2*c(d1%*%d1)) + exp(-0.25*c(d2%*%d2))
}

y <- apply(gd, 1, f.2d)

We can even illustrate these pretty easily, at least for two dimensional problems:

y.color.mat <- matrix(heat.colors(15)[cut(y, breaks = 15)], 
                      nrow = length(x1), ncol = length(x2), byrow=TRUE)
plot(0,0, xlim = range(x1), ylim = range(x2), type = "n")
rasterImage(y.color.mat, xleft = min(x1), xright = max(x1), ybottom = min(x2), ytop = max(x2))

Assignment

Write a function, grid.search.nd, which can perform an n-dimensional version of the grid search illustrated above. The function should follow something like the following template:

grid.search.nd <- function(objective, par, widths, npts=10, 
                           tolerance = 1e-8, ...){
  # Construct the grid
  gd.list <- lapply(1:length(par), function(i){seq(par[i] - widths[i], 
                                                   par[i] + widths[i], 
                                                   length = npts)})
  gd <- expand.grid(gd.list)
  # Perform the grid search here
}

Construct appropriate on, two, and three dimensional functions to demonstrate that your solution works. Please submit your answer as a compiled Rmarkdown or Sweave document on ICON.