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 MESA
Risk factor Hypercholesterolemia
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 MESA
  2. Select ID, Age, Gender & the risk factor Hypercholesterolemia.
  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 MESA: 2106 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 MESA: 397 rows
  1. Filter cases having Hypercholesterolemia
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 MESA: 145 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: 542 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 219 94
male 178 51

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: 176
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 = 542, columns = 180
  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 = 8 on full training set
## Partial Least Squares 
## 
## 542 samples
## 178 predictors
##   2 classes: 'NO_RISK', 'RISK' 
## 
## Pre-processing: centered (178) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 433, 434, 434, 434, 433 
## Resampling results across tuning parameters:
## 
##   ncomp  ROC        Sens       Spec      
##    1     0.5811305  0.9773101  0.02068966
##    2     0.6490703  0.9671835  0.12413793
##    3     0.6736338  0.9243354  0.21379310
##    4     0.6819653  0.9294620  0.26896552
##    5     0.7330260  0.9220570  0.33793103
##    6     0.7285552  0.9119304  0.33793103
##    7     0.7293627  0.8968038  0.36551724
##    8     0.7400578  0.8918671  0.37241379
##    9     0.7387560  0.8766772  0.40689655
##   10     0.7371039  0.8817722  0.40689655
##   11     0.7312778  0.8616772  0.40000000
##   12     0.7340430  0.8591456  0.43448276
##   13     0.7216128  0.8591139  0.39310345
##   14     0.7216652  0.8338608  0.41379310
##   15     0.7169904  0.8364241  0.41379310
##   16     0.7130762  0.8414241  0.43448276
##   17     0.7019620  0.8263608  0.43448276
##   18     0.6988488  0.8213608  0.42068966
##   19     0.6860072  0.8188924  0.40689655
##   20     0.6797185  0.8163924  0.37241379
##   21     0.6685967  0.8037975  0.37931034
##   22     0.6592121  0.8062658  0.38620690
##   23     0.6569500  0.7960759  0.40000000
##   24     0.6552695  0.7910443  0.38620690
##   25     0.6555369  0.7935127  0.38620690
##   26     0.6557300  0.7986076  0.38620690
##   27     0.6571093  0.7986392  0.40000000
##   28     0.6604168  0.7961076  0.40000000
##   29     0.6592940  0.7960759  0.40000000
##   30     0.6570482  0.7885759  0.41379310
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was ncomp = 8.

Get the number of component

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

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 
## 
## 542 samples
## 178 predictors
##   2 classes: 'NO_RISK', 'RISK' 
## 
## Pre-processing: centered (178) 
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 541, 541, 541, 541, 541, 541, ... 
## Resampling results:
## 
##   ROC       Sens       Spec     
##   0.749379  0.9017632  0.4137931
## 
## Tuning parameter 'ncomp' was held constant at a value of 8

Or use getTrainPerf to get the results

getTrainPerf(model$pls)
##   TrainROC TrainSens TrainSpec method
## 1 0.749379 0.9017632 0.4137931    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 145 controls (model$pls$pred$obs RISK) > 397 cases (model$pls$pred$obs NO_RISK).
## Area under the curve: 0.7494
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 -1.354647e-02  1.354647e-02
## Sex  4.655764e-04 -4.655764e-04
## `1`  2.194552e-04 -2.194552e-04
## `2`  1.615622e-04 -1.615622e-04
## `3` -1.286077e-04  1.286077e-04
## `4`  1.251057e-03 -1.251057e-03
## `5` -9.190863e-05  9.190863e-05
## `6`  2.847088e-04 -2.847088e-04
## `7`  6.269891e-04 -6.269891e-04
## `8` -5.000050e-04  5.000050e-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_MESA_Hypercholesterolemia.rds