knitr::opts_chunk$set(echo = TRUE)

library(caret)
library(R.matlab)
library(tidyverse)
library(pROC)
library(broom)
library(kableExtra)
library(rlang)
library(testthat)
library(doParallel)

source("train_pls_formulae.R")
n_cores <- detectCores()
message(sprintf("Using %d cores", n_cores))
## Using 20 cores

Note: the output HTML & the training RDS data are saved in PLS.

Parameters
name value
Cohort name UKBB
Risk factor Diabetes
Maximum number of PLS components 30
Pct PCA variance explained (%) 99.9
Data file MESA_UKBB_FinalData.csv

Get the data

  1. Read the variable and select only cases within the cohort UKBB
  2. Select ID, Age, Gender & the risk factor Diabetes.
  3. Recode the risk factor values where TRUE -> RISK and FALSE -> NO_RISK
dt.ori <- read_csv(datafile, show_col_types = FALSE) %>% 
  filter(Cohort == params$cohort) %>%
  select(c(ID, Age, Sex, NoRisk, sym(params$rf_name))) %>%
  mutate(
    !!sym(params$rf_name) := recode_factor(as.factor(!!sym(params$rf_name)), "FALSE" = "NO_RISK", "TRUE" = "RISK"),
    Sex = as.factor(Sex)
  )

message(sprintf("Original %s: %d rows", params$cohort, nrow(dt.ori)))
## Original UKBB: 2960 rows
  1. Define the NO RISK sub-cohort, which is all cases without any risk factor at all
dt.norf <- filter(dt.ori, NoRisk)

message(sprintf("No risk sub-cohort %s: %d rows", params$cohort, nrow(dt.norf)))
## No risk sub-cohort UKBB: 645 rows
  1. Filter cases having Diabetes
dt.rf <- filter(dt.ori,  !!sym(params$rf_name) == "RISK")

message(sprintf("Risk sub-cohort %s: %d rows", params$cohort, nrow(dt.rf)))
## Risk sub-cohort UKBB: 159 rows

Sanity check: the intersection between NO_RISK and RISK id’s should be zero

test_that("Unique IDs", {
  expect_equal(length(intersect(dt.rf$ID, dt.norf$ID)), 0)
})
## Test passed 🎊
  1. Final data
dt <- bind_rows(dt.norf, dt.rf) %>% 
  select(-c(NoRisk))

message(sprintf("Training data: %d rows", nrow(dt)))
## Training data: 804 rows
dt %>% select(c(Sex, sym(params$rf_name))) %>% table() %>% 
  kbl(caption = "Risk factor distributions") %>% kable_styling("hover", full_width = F, position="left")
Risk factor distributions
NO_RISK RISK
female 395 65
male 250 94

just for fixing plot title

cohort_title <- if_else(params$cohort == "UKBB", "UK Biobank", params$cohort)  

Prepare the PC scores

  1. Determine how many PCA components to use
model <- list()

expl_vars <- readMat(paste("PCA", params$cohort, "PCA_explained.mat", sep = "/"))$explained
model$npcs <- length(expl_vars[cumsum(expl_vars) < params$pca_var])
message(sprintf("Number of PC components with %.2f%% variance explained: %d", params$pca_var, model$npcs))
## Number of PC components with 99.90% variance explained: 210
rm(expl_vars)
  1. Read PCA components
  2. Combine with Age, Sex & the risk factor using the same ID
# this is a combined X (Age + Sex + PCScores) & Y (Risk Factor)
model$dt.train <- inner_join(
  dt %>% 
    select(c(ID, Age, Sex, sym(params$rf_name))) %>% 
    mutate(
      Sex = as.numeric(Sex)
    ),
  cbind(
    read.csv(paste("PCA", sprintf("%s_ids.csv", params$cohort), sep="/")),
    readMat(paste("PCA", params$cohort, "PCA_score.mat", sep="/"))$score[, 1:model$npcs]
  ),
  by = c("ID" = "ID"))

# check the cohort
message(sprintf("Number of cases = %d, columns = %d", nrow(model$dt.train), ncol(model$dt.train)))
## Number of cases = 804, columns = 214
  1. Sanity checks.

This should only include that specific cohort

test_that("Check cohort", {
  expect_equal(substr(params$cohort, 1, 3), (model$dt.train %>% transmute(cohort = substr(ID, 1, 3)) %>% distinct())$cohort)
})
## Test passed 🎊

No NA rows

test_that("No NA rows", {
  expect_equal(0, sum(is.na(model$dt.train)))
})
## Test passed 🥇

Find optimal number of PLS components

We’re going to use 5-fold cross validation to determine the optimal parameter for PLS, which is the ncomp.

