Guide to SuperLearner

Chris Kennedy, University of California, Berkeley

March 16, 2017

1 Background

SuperLearner is an algorithm that uses cross-validation to estimate the performance of multiple machine learning models, or the same model with different settings. It then creates an optimal weighted average of those models, aka an “ensemble”, using the test data performance. This approach has been proven to be asymptotically as accurate as the best possible prediction algorithm that is tested.

(We are oversimplifying this in the interest of brevity. Please see the references for more detailed information, especially “SuperLearner in Prediction”.)

2 Software requirements and installation

Make sure to have R 3.2 or greater, and preferably 3.3+.

Install the stable version of SuperLearner from CRAN:

install.packages("SuperLearner")

Or the development version from Github:

# Install devtools first:
# install.packages("devtools")
devtools::install_github("ecpolley/SuperLearner")

The Github version generally has some new features, fixes some bugs, but may also introduce new bugs. We will use the github version, and if we run into any bugs we can report them. This material is also currently consistent with the latest SuperLearner on CRAN (2.0-21).

Install the other packages we will use:

install.packages(c("caret", "glmnet", "randomForest", "ggplot2", "RhpcBLASctl"))

For XGBoost we need to tweak the install command a bit; Windows users may need to install Rtools first.

install.packages("xgboost", repos=c("http://dmlc.ml/drat/", getOption("repos")), type="source")

3 Setup dataset

We will be using the “Boston” dataset which is available from the “MASS” package.

############################
# Setup example dataset.

# Load a dataset from the MASS package.
data(Boston, package = "MASS")

# Review info on the Boston dataset.
?Boston
## No documentation for 'Boston' in specified packages and libraries:
## you could try '??Boston'
# Check for any missing data - looks like we don't have any.
colSums(is.na(Boston))
##    crim      zn   indus    chas     nox      rm     age     dis     rad 
##       0       0       0       0       0       0       0       0       0 
##     tax ptratio   black   lstat    medv 
##       0       0       0       0       0
# Extract our outcome variable from the dataframe.
outcome = Boston$medv

# Create a dataframe to contain our explanatory variables.
data = subset(Boston, select = -medv)

# Check structure of our dataframe.
str(data)
## 'data.frame':    506 obs. of  13 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
# If we had factor variables we would use model.matrix() to convert to numerics.

# Review our dimensions.
dim(data)
## [1] 506  13
# Set a seed for reproducibility in this random sampling.
set.seed(1)

# Reduce to a dataset of 150 observations to speed up model fitting.
train_obs = sample(nrow(data), 150)

# X is our training sample.
X_train = data[train_obs, ]

# Create a holdout set for evaluating model performance.
# Note: cross-validation is even better than a single holdout sample.
X_holdout = data[-train_obs, ]

# Create a binary outcome variable: towns in which median home value is > 22,000.
outcome_bin = as.numeric(outcome > 22)

Y_train = outcome_bin[train_obs]
Y_holdout = outcome_bin[-train_obs]

# Review the outcome variable distribution.
table(Y_train, useNA = "ifany")
## Y_train
##  0  1 
## 79 71

4 Review available models

library(SuperLearner)
## Loading required package: nnls
## Super Learner
## Version: 2.0-22
## Package created on 2017-07-18
# Review available models.
listWrappers()
## All prediction algorithm wrappers in SuperLearner:
##  [1] "SL.bartMachine"      "SL.bayesglm"         "SL.biglasso"        
##  [4] "SL.caret"            "SL.caret.rpart"      "SL.cforest"         
##  [7] "SL.dbarts"           "SL.earth"            "SL.extraTrees"      
## [10] "SL.gam"              "SL.gbm"              "SL.glm"             
## [13] "SL.glm.interaction"  "SL.glmnet"           "SL.ipredbagg"       
## [16] "SL.kernelKnn"        "SL.knn"              "SL.ksvm"            
## [19] "SL.lda"              "SL.leekasso"         "SL.lm"              
## [22] "SL.loess"            "SL.logreg"           "SL.mean"            
## [25] "SL.nnet"             "SL.nnls"             "SL.polymars"        
## [28] "SL.qda"              "SL.randomForest"     "SL.ranger"          
## [31] "SL.ridge"            "SL.rpart"            "SL.rpartPrune"      
## [34] "SL.speedglm"         "SL.speedlm"          "SL.step"            
## [37] "SL.step.forward"     "SL.step.interaction" "SL.stepAIC"         
## [40] "SL.svm"              "SL.template"         "SL.xgboost"
## 
## All screening algorithm wrappers in SuperLearner:
## [1] "All"
## [1] "screen.SIS"            "screen.corP"           "screen.corRank"       
## [4] "screen.glmnet"         "screen.randomForest"   "screen.template"      
## [7] "screen.ttest"          "write.screen.template"
# Peek at code for a model.
SL.glmnet
## function (Y, X, newX, family, obsWeights, id, alpha = 1, nfolds = 10, 
##     nlambda = 100, useMin = TRUE, loss = "deviance", ...) 
## {
##     .SL.require("glmnet")
##     if (!is.matrix(X)) {
##         X <- model.matrix(~-1 + ., X)
##         newX <- model.matrix(~-1 + ., newX)
##     }
##     fitCV <- glmnet::cv.glmnet(x = X, y = Y, weights = obsWeights, 
##         lambda = NULL, type.measure = loss, nfolds = nfolds, 
##         family = family$family, alpha = alpha, nlambda = nlambda, 
##         ...)
##     pred <- predict(fitCV, newx = newX, type = "response", s = ifelse(useMin, 
##         "lambda.min", "lambda.1se"))
##     fit <- list(object = fitCV, useMin = useMin)
##     class(fit) <- "SL.glmnet"
##     out <- list(pred = pred, fit = fit)
##     return(out)
## }
## <environment: namespace:SuperLearner>

