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.
name | value |
---|---|
Cohort name | MESA |
Risk factor | Hypertension |
Maximum number of PLS components | 30 |
Pct PCA variance explained (%) | 99.9 |
Data file | MESA_UKBB_FinalData.csv |
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
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
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: 1147 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 🥳
dt <- bind_rows(dt.norf, dt.rf) %>%
select(-c(NoRisk))
message(sprintf("Training data: %d rows", nrow(dt)))
## Training data: 1544 rows
dt %>% select(c(Sex, sym(params$rf_name))) %>% table() %>%
kbl(caption = "Risk factor distributions") %>% kable_styling("hover", full_width = F, position="left")
NO_RISK | RISK | |
---|---|---|
female | 219 | 646 |
male | 178 | 501 |
just for fixing plot title
cohort_title <- if_else(params$cohort == "UKBB", "UK Biobank", params$cohort)
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)
# 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 = 1544, columns = 180
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 😸
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
##
## 1544 samples
## 178 predictor
## 2 classes: 'NO_RISK', 'RISK'
##
## Pre-processing: centered (178)
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 1235, 1236, 1235, 1236, 1234
## Resampling results across tuning parameters:
##
## ncomp ROC Sens Spec
## 1 0.6219175 0.00000000 1.0000000
## 2 0.6933783 0.07560127 0.9799506
## 3 0.7156430 0.12091772 0.9703588
## 4 0.7271033 0.13863924 0.9668654
## 5 0.7396374 0.17645570 0.9468084
## 6 0.7453183 0.20914557 0.9407139
## 7 0.7497195 0.24183544 0.9389747
## 8 0.7560538 0.26949367 0.9328536
## 9 0.7510463 0.28468354 0.9232770
## 10 0.7528089 0.30481013 0.9258857
## 11 0.7471246 0.30487342 0.9197722
## 12 0.7454098 0.30740506 0.9084412
## 13 0.7431684 0.33522152 0.9093146
## 14 0.7439531 0.31756329 0.9101842
## 15 0.7397601 0.32503165 0.9040896
## 16 0.7354563 0.32506329 0.9075793
## 17 0.7327305 0.32000000 0.8971103
## 18 0.7301427 0.32765823 0.8988570
## 19 0.7258295 0.30496835 0.8945016
## 20 0.7239167 0.31512658 0.8962521
## 21 0.7206700 0.32265823 0.8953788
## 22 0.7181022 0.31000000 0.8883995
## 23 0.7179594 0.31506329 0.8901348
## 24 0.7139764 0.32253165 0.8822783
## 25 0.7125522 0.32003165 0.8796620
## 26 0.7116573 0.32253165 0.8822821
## 27 0.7121683 0.32259494 0.8796620
## 28 0.7124708 0.33525316 0.8761800
## 29 0.7112532 0.33775316 0.8753104
## 30 0.7115324 0.33775316 0.8744295
##
## 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))
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
##
## 1544 samples
## 178 predictor
## 2 classes: 'NO_RISK', 'RISK'
##
## Pre-processing: centered (178)
## Resampling: Leave-One-Out Cross-Validation
## Summary of sample sizes: 1543, 1543, 1543, 1543, 1543, 1543, ...
## Resampling results:
##
## ROC Sens Spec
## 0.7577055 0.2518892 0.9380994
##
## 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.7577055 0.2518892 0.9380994 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 1147 controls (model$pls$pred$obs RISK) > 397 cases (model$pls$pred$obs NO_RISK).
## Area under the curve: 0.7577
plot(m_roc, legacy_axes=TRUE, main = sprintf("Training ROC: %s (%s)", params$rf_name, params$cohort))
coef(model$pls$finalModel)[1:10,,]
## NO_RISK RISK
## Age -0.0083661344 0.0083661344
## Sex 0.0004837740 -0.0004837740
## `1` 0.0004044612 -0.0004044612
## `2` 0.0001041601 -0.0001041601
## `3` -0.0001257280 0.0001257280
## `4` 0.0010437589 -0.0010437589
## `5` 0.0002361550 -0.0002361550
## `6` 0.0012938788 -0.0012938788
## `7` -0.0001025789 0.0001025789
## `8` 0.0005456393 -0.0005456393
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_Hypertension.rds