(m_kcv <- train_pls(as.formula(sprintf("%s ~ Age + Sex + .", params$rf_name)), dt = model$dt.train %>% select(-c(ID)), n_comps=params$max_ncomps))
## + Fold1: ncomp=30 
## - Fold1: ncomp=30 
## + Fold2: ncomp=30 
## - Fold2: ncomp=30 
## + Fold3: ncomp=30 
## - Fold3: ncomp=30 
## + Fold4: ncomp=30 
## - Fold4: ncomp=30 
## + Fold5: ncomp=30 
## - Fold5: ncomp=30 
## Aggregating results
## Selecting tuning parameters
## Fitting ncomp = 16 on full training set
## Partial Least Squares 
## 
## 804 samples
## 212 predictors
##   2 classes: 'NO_RISK', 'RISK' 
## 
## Pre-processing: centered (212) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 643, 644, 643, 643, 643 
## Resampling results across tuning parameters:
## 
##   ncomp  ROC        Sens       Spec     
##    1     0.6492170  1.0000000  0.0062500
##    2     0.7253298  0.9782946  0.1252016
##    3     0.7581724  0.9751938  0.2389113
##    4     0.7664182  0.9689922  0.2391129
##    5     0.7765551  0.9689922  0.2264113
##    6     0.7866560  0.9627907  0.2893145
##    7     0.7835490  0.9565891  0.2891129
##    8     0.7772818  0.9488372  0.3391129
##    9     0.7821612  0.9488372  0.3141129
##   10     0.7818361  0.9503876  0.3266129
##   11     0.7811797  0.9426357  0.3264113
##   12     0.7853932  0.9457364  0.3457661
##   13     0.7862575  0.9333333  0.3520161
##   14     0.7870702  0.9240310  0.3836694
##   15     0.7901585  0.9271318  0.3772177
##   16     0.7943408  0.9271318  0.3903226
##   17     0.7941673  0.9209302  0.3838710
##   18     0.7870968  0.9224806  0.4215726
##   19     0.7827879  0.9240310  0.3963710
##   20     0.7795027  0.9271318  0.4151210
##   21     0.7828723  0.9209302  0.4282258
##   22     0.7801232  0.9178295  0.4405242
##   23     0.7779476  0.9209302  0.4344758
##   24     0.7797199  0.9193798  0.4469758
##   25     0.7786322  0.9209302  0.4090726
##   26     0.7755861  0.9193798  0.4592742
##   27     0.7799747  0.9131783  0.4342742
##   28     0.7770021  0.9085271  0.4217742
##   29     0.7725541  0.9193798  0.4280242
##   30     0.7742139  0.9131783  0.4280242
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was ncomp = 16.

Get the number of component

(model$ncomp <- m_kcv$bestTune$ncomp)
## [1] 16

Plot for analysis

plot(m_kcv, main=sprintf("PLS components (%s - %s)", params$rf_name, params$cohort))

Train PLS

After we get the optimal parameter, we train the PLS using leave-one-out cross validation. Since this will take time, we need multiple cores to compute.

Create train control with LOOCV

tc_loo <- trainControl(method="LOOCV", savePredictions = "all", classProbs = TRUE, verboseIter=FALSE,
                       summaryFunction = twoClassSummary, allowParallel = TRUE)
# parallel cores
if( n_cores > 1 ) {
  cl <- makeCluster(n_cores - 1, outfile = "")
  registerDoParallel(cl)
  getDoParWorkers()
}
## [1] 19
# train (take a while)
model$pls <- train(
  form = sprintf("%s ~ Age + Sex + .", params$rf_name) %>% as.formula(),
  data = model$dt.train %>% select(-ID),
  method = "pls", 
  metric = "ROC",
  preProc = c("center"),
  tuneGrid = data.frame(ncomp=model$ncomp),
  probMethod = "softmax",
  trControl = tc_loo
)

# unregister cores
if( n_cores > 1 ) {
  stopCluster(cl)
  registerDoSEQ()
}
model$pls
## Partial Least Squares 
## 
## 804 samples
## 212 predictors
##   2 classes: 'NO_RISK', 'RISK' 
## 
## Pre-processing: centered (212) 
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 803, 803, 803, 803, 803, 803, ... 
## Resampling results:
## 
##   ROC        Sens       Spec     
##   0.7908927  0.9333333  0.3584906
## 
## Tuning parameter 'ncomp' was held constant at a value of 16

Or use getTrainPerf to get the results

getTrainPerf(model$pls)
##    TrainROC TrainSens TrainSpec method
## 1 0.7908927 0.9333333 0.3584906    pls

The prediction is in model$pls$pred data frame. Let’s plot the training ROC

Check the level order, because RISK should be the first, since that’s the prediction target.

levels(model$pls$pred$obs)
## [1] "NO_RISK" "RISK"

Calculate the ROC. Note we need to reverse the category level.

(m_roc <- roc(model$pls$pred$obs, model$pls$pred$RISK, levels = rev(levels(model$pls$pred$obs))))
## Setting direction: controls > cases
## 
## Call:
## roc.default(response = model$pls$pred$obs, predictor = model$pls$pred$RISK,     levels = rev(levels(model$pls$pred$obs)))
## 
## Data: model$pls$pred$RISK in 159 controls (model$pls$pred$obs RISK) > 645 cases (model$pls$pred$obs NO_RISK).
## Area under the curve: 0.7909
plot(m_roc, legacy_axes=TRUE, main = sprintf("Training ROC: %s (%s)", params$rf_name, params$cohort))

Show the first 10 coefficients

coef(model$pls$finalModel)[1:10,,]
##           NO_RISK          RISK
## Age -6.324943e-03  6.324943e-03
## Sex  3.964181e-04 -3.964181e-04
## `1`  3.696745e-04 -3.696745e-04
## `2`  2.286540e-04 -2.286540e-04
## `3` -4.476987e-04  4.476987e-04
## `4` -9.143891e-04  9.143891e-04
## `5`  4.922849e-04 -4.922849e-04
## `6`  7.756114e-04 -7.756114e-04
## `7` -9.794765e-05  9.794765e-05
## `8`  8.053501e-04 -8.053501e-04

Save the results

Add some other information too in the model

model$cohort <- params$cohort
model$risk_factor <- params$rf_name
model$pca_var <- params$pca_var
model_filename <- paste(params$output_folder, sprintf("PLS_%s_%s.rds", params$cohort, params$rf_name), sep="/")
write_rds(model, file=model_filename, compress = "gz")
message(sprintf("Saved model to %s", model_filename))
## Saved model to PLS/PLS_UKBB_Diabetes.rds