For maximum accuracy one might try at least the following models: glmnet, randomForest, XGBoost, SVM, and bartMachine. These should ideally be tested with multiple hyperparameter settings for each algorithm.

5 Fit individual models

Let’s fit 2 separate models: lasso (sparse, penalized OLS) and randomForest. We specify family = binomial() because we are predicting a binary outcome, aka classification. With a continuous outcome we would specify family = gaussian().

# Set the seed for reproducibility.
set.seed(1)

# Fit lasso model.
sl_lasso = SuperLearner(Y = Y_train, X = X_train, family = binomial(),
                        SL.library = "SL.glmnet")
## Loading required package: glmnet
## Loading required package: Matrix
## Loading required package: foreach
## Loaded glmnet 2.0-10
sl_lasso
## 
## Call:  
## SuperLearner(Y = Y_train, X = X_train, family = binomial(), SL.library = "SL.glmnet") 
## 
## 
## 
##                    Risk Coef
## SL.glmnet_All 0.1330516    1
# Review the elements in the SuperLearner object.
names(sl_lasso)
##  [1] "call"              "libraryNames"      "SL.library"       
##  [4] "SL.predict"        "coef"              "library.predict"  
##  [7] "Z"                 "cvRisk"            "family"           
## [10] "fitLibrary"        "varNames"          "validRows"        
## [13] "method"            "whichScreen"       "control"          
## [16] "cvControl"         "errorsInCVLibrary" "errorsInLibrary"  
## [19] "metaOptimizer"     "env"               "times"
# Here is the risk of the best model (discrete SuperLearner winner).
sl_lasso$cvRisk[which.min(sl_lasso$cvRisk)]
## SL.glmnet_All 
##     0.1330516
# Here is the raw glmnet result object:
str(sl_lasso$fitLibrary$SL.glmnet_All$object, max.level = 1)
## List of 10
##  $ lambda    : num [1:77] 0.298 0.272 0.248 0.226 0.205 ...
##  $ cvm       : num [1:77] 1.39 1.34 1.29 1.24 1.2 ...
##  $ cvsd      : num [1:77] 0.00877 0.01104 0.01307 0.01565 0.01826 ...
##  $ cvup      : num [1:77] 1.4 1.35 1.3 1.26 1.22 ...
##  $ cvlo      : num [1:77] 1.39 1.33 1.27 1.22 1.18 ...
##  $ nzero     : Named int [1:77] 0 1 1 1 1 2 2 2 2 2 ...
##   ..- attr(*, "names")= chr [1:77] "s0" "s1" "s2" "s3" ...
##  $ name      : Named chr "Binomial Deviance"
##   ..- attr(*, "names")= chr "deviance"
##  $ glmnet.fit:List of 13
##   ..- attr(*, "class")= chr [1:2] "lognet" "glmnet"
##  $ lambda.min: num 0.00954
##  $ lambda.1se: num 0.0673
##  - attr(*, "class")= chr "cv.glmnet"
# Fit random forest.
sl_rf = SuperLearner(Y = Y_train, X = X_train, family = binomial(),
                     SL.library = "SL.randomForest")
## Loading required package: randomForest
## randomForest 4.6-12
## Type rfNews() to see new features/changes/bug fixes.
sl_rf
## 
## Call:  
## SuperLearner(Y = Y_train, X = X_train, family = binomial(), SL.library = "SL.randomForest") 
## 
## 
## 
##                          Risk Coef
## SL.randomForest_All 0.1188808    1

Risk is a measure of model accuracy or performance. We want our models to minimize the estimated risk, which means the model is making the fewest mistakes in its prediction. It’s basically the mean-squared error in a regression model, but you can customize it if you want.

SuperLearner is using cross-validation to estimate the risk on future data. By default it uses 10 folds; use the cvControl argument to customize.

The coefficient column tells us the weight or importance of each individual learner in the overall ensemble. By default the weights are always greater than or equal to 0 and sum to 1. In this case we only have one algorithm so the coefficient has to be 1. If a coefficient is 0 it means that the algorithm isn’t being used in the SuperLearner ensemble.

6 Fit multiple models

Instead of fitting the models separately and looking at the performance (lowest risk), we can fit them simultaneously. SuperLearner will then tell us which one is best (discrete winner) and also create a weighted average of multiple models.

We include the mean of Y (“SL.mean”) as a benchmark algorithm. It is a very simple prediction so the more complex algorithms should do better than the sample mean. We hope to see that it isn’t the best single algorithm (discrete winner) and has a low weight in the weighted-average ensemble. If it is the best algorithm something has likely gone wrong.

set.seed(1)
sl = SuperLearner(Y = Y_train, X = X_train, family = binomial(),
  SL.library = c("SL.mean", "SL.glmnet", "SL.randomForest"))
sl
## 
## Call:  
## SuperLearner(Y = Y_train, X = X_train, family = binomial(), SL.library = c("SL.mean",  
##     "SL.glmnet", "SL.randomForest")) 
## 
## 
##                          Risk      Coef
## SL.mean_All         0.2510508 0.0000000
## SL.glmnet_All       0.1380354 0.1261144
## SL.randomForest_All 0.1213518 0.8738856
# Review how long it took to run the SuperLearner:
sl$times$everything
##    user  system elapsed 
##   2.266   0.027   2.317

Again, the coefficient is how much weight SuperLearner puts on that model in the weighted-average. So if coefficient = 0 it means that model is not used at all. Here we see that random forest is given the most weight, following by lasso.

So we have an automatic ensemble of multiple learners based on the cross-validated performance of those learners, nice!

7 Predict on new data

Now that we have an ensemble let’s predict back on our holdout dataset and review the results.

