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 21  3
##         1  3 23
## 
##               AUC            Accuracy   Balanced accuracy   
##            0.9327              0.8800              0.8798

## 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.000134  0.700000  
## 
## Final coefficients:
## (Intercept)      V19583      V10235      V18767      V15040       V2810 
##     0.54417    -1.12955     1.07773     1.04470    -0.93285    -0.91779 
##      V15563      V16357       V8713      V17561       V7235       V6842 
##    -0.91047    -0.87128     0.83231     0.80264    -0.80175    -0.78071 
##       V2583       V2389       V6657      V18942      V17139      V13049 
##    -0.75805    -0.72744     0.71658     0.70005    -0.69589     0.67341 
##      V17506       V9349      V14745      V10960      V15981      V11725 
##     0.66658    -0.66383     0.66304    -0.66170    -0.66160     0.63766 
##      V14211       V9122       V8130      V15046       V8766      V12289 
##    -0.63109    -0.61695    -0.58749     0.55648    -0.55578    -0.54262 
##       V7175      V13311      V18904        V159      V18451       V8567 
##    -0.53899    -0.53711    -0.52282    -0.50498     0.50383    -0.50110 
##      V11255      V12980      V17085       V6872      V11489      V19010 
##     0.48472    -0.47895     0.44595     0.44090    -0.38280    -0.37894 
##      V17213      V12162      V12199       V2953       V8288       V9036 
##    -0.37002     0.34370    -0.33035     0.32582    -0.31367     0.30640 
##      V11937      V19259      V11406      V16629      V16858       V9860 
##     0.29887    -0.29701    -0.27376    -0.26593    -0.26362    -0.25490 
##       V2823       V8726      V11667      V13770       V5851       V1101 
##    -0.24259     0.23690    -0.22467    -0.21823     0.21608     0.21401 
##       V8236       V1524        V133      V14987       V6530       V2854 
##    -0.19900     0.18288     0.17236     0.16616    -0.16322    -0.14418 
##      V17283       V8217       V3435      V15048       V5348      V14800 
##    -0.11862    -0.11170     0.10529     0.10172     0.09143     0.08681 
##       V5354      V19564       V7438       V9789      V13970       V9505 
##    -0.08265    -0.07764     0.07651    -0.07013    -0.06825     0.05871 
##      V15315      V17455      V17145 
##    -0.05273     0.02718    -0.02508 
## 
## Result:
##          Reference
## Predicted  0  1
##         0 31 46
##         1 42 31
## 
##               AUC            Accuracy   Balanced accuracy   
##            0.4095              0.4133              0.4136

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.