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 20  4
##         1  3 23
## 
##               AUC            Accuracy   Balanced accuracy   
##            0.8841              0.8600              0.8607

## 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.0002694  0.7000000  
## 
## Final coefficients:
## (Intercept)      V16271       V4008       V7265       V1282       V6898 
##    0.432886   -1.107702   -1.017187   -0.895709    0.828289   -0.778280 
##      V12202      V11708      V11732      V12303      V10868      V11534 
##   -0.749061   -0.733650    0.723472    0.681886    0.670335    0.662275 
##      V10832      V17229       V1191      V15019      V10429       V2104 
##   -0.652839    0.651490    0.643632   -0.636516   -0.627248   -0.615734 
##      V19805       V9586       V1873      V17548      V18371       V7807 
##    0.588317   -0.571592   -0.561034    0.556873    0.549384    0.533387 
##       V5532       V7174      V15987      V13390       V4615       V5910 
##    0.523931    0.518838   -0.504717    0.466852   -0.462870   -0.455245 
##      V19045       V4838       V5502       V2301      V19878       V3771 
##    0.453023   -0.446510   -0.444657    0.433682    0.411563    0.408643 
##       V2677       V4281      V14871      V11731       V1571       V7699 
##   -0.388678   -0.383827    0.373248   -0.367704    0.367295   -0.366033 
##      V17034      V11970       V1965        V386       V7670       V4570 
##    0.358280   -0.349255    0.336908   -0.325898    0.323888   -0.322451 
##      V12818       V3380       V2205      V17995      V13005      V15446 
##    0.310344   -0.303745    0.289500    0.269014   -0.264709   -0.258427 
##       V4185       V6970      V11833      V15379      V15335      V14496 
##   -0.251182    0.249565   -0.248376   -0.240478    0.239906   -0.228712 
##       V4630       V5089      V13200       V4341       V4634       V8918 
##   -0.227385   -0.215477   -0.206303    0.201725   -0.191150   -0.178250 
##       V1416      V13607      V16964       V7657       V7226       V6563 
##    0.151740   -0.148336   -0.145606    0.144769    0.144612   -0.120399 
##      V15472       V5481      V16448       V2408      V10194        V598 
##    0.119699   -0.116685   -0.113242   -0.072799   -0.072332    0.067833 
##      V14294       V8887       V2079      V10011       V2207      V12397 
##    0.059412   -0.054051    0.029917   -0.022521   -0.021446    0.002501 
## 
## Result:
##          Reference
## Predicted  0  1
##         0 27 33
##         1 43 47
## 
##               AUC            Accuracy   Balanced accuracy   
##            0.4489              0.4933              0.4866

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.