# Predict back on the holdout dataset.
# onlySL is set to TRUE so we don't fit algorithms that had weight = 0, saving computation.
pred = predict(sl, X_holdout, onlySL = T)

# Check the structure of this prediction object.
str(pred)
## List of 2
##  $ pred           : num [1:356, 1] 0.95 0.693 0.931 0.957 0.952 ...
##  $ library.predict: num [1:356, 1:3] 0 0 0 0 0 0 0 0 0 0 ...
# Review the columns of $library.predict.
summary(pred$library.predict)
##        V1          V2                  V3        
##  Min.   :0   Min.   :0.0003921   Min.   :0.0090  
##  1st Qu.:0   1st Qu.:0.1382133   1st Qu.:0.1400  
##  Median :0   Median :0.4268453   Median :0.4190  
##  Mean   :0   Mean   :0.4743975   Mean   :0.4907  
##  3rd Qu.:0   3rd Qu.:0.8353414   3rd Qu.:0.8668  
##  Max.   :0   Max.   :0.9922678   Max.   :0.9990
# Histogram of our predicted values.
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
## 
##     margin
qplot(pred$pred[, 1]) + theme_minimal()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# Scatterplot of original values (0, 1) and predicted values.
# Ideally we would use jitter or slight transparency to deal with overlap.
qplot(Y_holdout, pred$pred[, 1]) + theme_minimal()

# Review AUC - Area Under Curve
pred_rocr = ROCR::prediction(pred$pred, Y_holdout)
auc = ROCR::performance(pred_rocr, measure = "auc", x.measure = "cutoff")@y.values[[1]]
auc
## [1] 0.9659829

AUC can range from 0.5 (no better than chance) to 1.0 (perfect). So at 0.96 we are looking pretty good!

8 Fit ensemble with external cross-validation

What we don’t have yet is an estimate of the performance of the ensemble itself. Right now we are just hopeful that the ensemble weights are successful in improving over the best single algorithm.

In order to estimate the performance of the SuperLearner ensemble we need an “external” layer of cross-validation, also called nested cross-validation. We generate a separate holdout sample that we don’t use to fit the SuperLearner, which allows it to be a good estimate of the SuperLearner’s performance on unseen data. Typically we would run 10 or 20-fold external cross-validation, but even 5-fold is reasonable.

Another nice result is that we get standard errors on the performance of the individual algorithms and can compare them to the SuperLearner.

set.seed(1)

# Don't have timing info for the CV.SuperLearner unfortunately.
# So we need to time it manually.

# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
system.time({
  # This will take about 3x as long as the previous SuperLearner.
  cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 3,
                          SL.library = c("SL.mean", "SL.glmnet", "SL.randomForest"))
})
##    user  system elapsed 
##   5.195   0.067   5.307
# We run summary on the cv_sl object rather than simply printing the object.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", "SL.randomForest")) 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  3 
## 
##            Algorithm     Ave        se     Min     Max
##        Super Learner 0.16120 0.0185053 0.12403 0.21501
##          Discrete SL 0.16299 0.0187922 0.12445 0.21996
##          SL.mean_All 0.25140 0.0027616 0.24970 0.25450
##        SL.glmnet_All 0.16271 0.0179917 0.13106 0.21996
##  SL.randomForest_All 0.14444 0.0168267 0.12445 0.16432
# Review the distribution of the best single learner as external CV folds.
table(simplify2array(cv_sl$whichDiscreteSL))
## 
##       SL.glmnet_All SL.randomForest_All 
##                   1                   2
# Plot the performance with 95% CIs (use a better ggplot theme).
plot(cv_sl) + theme_bw()

# Save plot to a file.
ggsave("SuperLearner.png")
## Saving 5 x 5 in image

We see two SuperLearner results: “Super Learner” and “Discrete SL”. “Discrete SL” chooses the best single learner - in this case SL.glmnet (lasso). “Super Learner” takes a weighted average of the learners using the coefficients/weights that we examined earlier. In general “Super Learner” should perform a little better than “Discrete SL”.

We see based on the outer cross-validation that SuperLearner is statistically tying with the best algorithm. Our benchmark learner “SL.mean” shows that we get a nice improvement over a naive guess based only on the mean. We could also add “SL.glm” to compare to logistic regression.

9 Customize a model hyperparameter

Hyperparameters are the configuration settings for an algorithm. OLS has no hyperparameters but essentially every other algorithm does.

There are two ways to customize a hyperparameter: make a new learner function, or use create.Learner().

Let’s make a variant of random forest that fits more trees, which may increase our accuracy and can’t hurt it (outside of small random variation).

# Review the function argument defaults at the top.
SL.randomForest
## function (Y, X, newX, family, mtry = ifelse(family$family == 
##     "gaussian", max(floor(ncol(X)/3), 1), floor(sqrt(ncol(X)))), 
##     ntree = 1000, nodesize = ifelse(family$family == "gaussian", 
##         5, 1), maxnodes = NULL, importance = FALSE, ...) 
## {
##     .SL.require("randomForest")
##     if (family$family == "gaussian") {
##         fit.rf <- randomForest::randomForest(Y ~ ., data = X, 
##             ntree = ntree, xtest = newX, keep.forest = TRUE, 
##             mtry = mtry, nodesize = nodesize, maxnodes = maxnodes, 
##             importance = importance)
##         pred <- fit.rf$test$predicted
##         fit <- list(object = fit.rf)
##     }
##     if (family$family == "binomial") {
##         fit.rf <- randomForest::randomForest(y = as.factor(Y), 
##             x = X, ntree = ntree, xtest = newX, keep.forest = TRUE, 
##             mtry = mtry, nodesize = nodesize, maxnodes = maxnodes, 
##             importance = importance)
##         pred <- fit.rf$test$votes[, 2]
##         fit <- list(object = fit.rf)
##     }
##     out <- list(pred = pred, fit = fit)
##     class(out$fit) <- c("SL.randomForest")
##     return(out)
## }
## <bytecode: 0x7fde8a3c95f0>
## <environment: namespace:SuperLearner>
# Create a new function that changes just the ntree argument.
# (We could do this in a single line.)
# "..." means "all other arguments that were sent to the function"
SL.rf.better = function(...) {
  SL.randomForest(..., ntree = 3000)
}

