Introduction

The motivation for this package is to provide functions which help with the development and tuning of machine learning models in biomedical data where the sample size is frequently limited, but the number of predictors may be significantly larger (P >> n). While most machine learning pipelines involve splitting data into training and testing cohorts, typically 2/3 and 1/3 respectively, medical datasets may be too small for this, and so determination of accuracy in the left-out test set suffers because the test set is small. Nested cross-validation (CV) provides a way to get round this, by maximising use of the whole dataset for testing overall accuracy, while maintaining the split between training and testing.

In addition typical biomedical datasets often have many 10,000s of possible predictors, so filtering of predictors is commonly needed. However, it has been demonstrated that filtering on the whole dataset creates a bias when determining accuracy of models (Vabalas et al, 2019). Feature selection of predictors should be considered an integral part of a model, with feature selection performed only on training data. Then the selected features and accompanying model can be tested on hold-out test data without bias. Thus, it is recommended that any filtering of predictors is performed within the CV loops, to prevent test data information leakage.

This package enables nested cross-validation (CV) to be performed using the commonly used glmnet package, which fits elastic net regression models, and the caret package, which is a general framework for fitting a large number of machine learning models. In addition, nestedcv adds functionality to enable cross-validation of the elastic net alpha parameter when fitting glmnet models.

nestedcv partitions the dataset into outer and inner folds (default 10 x 10 folds). The inner fold CV, (default is 10-fold), is used to tune optimal hyperparameters for models. Then the model is fitted on the whole inner fold and tested on the left-out data from the outer fold. This is repeated across all outer folds (default 10 outer folds), and the unseen test predictions from the outer folds are compared against the true results for the outer test folds and the results concatenated, to give measures of accuracy (e.g. AUC and accuracy for classification, or RMSE for regression) across the whole dataset.

A final round of CV is performed on the whole dataset to determine hyperparameters to fit the final model to the whole data, which can be used for prediction with external data.

Variable selection

While some models such as glmnet allow for sparsity and have variable selection built-in, many models fail to fit when given massive numbers of predictors, or perform poorly due to overfitting without variable selection. In addition, in medicine one of the goals of predictive modelling is commonly the development of diagnostic or biomarker tests, for which reducing the number of predictors is typically a practical necessity.

Several filter functions (t-test, Wilcoxon test, anova, Pearson/Spearman correlation, random forest variable importance, and ReliefF from the CORElearn package) for feature selection are provided, and can be embedded within the outer loop of the nested CV.

Installation

install.packages("nestedcv")
library(nestedcv)

Examples

Importance of nested CV

The following simulated example demonstrates the bias intrinsic to datasets where P >> n when applying filtering of predictors to the whole dataset rather than to training folds.

## Example binary classification problem with P >> n
x <- matrix(rnorm(150 * 2e+04), 150, 2e+04)  # predictors
y <- factor(rbinom(150, 1, 0.5))  # binary response

## Partition data into 2/3 training set, 1/3 test set
trainSet <- caret::createDataPartition(y, p = 0.66, list = FALSE)

## t-test filter using whole test set
filt <- ttest_filter(y, x, nfilter = 100)
filx <- x[, filt]

## Train glmnet on training set only using filtered predictor matrix
library(glmnet)
## Loading required package: Matrix
## Loaded glmnet 4.1-8
fit <- cv.glmnet(filx[trainSet, ], y[trainSet], family = "binomial")

## Predict response on test set
predy <- predict(fit, newx = filx[-trainSet, ], s = "lambda.min", type = "class")
predy <- as.vector(predy)
predyp <- predict(fit, newx = filx[-trainSet, ], s = "lambda.min", type = "response")
predyp <- as.vector(predyp)
output <- data.frame(testy = y[-trainSet], predy = predy, predyp = predyp)

## Results on test set
## shows bias since univariate filtering was applied to whole dataset
predSummary(output)
##          Reference
## Predicted  0  1
##         0 23  6
##         1  2 19
## 
##               AUC            Accuracy   Balanced accuracy   
##            0.9376              0.8400              0.8400

