Practical Concerns for Machine Learning Techniques

Many machine learning techniques can be cast as optimization problems; in fact, in The Elements Of Statistical Learning, this is precisely the perspective the authors take throughout. Often, however, using a given technique in practice involves multiple layers of optimization: executing the algorithm given a set of tuning parameters to minimize a given loss function, and finding the best performing combination of tuning parameters.

Example: Random Forests

Background/Reading Material

The Random Forest approach to regression and classification is a popular and well documented technique, applicable to many different problems. Random Forests are an ensemble method, meaning they combine the results of multiple algorithms or multiple runs of the same algorithm to attain improved performance. The fundamental unit of a Random Forest is a regression or classification tree, usually constructed using the CART algorithm. This algorithm is described in detail in section 9.2 of the Elements book, and provides a method of estimating a recursive binary tree, albeit in a ‘greedy’ fashion.

A ‘greedy’ algorithm makes locally optimal decisions at each iteration, in the hope that a good global minimum can be found. Consider, for example, coordinate descent, which finds a minimum in one dimension at a time. The CART algorithm is actually quite like a coordinate descent algorithm, except instead of choosing coordinates in an n-dimensional system, it chooses break-points in such dimensions to divide the sample up. Please refer to the links above for more information.

Working with Random Forests

The randomForest package is still one of the most popular ways to fit randomForest models, despite the fact that the underlying code is quite old. The package is single-threaded, meaning that by default it is unable to take advantage of parallel processing. Fortunately, for our purposes in this lab, this will simplify things when we want to evaluate many model runs.

# Classification Example
library(randomForest)
## randomForest 4.6-14
## Type rfNews() to see new features/changes/bug fixes.
data(iris)
train.idx <- sample(1:nrow(iris), size = 120)
test.idx <- setdiff(1:nrow(iris), train.idx)
iris.train <- iris[train.idx,]
iris.test <- iris[test.idx,]


rf.out <- randomForest(Species ~ ., data = iris.train, 
                       sampsize = 100,
                       nodesize = 20)
                       
# Fitted values in sample
table(iris.train$Species, rf.out$predicted)
##             
##              setosa versicolor virginica
##   setosa         39          0         0
##   versicolor      0         38         2
##   virginica       0          4        37
rf.pred <- predict(rf.out, iris.test)
table(iris.test$Species, rf.pred)
##             rf.pred
##              setosa versicolor virginica
##   setosa         11          0         0
##   versicolor      0          9         1
##   virginica       0          0         9

As you can see, the randomForest above does a pretty good job of classifying the irises into species, with just some slight confusion between versicolor and virginica.

If we want to optimize this model fitting process, we need some quantitative measure of performance. One metric we could use is simply the correct classification rate:

mean(iris.train$Species == rf.out$predicted)
## [1] 0.95
mean(iris.test$Species == rf.pred)
## [1] 0.9666667

We need to think carefully about which measure we use: if we focus on the training data, the ‘optimal’ model will likely overfit the data. By focusing on the test data, we’ll be estimating the extrapolation performance of the model we choose.

Tuning Parameter Optimization

When it comes to the task of tuning parameter optimization, our new function to be optmized is a loss function evaluated on test data. As such, we need a concise way to ‘evaluate’ that function:

pred.loss <- function(param, n.itrs = 10){
  print(c(param))
  trials <- sapply(1:n.itrs, function(x){
    
    train.idx <- sample(1:nrow(iris), size = 120)
    test.idx <- setdiff(1:nrow(iris), train.idx)
    iris.train <- iris[train.idx,]
    iris.test <- iris[test.idx,]
  
  
    rf.out <- randomForest(Species ~ ., data = iris.train, ntree = 500,
                         sampsize = param[1],
                         nodesize = param[2])
                         
  
    rf.pred <- predict(rf.out, iris.test)
    1-mean(iris.test$Species == rf.pred)
  })
  mean(trials)
}

As you can see, we’re actually running the analysis several times. This is because for each partition into test/training data, we’ll get a slightly different model, and slightly different performance. This ad-hoc averaging is designed to decrease the variability. As you can imagine, however, this adds a lot of computational burden! For some procedures, cross validation is performed internally, but it is still a costly procedure.

sampsizes <- c(50, 75, 100, 120)
nodesizes <- c(1, 5, 10, 25, 50)

param.grid <- as.matrix(expand.grid(sampsizes, nodesizes))

system.time(rslt <- apply(param.grid, 1, pred.loss))
## Var1 Var2 
##   50    1 
## Var1 Var2 
##   75    1 
## Var1 Var2 
##  100    1 
## Var1 Var2 
##  120    1 
## Var1 Var2 
##   50    5 
## Var1 Var2 
##   75    5 
## Var1 Var2 
##  100    5 
## Var1 Var2 
##  120    5 
## Var1 Var2 
##   50   10 
## Var1 Var2 
##   75   10 
## Var1 Var2 
##  100   10 
## Var1 Var2 
##  120   10 
## Var1 Var2 
##   50   25 
## Var1 Var2 
##   75   25 
## Var1 Var2 
##  100   25 
## Var1 Var2 
##  120   25 
## Var1 Var2 
##   50   50 
## Var1 Var2 
##   75   50 
## Var1 Var2 
##  100   50 
## Var1 Var2 
##  120   50
##    user  system elapsed 
##    3.18    0.09    3.31
plotMatrix <- function(M){
  image(t(M[nrow(M):1,]))
}
M <- matrix(rslt, nrow = length(sampsizes), ncol = length(nodesizes))
plotMatrix(1/M)