set.seed(1)

# Fit the CV.SuperLearner.
# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 3,
                        SL.library = c("SL.mean", "SL.glmnet", "SL.rf.better", "SL.randomForest"))

# Review results.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", "SL.rf.better", "SL.randomForest")) 
## 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  3 
## 
##            Algorithm     Ave        se     Min     Max
##        Super Learner 0.15634 0.0177517 0.12509 0.20573
##          Discrete SL 0.16400 0.0189549 0.12602 0.22289
##          SL.mean_All 0.25140 0.0027616 0.24970 0.25450
##        SL.glmnet_All 0.15741 0.0186996 0.11518 0.22289
##     SL.rf.better_All 0.14433 0.0167944 0.12602 0.16387
##  SL.randomForest_All 0.14418 0.0168854 0.12920 0.16286

Looks like our new RF is not improving performance. This implies that the original 500 trees had already reached the performance plateau - a maximum accuracy that RF can achieve unless other settings are changed (e.g. max nodes).

For comparison we can do the same hyperparameter customization with create.Learner().

# Customize the defaults for randomForest.
learners = create.Learner("SL.randomForest", params = list(ntree = 3000))

# Look at the object.
learners
## $grid
## NULL
## 
## $names
## [1] "SL.randomForest_1"
## 
## $base_learner
## [1] "SL.randomForest"
## 
## $params
## $params$ntree
## [1] 3000
# List the functions that were created
learners$names
## [1] "SL.randomForest_1"
# Review the code that was automatically generated for the function.
# Notice that it's exactly the same as the function we made manually.
SL.randomForest_1
## function (...) 
## SL.randomForest(..., ntree = 3000)
set.seed(1)

# Fit the CV.SuperLearner.
# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 3,
                        SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))

# Review results.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest")) 
## 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  3 
## 
##              Algorithm     Ave        se     Min     Max
##          Super Learner 0.15634 0.0177517 0.12509 0.20573
##            Discrete SL 0.16400 0.0189549 0.12602 0.22289
##            SL.mean_All 0.25140 0.0027616 0.24970 0.25450
##          SL.glmnet_All 0.15741 0.0186996 0.11518 0.22289
##  SL.randomForest_1_All 0.14433 0.0167944 0.12602 0.16387
##    SL.randomForest_All 0.14418 0.0168854 0.12920 0.16286

We get exactly the same results between the two methods of creating a custom learner.

10 Test algorithm with multiple hyperparameter settings

The performance of an algorithm varies based on its hyperparamters, which again are its configuration settings. Some algorithms may not vary much, and others might have far better or worse performance for certain settings. Often we focus our attention on 1 or 2 hyperparameters for a given algorithm because they are the most important ones.

For randomForest there are two particularly important hyperparameters: mtry and maximum leaf nodes. Mtry is how many features are randomly chosen within each decision tree node - in other words, each time the tree considers making a split. Maximum leaf nodes controls how complex each tree can get.

Let’s try 3 different mtry options.

# sqrt(p) is the default value of mtry for classification.
floor(sqrt(ncol(X_train)))
## [1] 3
# Let's try 3 multiplies of this default: 0.5, 1, and 2.
mtry_seq = floor(sqrt(ncol(X_train)) * c(0.5, 1, 2))
mtry_seq
## [1] 1 3 7
learners = create.Learner("SL.randomForest", tune = list(mtry = mtry_seq))

# Review the resulting object
learners
## $grid
##   mtry
## 1    1
## 2    3
## 3    7
## 
## $names
## [1] "SL.randomForest_1" "SL.randomForest_2" "SL.randomForest_3"
## 
## $base_learner
## [1] "SL.randomForest"
## 
## $params
## list()
# Check code for the learners that were created.
SL.randomForest_1
## function (...) 
## SL.randomForest(..., mtry = 1)
SL.randomForest_2
## function (...) 
## SL.randomForest(..., mtry = 3)
SL.randomForest_3
## function (...) 
## SL.randomForest(..., mtry = 7)
set.seed(1)

# Fit the CV.SuperLearner.
# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 3,
                        SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))

# Review results.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest")) 
## 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  3 
## 
##              Algorithm     Ave        se     Min     Max
##          Super Learner 0.15743 0.0183102 0.12784 0.19743
##            Discrete SL 0.16643 0.0193187 0.12659 0.22568
##            SL.mean_All 0.25140 0.0027616 0.24970 0.25450
##          SL.glmnet_All 0.16587 0.0181550 0.13482 0.22568
##  SL.randomForest_1_All 0.14837 0.0166496 0.12216 0.16964
##  SL.randomForest_2_All 0.14417 0.0169750 0.12613 0.16212
##  SL.randomForest_3_All 0.14905 0.0186907 0.13598 0.16816
##    SL.randomForest_All 0.14536 0.0169050 0.12659 0.16248

We see here that mtry = 3 performed a little bit better than mtry = 1 or mtry = 7, although the difference is not significant. If we used more data and more cross-validation folds we might see more drastic differences. A higher mtry does better when a small percentage of variables are predictive of the outcome, because it gives each tree a better chance of finding a useful variable.

Note that SL.randomForest and SL.randomForest_2 have the same settings, and their performance is very similar - statistically a tie. It’s not exactly equivalent due to random variation in the two forests.

