knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "images/README-",
  fig.width = 4,
  fig.height = 3,
  echo = TRUE
)

ck37r

Build Status Build Status: appveyor codecov CRAN_Status_Badge

My R toolkit for organizing analysis projects, cleaning data for machine learning, parallelizing code for multiple cores or in a SLURM cluster, and extended functionality for SuperLearner and TMLE. Some of the SuperLearner functions may eventually be migrated into the SuperLearner package.

Installation

Install the latest release from CRAN:

install.packages("ck37r") 

Install the development version from github (recommended):

# install.packages("remotes")
remotes::install_github("ck37/ck37r")
library(ck37r)

Functions

Examples

Impute missing values

# Load a test dataset.
# TODO: need to switch to a different dataset.
data(PimaIndiansDiabetes2, package = "mlbench")

# Check for missing values.
colSums(is.na(PimaIndiansDiabetes2))

# Impute missing data and add missingness indicators.
# Don't impute the outcome though.
result = impute_missing_values(PimaIndiansDiabetes2, skip_vars = "diabetes")

# Confirm we have no missing data.
colSums(is.na(result$data))

Impute with GLRM

We are using default hyperparameters here, but it would be best to optimize the hyperparameters.

#############
# Generalized low-rank model imputation via h2o.
result2 = impute_missing_values(PimaIndiansDiabetes2, type = "glrm", skip_vars = "diabetes")

# Confirm we have no missing data.
colSums(is.na(result2$data))

Load packages

This loads a vector of packages, automatically installing any packages that aren't already installed.

# Load these 4 packages and install them if necessary.
load_packages(c("MASS", "SuperLearner", "tmle", "doParallel"), auto_install = TRUE)

Random Forest: count terminal nodes

We estimate one standard Random Forest first and examine how many terminal nodes are in each decision tree. We take the maximum of that as the most data-adaptive Random Forest in terms of decision tree size, then compare to Random Forests in which they are restricted to have smaller decision trees. This allows the SuperLearner to explore under vs. over-fitting for a Random Forest. See Segal (2004) and Segal & Xiao (2011) for details on overfitting in Random Forests.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
(sl = SuperLearner(Boston$medv, subset(Boston, select = -medv), family = gaussian(),
                  cvControl = list(V = 3L),
                  SL.library = c("SL.mean", "SL.glm", "SL.randomForest")))

summary(rf_count_terminal_nodes(sl$fitLibrary$SL.randomForest_All$object))

(max_terminal_nodes = max(rf_count_terminal_nodes(sl$fitLibrary$SL.randomForest_All$object)))

# Now run create.Learner() based on that maximum.

# It is often handy to convert to log scale of a hyperparameter before testing a ~linear grid.
# NOTE: -0.7 ~ log(0.5) which is the multiplier that yields sqrt(max)
(maxnode_seq = unique(round(exp(log(max_terminal_nodes) * exp(c(-0.6, -0.35, -0.15, 0))))))

rf = create.Learner("SL.randomForest", detailed_names = TRUE,
                    name_prefix = "rf",
                    params = list(ntree = 100L), # fewer trees for testing speed only.
                    tune = list(maxnodes = maxnode_seq))

# We see that an RF with simpler decision trees performs better than the default.
(sl = SuperLearner(Boston$medv, subset(Boston, select = -medv), family = gaussian(),
                  cvControl = list(V = 3L),
                  SL.library = c("SL.mean", "SL.glm", rf$names)))

Parallel TMLE

library(ck37r)
library(tmle)

# Use multiple cores as available.
ck37r::setup_parallel_tmle()

# Basic SL library.
sl_lib = c("SL.mean", "SL.rpart", "SL.glmnet")

# Set a parallel-compatible seed so cross-validation folds are deterministic.
set.seed(1, "L'Ecuyer-CMRG")
# Just an example -- we haven't defined A or W in this code.
result = run_tmle(Y = Y, A = A, W = W, family = "binomial",
                  g.SL.library = sl_lib, Q.SL.library = sl_lib)

SuperLearner AUC Table

This will return an AUC table for all learners. It does not include Discrete SL or SuperLearner as those require CV.SuperLearner.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
y = as.numeric(Boston$medv > 23)
sl = SuperLearner(Y = y,
                  X = subset(Boston, select = -medv),
                  family = binomial(),
                  cvControl = list(V = 2L, stratifyCV = TRUE),
                  SL.library = c("SL.mean", "SL.lm", "SL.glm"))

auc_table(sl, y = y)

SuperLearner plot of risk estimates