## Nested CV
fit2 <- nestcv.glmnet(y, x, family = "binomial", alphaSet = 7:10 / 10,
                      filterFUN = ttest_filter,
                      filter_options = list(nfilter = 100))
fit2
## Nested cross-validation with glmnet
## Filter:  ttest_filter 
## 
## Final parameters:
##   lambda     alpha  
## 0.001811  0.700000  
## 
## Final coefficients:
## (Intercept)       V9391       V3001      V18403       V6902       V2414 
##    0.006943    0.717822    0.688902    0.600608   -0.580541   -0.577643 
##      V19254       V2496       V7328        V940       V2129      V19519 
##   -0.556131    0.515752   -0.496468   -0.492575    0.465153   -0.455711 
##       V8934       V3629      V14459      V15303       V3341      V17904 
##   -0.452834   -0.433881    0.431087   -0.429622   -0.400290    0.399325 
##       V8329      V19720      V18227       V1993       V3179      V13348 
##    0.390014    0.386027   -0.382482    0.381912    0.380943    0.370534 
##       V1551      V16842      V19968       V5741       V4673       V3396 
##   -0.367768    0.350342   -0.344486   -0.340314    0.334453   -0.329887 
##      V12248      V18045       V9648      V17888      V11635      V11026 
##   -0.321231    0.316122    0.315314   -0.312241   -0.311555   -0.307085 
##        V119      V15391       V6049       V6879      V15399       V6124 
##   -0.305138   -0.300891    0.299357    0.293590    0.290350   -0.281363 
##      V16398       V9475       V3786      V13874      V18063      V10307 
##   -0.274936    0.271674    0.270676    0.266855   -0.265814   -0.265357 
##       V8529       V9059       V8832        V293        V723       V9900 
##    0.264228   -0.263307    0.243634   -0.231052   -0.229039   -0.227427 
##       V6117      V13481       V5777       V2775      V16434      V19517 
##    0.222352   -0.219635    0.203188    0.200079    0.198423    0.193456 
##       V9966      V16377      V11369      V13475       V6887       V6480 
##   -0.181949   -0.177703    0.176870   -0.167257   -0.161931    0.155357 
##       V9096       V2995       V2450       V3885        V219       V1191 
##    0.153667    0.153649    0.151666   -0.145553   -0.133420   -0.099962 
##       V2481       V5960      V19856       V4928       V3854      V11236 
##    0.098911   -0.094332    0.074366   -0.072026   -0.069486   -0.063382 
##       V8485       V8000       V4916      V16213       V1321       V9105 
##   -0.057951    0.056875   -0.040130    0.033108   -0.031514    0.012946 
##       V9586       V9067 
##   -0.012891    0.002340 
## 
## Result:
##          Reference
## Predicted  0  1
##         0 33 48
##         1 43 26
## 
##               AUC            Accuracy   Balanced accuracy   
##            0.3318              0.3933              0.3928

testroc <- pROC::roc(output$testy, output$predyp, direction = "<", quiet = TRUE)
inroc <- innercv_roc(fit2)
plot(fit2$roc)
lines(inroc, col = 'blue')
lines(testroc, col = 'red')
legend('bottomright', legend = c("Nested CV", "Left-out inner CV folds", 
                                 "Test partition, non-nested filtering"), 
       col = c("black", "blue", "red"), lty = 1, lwd = 2, bty = "n")

In this example the dataset is pure noise. Filtering of predictors on the whole dataset is a source of leakage of information about the test set, leading to substantially overoptimistic performance on the test set as measured by ROC AUC.

Figures A & B below show two commonly used, but biased methods in which cross-validation is used to fit models, but the result is a biased estimate of model performance. In scheme A, there is no hold-out test set at all, so there are two sources of bias/ data leakage: first, the filtering on the whole dataset, and second, the use of left-out CV folds for measuring performance. Left-out CV folds are known to lead to biased estimates of performance as the tuning parameters are ‘learnt’ from optimising the result on the left-out CV fold.

In scheme B, the CV is used to tune parameters and a hold-out set is used to measure performance, but information leakage occurs when filtering is applied to the whole dataset. Unfortunately this is commonly observed in many studies which apply differential expression analysis on the whole dataset to select predictors which are then passed to machine learning algorithms.