A key difference with SuperLearner over caret or other frameworks is that we are not trying to choose the single best hyperparameter or model. Instead, we usually want the best weighted average. So we are including all of the different settings in our SuperLearner, and we may choose a weighted average that includes the same model multiple times but with different settings. That can give us better performance than choosing only the single best settings for a given algorithm, which has some random noise in any case.

11 Multicore parallelization

SuperLearner makes it easy to use multiple CPU cores on your computer to speed up the calculations. We first need to setup R for multiple cores, then tell CV.SuperLearner to divide its computations across those cores.

There are two ways to use multiple cores in R: the “multicore” system and the “snow” system. Windows only supports the “snow” system, which is more difficult to use, whereas macOS and Linux can use either one.

First we show the “multicore” system version:

# Setup parallel computation - use all cores on our computer.
num_cores = RhpcBLASctl::get_num_cores()

# How many cores does this computer have?
num_cores
## [1] 4
# Use 2 of those cores for parallel SuperLearner.
# Replace "2" with "num_cores" (without quotes) to use all cores.
options(mc.cores = 2)

# Check how many parallel workers we are using (on macOS/Linux).
getOption("mc.cores")
## [1] 2
# We need to set a different type of seed that works across cores.
# Otherwise the other cores will go rogue and we won't get repeatable results.
# This version is for the "multicore" parallel system in R.
set.seed(1, "L'Ecuyer-CMRG")

# While this is running check CPU using in Activity Monitor / Task Manager.
system.time({
  cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 10,
                          parallel = "multicore",
                          SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))
})
## Loading required package: parallel
##    user  system elapsed 
##  25.078   0.825  26.452
# Review results.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 10, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"),  
##     parallel = "multicore") 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  10 
## 
##              Algorithm     Ave       se      Min     Max
##          Super Learner 0.12367 0.015122 0.076113 0.19118
##            Discrete SL 0.12537 0.015656 0.078565 0.19047
##            SL.mean_All 0.25147 0.002361 0.246420 0.25981
##          SL.glmnet_All 0.13433 0.016411 0.066764 0.21176
##  SL.randomForest_1_All 0.13491 0.015558 0.094331 0.19815
##  SL.randomForest_2_All 0.12243 0.014798 0.078565 0.18185
##  SL.randomForest_3_All 0.12499 0.016308 0.073813 0.19047
##    SL.randomForest_All 0.12130 0.014755 0.075437 0.17915

Here is the “snow” equivalent:

# Make a snow cluster
# Again, replace 2 with num_cores to use all available cores.
cluster = parallel::makeCluster(2)

# Check the cluster object.
cluster
## socket cluster with 2 nodes on host 'localhost'
# Load the SuperLearner package on all workers so they can find
# SuperLearner::All(), the default screening function which keeps all variables.
parallel::clusterEvalQ(cluster, library(SuperLearner))
## [[1]]
## [1] "SuperLearner" "nnls"         "stats"        "graphics"    
## [5] "grDevices"    "utils"        "datasets"     "methods"     
## [9] "base"        
## 
## [[2]]
## [1] "SuperLearner" "nnls"         "stats"        "graphics"    
## [5] "grDevices"    "utils"        "datasets"     "methods"     
## [9] "base"
# We need to explictly export our custom learner functions to the workers.
parallel::clusterExport(cluster, learners$names)

# We need to set a different type of seed that works across cores.
# This version is for SNOW parallelization.
# Otherwise the other cores will go rogue and we won't get repeatable results.
parallel::clusterSetRNGStream(cluster, 1)

# While this is running check CPU using in Activity Monitor / Task Manager.
system.time({
  cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 10,
                          parallel = cluster,
                          SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))
})
##    user  system elapsed 
##   0.008   0.001  29.243
# Review results.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 10, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"),  
##     parallel = cluster) 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  10 
## 
##              Algorithm     Ave        se      Min     Max
##          Super Learner 0.12288 0.0145636 0.050489 0.19285
##            Discrete SL 0.12352 0.0148400 0.050588 0.19147
##            SL.mean_All 0.25501 0.0025995 0.246420 0.26837
##          SL.glmnet_All 0.13701 0.0170611 0.041882 0.20458
##  SL.randomForest_1_All 0.13122 0.0150227 0.069965 0.18893
##  SL.randomForest_2_All 0.12244 0.0145517 0.050583 0.19147
##  SL.randomForest_3_All 0.12388 0.0159529 0.050863 0.20367
##    SL.randomForest_All 0.12113 0.0145683 0.050588 0.19449
# Stop the cluster workers now that we're done.
parallel::stopCluster(cluster)

If we want to use multiple cores for normal SuperLearner, not CV.SuperLearner (i.e. external cross-validation to estimate performance), we need to change the function name to mcSuperLearner (“multicore” version) or snowSuperLearner (“snow” version).

First the “multicore” version (won’t be parallel on Windows):

# Set multicore compatible seed.
set.seed(1, "L'Ecuyer-CMRG")

# Fit the SuperLearner.
sl = mcSuperLearner(Y = Y_train, X = X_train, family = binomial(),
                    SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))
sl
## 
## Call:  
## mcSuperLearner(Y = Y_train, X = X_train, family = binomial(), SL.library = c("SL.mean",  
##     "SL.glmnet", learners$names, "SL.randomForest")) 
## 
## 
##                            Risk      Coef
## SL.mean_All           0.2514678 0.0000000
## SL.glmnet_All         0.1303089 0.3045078
## SL.randomForest_1_All 0.1377585 0.0000000
## SL.randomForest_2_All 0.1236780 0.0000000
## SL.randomForest_3_All 0.1252757 0.0000000
## SL.randomForest_All   0.1227621 0.6954922
# We see the time is reduced over our initial single-core superlearner.
sl$times$everything
##    user  system elapsed 
##  30.233   1.096   3.066

Now the “snow” version, which should be parallel on all operating systems.

