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 Obesity
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 Obesity.
  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 Obesity
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: 676 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: 1073 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 392
male 178 284

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 = 1073, 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 
## 
## 1073 samples
##  178 predictor
##    2 classes: 'NO_RISK', 'RISK' 
## 
## Pre-processing: centered (178) 
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 859, 859, 857, 859, 858 
## Resampling results across tuning parameters:
## 
##   ncomp  ROC        Sens       Spec     
##    1     0.6931867  0.3776266  0.8846732
##    2     0.7535209  0.5263608  0.8283442
##    3     0.7817470  0.5818671  0.8402070
##    4     0.7985058  0.5795570  0.8475817
##    5     0.8128567  0.5894304  0.8520479
##    6     0.8137290  0.6045570  0.8460784
##    7     0.8136041  0.6070886  0.8475490
##    8     0.8140656  0.5996203  0.8475926
##    9     0.8114527  0.6072152  0.8475817
##   10     0.8077203  0.6222152  0.8402070
##   11     0.8055640  0.6020886  0.8327887
##   12     0.8032540  0.6121835  0.8239216
##   13     0.8049535  0.6047152  0.8313399
##   14     0.8065908  0.6121203  0.8328214
##   15     0.8000127  0.6146835  0.8194989
##   16     0.8020338  0.6198101  0.8165251
##   17     0.7995949  0.6223418  0.8179956
##   18     0.7986771  0.6349051  0.8209586
##   19     0.7949984  0.6424051  0.8135730
##   20     0.7885481  0.6273418  0.8076471
##   21     0.7893997  0.6273101  0.8135730
##   22     0.7873467  0.6349367  0.8224619
##   23     0.7840828  0.6349051  0.8121242
##   24     0.7840230  0.6298418  0.8076580
##   25     0.7822385  0.6197785  0.8091721
##   26     0.7815566  0.6147152  0.8076906
##   27     0.7805920  0.6096519  0.7988126
##   28     0.7820040  0.6121835  0.8017647
##   29     0.7814306  0.6121835  0.7958388
##   30     0.7799309  0.6121835  0.8017865
## 
## 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 
## 
## 1073 samples
##  178 predictor
##    2 classes: 'NO_RISK', 'RISK' 
## 
## Pre-processing: centered (178) 
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 1072, 1072, 1072, 1072, 1072, 1072, ... 
## Resampling results:
## 
##   ROC        Sens       Spec     
##   0.8216058  0.6322418  0.8476331
## 
## 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.8216058 0.6322418 0.8476331    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 676 controls (model$pls$pred$obs RISK) > 397 cases (model$pls$pred$obs NO_RISK).
## Area under the curve: 0.8216
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 -0.0021543902  0.0021543902
## Sex  0.0006916250 -0.0006916250
## `1`  0.0008227939 -0.0008227939
## `2`  0.0004325679 -0.0004325679
## `3`  0.0002075783 -0.0002075783
## `4`  0.0015856783 -0.0015856783
## `5`  0.0003963028 -0.0003963028
## `6`  0.0015442720 -0.0015442720
## `7` -0.0006239571  0.0006239571
## `8` -0.0001803662  0.0001803662

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_Obesity.rds