This is similar to CV.SuperLearner's plot except SuperLearner cannot estimate risk for the Discrete SL and SuperLearner, so those must be omitted here.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
(sl = SuperLearner(Boston$medv, subset(Boston, select = -medv),
                  family = gaussian(),
                  cvControl = list(V = 2),
                  SL.library = c("SL.mean", "SL.lm")))

plot(sl, y = Boston$medv)

SuperLearner ROC plot

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

y = as.numeric(Boston$medv > 23)
set.seed(1)
(sl = SuperLearner(Y = y,
                   X = subset(Boston, select = -medv),
                   family = binomial(),
                   cvControl = list(V = 2L, stratifyCV = TRUE),
                   SL.library = c("SL.mean", "SL.lm", "SL.glm")))

plot_roc(sl, y = y)

SuperLearner PR-AUC table

Reports on the precision-recall AUC for each learner, and includes the estimated standard error and 95% confidence interval.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

y = as.numeric(Boston$medv > 23)
set.seed(1)
sl = SuperLearner(Y = y,
                  X = subset(Boston, select = -medv),
                  family = binomial(),
                  cvControl = list(V = 2L, stratifyCV = TRUE),
                  SL.library = c("SL.mean", "SL.lm", "SL.glm"))

prauc_table(sl, y = y)

CV.SuperLearner AUC

This will return the AUC inference for the CV.SuperLearner.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
cvsl = CV.SuperLearner(Y = as.numeric(Boston$medv > 23),
                       X = subset(Boston, select = -medv),
                       family = binomial(),
                       cvControl = list(V = 2L, stratifyCV = TRUE),
                       SL.library = c("SL.mean", "SL.lm", "SL.glm"))
cvsl_auc(cvsl)

CV.SuperLearner AUC table

This will return an AUC table for all learners, plus DiscreteSL and the SuperLearner.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
cvsl = CV.SuperLearner(Y = as.numeric(Boston$medv > 23),
                       X = subset(Boston, select = -medv),
                       family = binomial(),
                       cvControl = list(V = 2, stratifyCV = TRUE),
                       SL.library = c("SL.mean", "SL.lm", "SL.glm"))
auc_table(cvsl)

CV.SuperLearner plot ROC

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
cvsl = CV.SuperLearner(Y = as.numeric(Boston$medv > 23),
                       X = subset(Boston, select = -medv),
                       family = binomial(),
                       cvControl = list(V = 2L, stratifyCV = TRUE),
                       SL.library = c("SL.mean", "SL.lm", "SL.glm"))
plot_roc(cvsl)

CV.SuperLearner weight table

Returns summary statistics (mean, sd, min, max) on the distribution of the weights assigned to each learner across SuperLearner ensembles. This makes it easier to understand the stochastic nature of the SL learner weights and to see how often certain learners are used.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
cvsl = CV.SuperLearner(Y = as.numeric(Boston$medv > 23),
                       X = subset(Boston, select = -medv),
                       family = binomial(),
                       cvControl = list(V = 2L, stratifyCV = TRUE),
                       SL.library = c("SL.mean", "SL.lm", "SL.glm"))
cvsl_weights(cvsl)

CV.SuperLearner PR-AUC table

Reports on the precision-recall AUC for each learner, as well as the SuperLearner and Discrete Superlearner. Includes the estimated standard error and 95% confidence interval.

library(SuperLearner)
library(ck37r)

data(Boston, package = "MASS")

set.seed(1)
cvsl = CV.SuperLearner(Y = as.numeric(Boston$medv > 23),
                       X = subset(Boston, select = -medv),
                       family = binomial(),
                       cvControl = list(V = 2L, stratifyCV = TRUE),
                       SL.library = c("SL.mean", "SL.lm", "SL.glm"))
prauc_table(cvsl)

More examples to be added.

Acknowledgments

The ROC plot is inspired by similar base plot functionality created by Alan Hubbard.

References

Breiman, L. (2001). Random forests. Machine learning, 45(1), 5-32.

Dudoit, S., & van der Laan, M. J. (2005). Asymptotics of cross-validated risk estimation in estimator selection and performance assessment. Statistical Methodology, 2(2), 131-154.

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/

Segal, M. R. (2004). Machine learning benchmarks and random forest regression.

Segal, M., & Xiao, Y. (2011). Multivariate random forests. Wiley Interdisciplinary Reviews: Data Mining and Knowledge Discovery, 1(1), 80-87.

Sing, T., Sander, O., Beerenwinkel, N., & Lengauer, T. (2005). ROCR: visualizing classifier performance in R. Bioinformatics, 21(20), 3940-3941.

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.

van der Laan, M. J., & Rubin, D. (2006). Targeted Maximum Likelihood Learning. The International Journal of Biostatistics, 2(1), 1-38.



ck37/ck37r documentation built on April 29, 2023, 11:42 p.m.