# Make a snow cluster
# Reminder: change "2" to "num_cores" (without quotes) to use all available cores.
cluster = parallel::makeCluster(2)

# Check the cluster object.
cluster
## socket cluster with 2 nodes on host 'localhost'
# Load the SuperLearner package on all workers so they can find
# SuperLearner::All(), the default screening function which keeps all variables.
parallel::clusterEvalQ(cluster, library(SuperLearner))
## [[1]]
## [1] "SuperLearner" "nnls"         "stats"        "graphics"    
## [5] "grDevices"    "utils"        "datasets"     "methods"     
## [9] "base"        
## 
## [[2]]
## [1] "SuperLearner" "nnls"         "stats"        "graphics"    
## [5] "grDevices"    "utils"        "datasets"     "methods"     
## [9] "base"
# We need to explictly export our custom learner functions to the workers.
parallel::clusterExport(cluster, learners$names)

# We need to set a different type of seed that works across cores.
# This version is for SNOW parallelization.
# Otherwise the other cores will go rogue and we won't get repeatable results.
parallel::clusterSetRNGStream(cluster, 1)

# Fit the SuperLearner.
sl = snowSuperLearner(Y = Y_train, X = X_train, family = binomial(),
                      cluster = cluster,
                      SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))
sl
## 
## Call:  
## snowSuperLearner(cluster = cluster, Y = Y_train, X = X_train, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest")) 
## 
## 
## 
##                            Risk      Coef
## SL.mean_All           0.2550123 0.0000000
## SL.glmnet_All         0.1354069 0.1654791
## SL.randomForest_1_All 0.1323482 0.0000000
## SL.randomForest_2_All 0.1210463 0.8345209
## SL.randomForest_3_All 0.1249136 0.0000000
## SL.randomForest_All   0.1227729 0.0000000
# We see the time is reduced over our initial single-core superlearner.
sl$times$everything
##    user  system elapsed 
##   0.198   0.028   4.851

SuperLearner also supports running across multiple computers at a time, called “multi-node” or “cluster” computing. We will skip that for now.

12 Weight distribution for SuperLearner

The weights or coefficients of the SuperLearner are stochastic - they will change as the data changes. So we don’t necessarily trust a given set of weights as being the “true” weights, but when we use CV.SuperLearner we at least have multiple samples from the distribution of the weights.

We can write a little function to extract the weights at each CV.SuperLearner iteration and summarize the distribution of those weights. This may be added to the SuperLearner package sometime in the future.

# Review meta-weights (coefficients) from a CV.SuperLearner object
review_weights = function(cv_sl) {
  meta_weights = coef(cv_sl)
  means = colMeans(meta_weights)
  sds = apply(meta_weights, MARGIN = 2,  FUN = sd)
  mins = apply(meta_weights, MARGIN = 2, FUN = min)
  maxs = apply(meta_weights, MARGIN = 2, FUN = max)
  # Combine the stats into a single matrix.
  sl_stats = cbind("mean(weight)" = means, "sd" = sds, "min" = mins, "max" = maxs)
  # Sort by decreasing mean weight.
  sl_stats[order(sl_stats[, 1], decreasing = T), ]
}

print(review_weights(cv_sl), digits = 3)
##                       mean(weight)    sd min   max
## SL.randomForest_All         0.4391 0.478   0 1.000
## SL.randomForest_2_All       0.3772 0.452   0 1.000
## SL.randomForest_3_All       0.1099 0.207   0 0.589
## SL.glmnet_All               0.0738 0.107   0 0.325
## SL.mean_All                 0.0000 0.000   0 0.000
## SL.randomForest_1_All       0.0000 0.000   0 0.000

Notice that in this case the ensemble never uses the mean, lasso, or the randomForest with mtry = 1. Adding multiple configurations of randomForest was helpful because mtry = 7 was used. However, based on the minimum column we can see that no algorithm was used every single time.

We recommend reviewing the weight distribution for any SuperLearner project to better understand which algorithms are chosen for the ensemble.

13 Feature selection (screening)

When datasets have many covariates our algorithms may benefit from first choosing a subset of available covariates, a step called feature selection. Then we pass only those variables to the modeling algorithm, and it may be less likely to overfit to variables that are not related to the outcome.

Let’s revisit listWrappers() and check out the bottom section.

listWrappers()
## All prediction algorithm wrappers in SuperLearner:
##  [1] "SL.bartMachine"      "SL.bayesglm"         "SL.biglasso"        
##  [4] "SL.caret"            "SL.caret.rpart"      "SL.cforest"         
##  [7] "SL.dbarts"           "SL.earth"            "SL.extraTrees"      
## [10] "SL.gam"              "SL.gbm"              "SL.glm"             
## [13] "SL.glm.interaction"  "SL.glmnet"           "SL.ipredbagg"       
## [16] "SL.kernelKnn"        "SL.knn"              "SL.ksvm"            
## [19] "SL.lda"              "SL.leekasso"         "SL.lm"              
## [22] "SL.loess"            "SL.logreg"           "SL.mean"            
## [25] "SL.nnet"             "SL.nnls"             "SL.polymars"        
## [28] "SL.qda"              "SL.randomForest"     "SL.ranger"          
## [31] "SL.ridge"            "SL.rpart"            "SL.rpartPrune"      
## [34] "SL.speedglm"         "SL.speedlm"          "SL.step"            
## [37] "SL.step.forward"     "SL.step.interaction" "SL.stepAIC"         
## [40] "SL.svm"              "SL.template"         "SL.xgboost"
## 
## All screening algorithm wrappers in SuperLearner:
## [1] "All"
## [1] "screen.SIS"            "screen.corP"           "screen.corRank"       
## [4] "screen.glmnet"         "screen.randomForest"   "screen.template"      
## [7] "screen.ttest"          "write.screen.template"
# Review code for corP, which is based on univariate correlation.
screen.corP
## function (Y, X, family, obsWeights, id, method = "pearson", minPvalue = 0.1, 
##     minscreen = 2, ...) 
## {
##     listp <- apply(X, 2, function(x, Y, method) {
##         ifelse(var(x) <= 0, 1, cor.test(x, y = Y, method = method)$p.value)
##     }, Y = Y, method = method)
##     whichVariable <- (listp <= minPvalue)
##     if (sum(whichVariable) < minscreen) {
##         warning("number of variables with p value less than minPvalue is less than minscreen")
##         whichVariable[rank(listp) <= minscreen] <- TRUE
##     }
##     return(whichVariable)
## }
## <environment: namespace:SuperLearner>
set.seed(1)