param.grid[which.min(rslt),]
## Var1 Var2 
##   75    1

Assignment

Your task is to use a grid search to find good tuning parameters for classifying the MNIST data. Obviously, given the computationally intensive nature of the problem, you’ll have to be conservative in the number of conditions you vary, and how stringent your grid search is.

Also, while we’re not yet to the part of the course where we’ll talk about parallel processing in detail, we can mention a few preliminaries here.

Example: Parallel

The most basic type of parallel processing is multi-processing, or running multiple instances of the a program at the same time. Recent versions of R provide mechanisms to do this automatically:

library(parallel)
# Create a 4 core cluster
cl <- makeCluster(4)

These ‘clusters’ are essentially hidden R windows, waiting for commands to be run. One of my favorite ways to run code on cluster ‘nodes’ is the parLapply function:

result <- parLapply(cl, 1:length(cl), function(x){paste0("The random number ", rpois(1,10), " was generated on node ", x)})
print(result)
## [[1]]
## [1] "The random number 9 was generated on node 1"
## 
## [[2]]
## [1] "The random number 10 was generated on node 2"
## 
## [[3]]
## [1] "The random number 22 was generated on node 3"
## 
## [[4]]
## [1] "The random number 9 was generated on node 4"

If you look at the help page for parLapply, you’ll see that there are equivalents for the other apply type functions.

One complication is that our new R processes don’t have the packages loaded that we’d like them to, and they don’t know about any objects currently living in our global namespace. This is easily remedied:

# Load a package on the nodes
parLapply(cl, 1:length(cl), function(x){library(randomForest)})
## [[1]]
## [1] "randomForest" "stats"        "graphics"     "grDevices"   
## [5] "utils"        "datasets"     "methods"      "base"        
## 
## [[2]]
## [1] "randomForest" "stats"        "graphics"     "grDevices"   
## [5] "utils"        "datasets"     "methods"      "base"        
## 
## [[3]]
## [1] "randomForest" "stats"        "graphics"     "grDevices"   
## [5] "utils"        "datasets"     "methods"      "base"        
## 
## [[4]]
## [1] "randomForest" "stats"        "graphics"     "grDevices"   
## [5] "utils"        "datasets"     "methods"      "base"
# Export a list of objects to the nodes
clusterExport(cl, c("pred.loss"))

Finally, when we’re done, we should stop the cluster with:

stopCluster(cl)

Example: Read in, process, and model the MNIST data

readMNISTImages <- function(fname){
  imgCon = file(fname, "rb")
  magicNumber = readBin(imgCon, "int", n = 1, size = 4, endian = "big")
  nImg = readBin(imgCon, "int", n = 1, size = 4, endian = "big")
  nRow = readBin(imgCon, "int", n = 1, size = 4, endian = "big")
  nCol = readBin(imgCon, "int", n = 1, size = 4, endian = "big")

  imageList = lapply(1:nImg, function(x){
   matrix(as.numeric(readBin(imgCon, "int", n = nRow*nCol, size = 1, endian = "big")),
          nrow = nRow, ncol = nCol)
  })
  close(imgCon)
  imageList
}

readMNISTLabels <- function(fname){
  labCon = file(fname, "rb")
  magicNumber = readBin(labCon, "int", n = 1, size = 4, endian = "big")
  nItems = readBin(labCon, "int", n = 1, size = 4, endian = "big")
  
  imageLabels = sapply(1:nItems, function(x){
    readBin(labCon, "int", n = 1, size = 1, endian = "big", signed = FALSE)
  })
  close(labCon)
  imageLabels
}

train_img <- readMNISTImages("./train-images.idx3-ubyte")
train_labels <- readMNISTLabels("./train-labels.idx1-ubyte")

test_img <- readMNISTImages("./t10k-images.idx3-ubyte")
test_labels <- readMNISTLabels("./t10k-labels.idx1-ubyte")

# Turn training data into a matrix we can use in modeling
training_data <- matrix(unlist(train_img), nrow = length(train_img), byrow = TRUE)
training_data = data.frame(Y = as.factor(train_labels),
                           X = training_data)

# Omit pixels with little to no information
keep_idx <- apply(training_data, 2, var) > 1
training_data <- training_data[,keep_idx]

system.time({rf.out <- randomForest(Y ~ ., data = training_data, ntree = 500,
                       mtry = 10,
                       sampsize = 1000,
                       nodesizes = 25)})
##    user  system elapsed 
##  264.10    0.68  265.11

Additional Reading

Often, this kind of metaparameter tuning is not handled manually, but it’s worth being aware of what’s going on. Check out the caret documentation on model tuning to see an automated approach.