Vignette of the oosse package

Introduction

This vignette demonstrates the use of the oosse package for estimating for estimating out-of-sample R² and its standard error through resampling algorithms, described in “Out-of-sample R²: estimation and inference” by Hawinkel et al. 2023.

Installation instructions

install.packages("oosse")
library(oosse)

Illustrative examples

The R2oosse function works with any pair of fitting and prediction functions. Here we illustrate a number of them, but any prediction function implemented in R can be used. The built-in dataset Brassica is used, which contains rlog-transformed gene expression measurements for the 1,000 most expressed genes in the Expr slot, as well as 5 outcome phenotypes in the Pheno slot.

data(Brassica)

Linear model

The fitting model must accept at least an outcome vector y and a regressor matrix x:

fitFunLM = function(y, x){lm.fit(y = y, x = cbind(1, x))}

The predictive model must accept arguments mod (the fitted model) and x, the regressor matrix for a new set of observations.

predFunLM = function(mod, x) {cbind(1,x) %*% mod$coef}

Now that these functions have been defined, we apply the prediction model for leaf_8_width using the first 10 genes. Multithreading is used automatically using the BiocParallel package. Change the following setup depending on your system.

nCores = 2 # For CRAN build max 2
library(BiocParallel)
if(.Platform$OS.type == "unix"){
    #On unix-based systems, use MulticoreParam
    register(MulticoreParam(nCores))
} else {
    #On windows, use makeCluster
    library(doParallel)
    Clus = makeCluster(nCores)
    registerDoParallel(Clus)
    register(DoparParam(), default = TRUE)
}

Now estimate out-of-sample R2, also a rough estimate of the computation time is given. Remember to provide the cluster for multithreading.

R2lm = R2oosse(y = Brassica$Pheno$Leaf_8_width, x = Brassica$Expr[, 1:5], 
               fitFun = fitFunLM, predFun = predFunLM)
## Fitting and evaluating the model once took 0 seconds.
## You requested 200 repeats of 10-fold cross-validation with 2 cores, which is expected to last for roughly
## 10.25 seconds

Estimates and standard error of the different components are now available.

#R2
R2lm$R2
##        R2      R2SE 
## 0.4821389 0.1176087
#MSE
R2lm$MSE
##       MSE     MSESE 
## 2.9617958 0.4799818
#MST
R2lm$MST
##      MST    MSTSE 
## 5.719286 1.035600

Also confidence intervals can be constructed:

# R2
buildConfInt(R2lm)
##      2.5%     97.5% 
## 0.2516301 0.7126477
#MSE, 90% confidence interval
buildConfInt(R2lm, what = "MSE", conf = 0.9)
##       5%      95% 
## 2.172296 3.751296
#MST, based on chi-square distribution
buildConfInt(R2lm, what = "MST")
##     2.5%    97.5% 
## 4.129867 8.446729

By default, cross-validation (CV) is used to estimate the MSE, and nonparametric bootstrapping is used to estimate the correlation between MSE and MST estimators. Other choices can be supplied though, e.g. for bootstrap .632 estimation of the MSE and jackknife estimation of the correlation:

R2lm632jn = R2oosse(y = Brassica$Pheno$Leaf_8_width, x = Brassica$Expr[, 1:5], 
                    fitFun = fitFunLM, predFun = predFunLM, methodMSE = "bootstrap",
                    methodCor = "jackknife")
## Fitting and evaluating the model once took 0 seconds.
## You requested 200 .632 bootstrap instances with 2 cores, which is expected to last for roughly
## 19.2 seconds

Supplying a dataframe with predictor variables is not allowed. The user is asked to build the design matrix yourself with model.matrix prior to calling R2oosse:

#We construct a fake data frame also containing genotypes
fakeDf = data.frame(Brassica$Expr[, 1:5], "genotype" = sample(c("Genotype1", "Genotype2", "Genotype3"), replace = TRUE, nrow(Brassica$Expr)))
#Build the design matrix. The model.matrix variables automatically constructs dummy variables
designMatrix = model.matrix(~ .  , data = fakeDf)[, -1] #Include no intercept as fitting function already does this
#Now run oosse
R2modMat = R2oosse(y = Brassica$Pheno$Leaf_8_width, x = designMatrix, 
                    fitFun = fitFunLM, predFun = predFunLM)