# Fit the SuperLearner.
# We need to use list() instead of c().
# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 3,
                        parallel = "multicore",
                        SL.library = list("SL.mean", "SL.glmnet", c("SL.glmnet", "screen.corP")))
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = list("SL.mean", "SL.glmnet", c("SL.glmnet", "screen.corP")),  
##     parallel = "multicore") 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  3 
## 
##              Algorithm     Ave        se     Min     Max
##          Super Learner 0.13639 0.0167625 0.12591 0.14976
##            Discrete SL 0.13636 0.0167725 0.12583 0.14976
##            SL.mean_All 0.25273 0.0030641 0.25160 0.25450
##          SL.glmnet_All 0.13512 0.0162308 0.12583 0.14602
##  SL.glmnet_screen.corP 0.13661 0.0166732 0.12658 0.14976

We see a small performance boost by first screening by univarate correlation with our outcome, and only keeping variables with a p-value less than 0.10. Try using some of the other screening algorithms as they may do even better for a particular dataset.

14 Optimize for AUC

For binary prediction we are typically trying to maximize AUC, which can be the best performance metric when our outcome variable has some imbalance. In other words, we don’t have exactly 50% 1s and 50% 0s in our outcome. Our SuperLearner is not targeting AUC by default, but it can if we tell it to by specifying our method.

set.seed(1)

# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(), V = 3,
                        method = "method.AUC",
                        SL.library = list("SL.mean", "SL.glmnet", c("SL.glmnet", "screen.corP")))
## Loading required package: cvAUC
## Loading required package: ROCR
## Loading required package: gplots
## 
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
## 
##     lowess
## Loading required package: data.table
## 
## cvAUC version: 1.1.0
## Notice to cvAUC users: Major speed improvements in version 1.1.0
## 
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = list("SL.mean", "SL.glmnet", c("SL.glmnet", "screen.corP")),  
##     method = "method.AUC") 
## 
## Risk is based on: Area under ROC curve (AUC)
## 
## All risk estimates are based on V =  3 
## 
##              Algorithm     Ave se     Min     Max
##          Super Learner 0.89558 NA 0.88320 0.91186
##            Discrete SL 0.89675 NA 0.87520 0.91506
##            SL.mean_All 0.50000 NA 0.50000 0.50000
##          SL.glmnet_All 0.89764 NA 0.88667 0.91506
##  SL.glmnet_screen.corP 0.89569 NA 0.87520 0.91186

This conveniently shows us the AUC for each algorithm without us having to calculate it manually. But we aren’t getting SEs sadly.

Another important optimizer to consider is negative log likelihood, which is intended for binary outcomes and will often work better than NNLS (the default). This is specified by method = “NNloglik”.

15 XGBoost hyperparameter exploration

XGBoost is a version of GBM that is even faster and has some extra settings. GBM’s adaptivity is determined by its configuration, so we want to thoroughly test a wide range of configurations for any given problem. Let’s do 36 now. This will take a good amount of time (~7 minutes on my computer) so we need to at least use multiple cores, if not multiple computers.

# 3 * 4 * 3 = 36 different configurations.
tune = list(ntrees = c(100, 200, 500),
            max_depth = 1:4,
            shrinkage = c(0.001, 0.01, 0.1))

# Set detailed names = T so we can see the configuration for each function.
# Also shorten the name prefix.
learners = create.Learner("SL.xgboost", tune = tune, detailed_names = T, name_prefix = "xgb")

# 36 configurations - not too shabby.
length(learners$names)
## [1] 36
learners$names
##  [1] "xgb_100_1_0.001" "xgb_200_1_0.001" "xgb_500_1_0.001"
##  [4] "xgb_100_2_0.001" "xgb_200_2_0.001" "xgb_500_2_0.001"
##  [7] "xgb_100_3_0.001" "xgb_200_3_0.001" "xgb_500_3_0.001"
## [10] "xgb_100_4_0.001" "xgb_200_4_0.001" "xgb_500_4_0.001"
## [13] "xgb_100_1_0.01"  "xgb_200_1_0.01"  "xgb_500_1_0.01" 
## [16] "xgb_100_2_0.01"  "xgb_200_2_0.01"  "xgb_500_2_0.01" 
## [19] "xgb_100_3_0.01"  "xgb_200_3_0.01"  "xgb_500_3_0.01" 
## [22] "xgb_100_4_0.01"  "xgb_200_4_0.01"  "xgb_500_4_0.01" 
## [25] "xgb_100_1_0.1"   "xgb_200_1_0.1"   "xgb_500_1_0.1"  
## [28] "xgb_100_2_0.1"   "xgb_200_2_0.1"   "xgb_500_2_0.1"  
## [31] "xgb_100_3_0.1"   "xgb_200_3_0.1"   "xgb_500_3_0.1"  
## [34] "xgb_100_4_0.1"   "xgb_200_4_0.1"   "xgb_500_4_0.1"
# Confirm we have multiple cores configured. This should be > 1.
getOption("mc.cores")
## [1] 2
# Remember to set multicore-compatible seed.
set.seed(1, "L'Ecuyer-CMRG")