## Fitting and evaluating the model once took 0 seconds.
## You requested 200 repeats of 10-fold cross-validation with 2 cores, which is expected to last for roughly
## 0 seconds

Regularised linear model

For high-dimensional problems, such as the Brassica dataset, a regularised linear model is better suited to incorporate information for all genes. We use the cv.glmnet function from the glmnet package, which includes internal cross-validation for tuning the penalty parameter. Following custom function definitions are needed to fit in with the naming convention of the oosse package.

fitFunReg = function(y, x, ...) {cv.glmnet(y = y, x = x, ...)}
predFunReg = function(mod, x, ...){predict(mod, newx = x, ...)}

We adapt the parameter settings a bit to reduce computation time of the vignette, it is recommended to use 10-fold cross-validation, at least 200 repeats of the cross-validation splits and 50 bootstrap replicates.

nFolds = 5; cvReps = 1e2; nBoots = 4e1;numFeat = 25
if(require(glmnet)){
    if(onWindows <- (.Platform$OS.type == "windows")){
        clusterEvalQ(Clus, require(glmnet))
    }
    R2pen = R2oosse(y = Brassica$Pheno$Leaf_8_width, x = Brassica$Expr[, seq_len(numFeat)], #Subset genes for speed
                    nFolds = nFolds, cvReps = cvReps, nBootstrapsCor = nBoots,
                        fitFun = fitFunReg, predFun = predFunReg, alpha = 1)#Lasso model
    R2pen$R2
}
## Loading required package: glmnet
## Loading required package: Matrix
## Loaded glmnet 4.1-8
## Fitting and evaluating the model once took 0.07 seconds.
## You requested 100 repeats of 5-fold cross-validation with 2 cores, which is expected to last for roughly
## 1 minutes and 30.45 seconds
##         R2       R2SE 
## 0.63788090 0.09197995

Random forest

As a final example we use a random forest as a prediction model. We use the implementation from the randomForest package.

if(require(randomForest)){
   if(onWindows){
        clusterEvalQ(Clus, require(randomForest))
    }
    fitFunrf = function(y, x, ...){randomForest(y = y, x, ...)}
    predFunrf = function(mod, x, ...){predict(mod, x, ...)}
    R2rf = R2oosse(y = Brassica$Pheno$Leaf_8_width, x = Brassica$Expr[, seq_len(numFeat)],
                     nFolds = nFolds, cvReps = cvReps, nBootstrapsCor = nBoots,
                        fitFun = fitFunrf, predFun = predFunrf)
    R2rf$R2
}
## Loading required package: randomForest
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
## Fitting and evaluating the model once took 0.07 seconds.
## You requested 100 repeats of 5-fold cross-validation with 2 cores, which is expected to last for roughly
## 1 minutes and 33.15 seconds
##         R2       R2SE 
## 0.69723299 0.09214491
if(onWindows){
    stopCluster(Clus)
}

The R2 estimate is comparable to that of the penalised regression model.

Session info

sessionInfo()
## R version 4.4.1 (2024-06-14)
## Platform: x86_64-pc-linux-gnu
## Running under: Ubuntu 24.04.1 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C              
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## time zone: Etc/UTC
## tzcode source: system (glibc)
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] randomForest_4.7-1.2 glmnet_4.1-8         Matrix_1.7-1        
## [4] BiocParallel_1.41.0  oosse_1.0.11         rmarkdown_2.28      
## 
## loaded via a namespace (and not attached):
##  [1] doParallel_1.0.17 cli_3.6.3         knitr_1.48        rlang_1.1.4      
##  [5] xfun_0.48         jsonlite_1.8.9    buildtools_1.0.0  htmltools_0.5.8.1
##  [9] maketools_1.3.1   sys_3.4.3         sass_0.4.9        grid_4.4.1       
## [13] evaluate_1.0.1    jquerylib_0.1.4   fastmap_1.2.0     foreach_1.5.2    
## [17] yaml_2.3.10       lifecycle_1.0.4   compiler_4.4.1    codetools_0.2-20 
## [21] Rcpp_1.0.13       lattice_0.22-6    digest_0.6.37     R6_2.5.1         
## [25] splines_4.4.1     shape_1.4.6.1     Rdpack_2.6.1      parallel_4.4.1   
## [29] rbibutils_2.3     bslib_0.8.0       tools_4.4.1       iterators_1.0.14 
## [33] survival_3.7-0    cachem_1.1.0