# Fit the CV.SuperLearner. This will take 1-2 minutes.
# We use V = 3 to save computation time; for a real analysis use V = 10 or 20.
system.time({
  cv_sl = CV.SuperLearner(Y = Y_train, X = X_train, family = binomial(),
                          V = 3, parallel = "multicore",
                          SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"))
})
##    user  system elapsed 
##  19.613   0.432  30.653
# Review results.
summary(cv_sl)
## 
## Call:  
## CV.SuperLearner(Y = Y_train, X = X_train, V = 3, family = binomial(),  
##     SL.library = c("SL.mean", "SL.glmnet", learners$names, "SL.randomForest"),  
##     parallel = "multicore") 
## 
## Risk is based on: Mean Squared Error
## 
## All risk estimates are based on V =  3 
## 
##            Algorithm     Ave        se     Min     Max
##        Super Learner 0.12519 0.0147340 0.12367 0.12773
##          Discrete SL 0.12289 0.0143333 0.11559 0.12745
##          SL.mean_All 0.25273 0.0030641 0.25160 0.25450
##        SL.glmnet_All 0.13671 0.0170438 0.12583 0.15021
##  xgb_100_1_0.001_All 0.23808 0.0017966 0.23717 0.23881
##  xgb_200_1_0.001_All 0.22814 0.0032803 0.22688 0.22949
##  xgb_500_1_0.001_All 0.20557 0.0059835 0.20278 0.20747
##  xgb_100_2_0.001_All 0.23808 0.0017966 0.23717 0.23881
##  xgb_200_2_0.001_All 0.22814 0.0032803 0.22688 0.22949
##  xgb_500_2_0.001_All 0.20557 0.0059835 0.20278 0.20747
##  xgb_100_3_0.001_All 0.23808 0.0017966 0.23717 0.23881
##  xgb_200_3_0.001_All 0.22814 0.0032803 0.22688 0.22949
##  xgb_500_3_0.001_All 0.20557 0.0059835 0.20278 0.20747
##  xgb_100_4_0.001_All 0.23808 0.0017966 0.23717 0.23881
##  xgb_200_4_0.001_All 0.22814 0.0032803 0.22688 0.22949
##  xgb_500_4_0.001_All 0.20557 0.0059835 0.20278 0.20747
##   xgb_100_1_0.01_All 0.18151 0.0089164 0.17312 0.18686
##   xgb_200_1_0.01_All 0.16256 0.0121780 0.15084 0.17339
##   xgb_500_1_0.01_All 0.16116 0.0126982 0.14789 0.17352
##   xgb_100_2_0.01_All 0.18151 0.0089164 0.17312 0.18686
##   xgb_200_2_0.01_All 0.16256 0.0121780 0.15084 0.17339
##   xgb_500_2_0.01_All 0.16116 0.0126982 0.14789 0.17352
##   xgb_100_3_0.01_All 0.18151 0.0089164 0.17312 0.18686
##   xgb_200_3_0.01_All 0.16256 0.0121780 0.15084 0.17339
##   xgb_500_3_0.01_All 0.16116 0.0126982 0.14789 0.17352
##   xgb_100_4_0.01_All 0.18151 0.0089164 0.17312 0.18686
##   xgb_200_4_0.01_All 0.16256 0.0121780 0.15084 0.17339
##   xgb_500_4_0.01_All 0.16116 0.0126982 0.14789 0.17352
##    xgb_100_1_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_200_1_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_500_1_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_100_2_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_200_2_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_500_2_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_100_3_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_200_3_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_500_3_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_100_4_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_200_4_0.1_All 0.16119 0.0127952 0.15240 0.17263
##    xgb_500_4_0.1_All 0.16119 0.0127952 0.15240 0.17263
##  SL.randomForest_All 0.12289 0.0143333 0.11559 0.12745
review_weights(cv_sl)
##                     mean(weight)        sd       min       max
## SL.randomForest_All    0.7256498 0.1754881 0.5257817 0.8544914
## SL.glmnet_All          0.2743502 0.1754881 0.1455086 0.4742183
## SL.mean_All            0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_1_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_1_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_1_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_2_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_2_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_2_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_3_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_3_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_3_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_4_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_4_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_4_0.001_All    0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_1_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_1_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_1_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_2_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_2_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_2_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_3_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_3_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_3_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_4_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_4_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_4_0.01_All     0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_1_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_1_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_1_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_2_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_2_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_2_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_3_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_3_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_3_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_100_4_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_200_4_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000
## xgb_500_4_0.1_All      0.0000000 0.0000000 0.0000000 0.0000000

We can see how stochastic the weights are for each individual execution of SuperLearner.

Finally, plot the performance for the different settings.

plot(cv_sl) + theme_bw()

16 Troubleshooting

  • If you get an error about predict for xgb.Booster, you probably need to install the latest version of XGBoost from github.

17 References

LeDell, E., Petersen, M., & van der Laan, M. (2015). Computationally efficient confidence intervals for cross-validated area under the ROC curve estimates. Electronic journal of statistics, 9(1), 1583.

Polley EC, van der Laan MJ (2010) Super Learner in Prediction. U.C. Berkeley Division of Biostatistics Working Paper Series. Paper 226. http://biostats.bepress.com/ucbbiostat/paper266/

van der Laan, M. J., Polley, E. C. and Hubbard, A. E. (2007) Super Learner. Statistical Applications of Genetics and Molecular Biology, 6, article 25. http://www.degruyter.com/view/j/sagmb.2007.6.issue-1/sagmb.2007.6.1.1309/sagmb.2007.6.1.1309.xml

van der Laan, M. J., & Rose, S. (2011). Targeted learning: causal inference for observational and experimental data. Springer Science & Business Media.