BTE3207 week 14

Minsik Kim

2026 Fall

Agenda

This lecture will practice running

  1. Random forest (RF)
  2. Lasso regression
  3. Partial least squares (PLS)
  4. Sparse partial least squares (sPLS)
  5. Binary prediction, ROC curves, and AUC

Let’s use the same data for all four. Our question is simple: can we predict SBP for a person the model has not seen?

Run a few chunks as we reach each model in class. We will look at the syntax first, then compare the predictions together. The second part changes the outcome to a 0/1 measurement label and compares disease history with predictions from the same examination data.

Download this Rmd

Before begin..

Open BTE3207_Advanced_Biostatistics.Rproj. Save this Rmd in the project folder. Keep sbp_dataset_korea_2013-2014.csv in dataset, just as before.

If a package is missing, run the following once in the Console. The installation chunks do not run when we Knit.

install.packages(c("knitr", "rmarkdown", "rmdformats", "randomForest", "glmnet", "pROC"))
install.packages("BiocManager")
BiocManager::install("mixOmics", update = FALSE, ask = FALSE)

mixOmics comes from Bioconductor. It provides both PLS and sPLS here. package::function() tells R which package’s function we want to use. We will use this form so that similarly named functions do not get mixed up.

Let’s load the data

SBP is systolic blood pressure. Today it is a continuous outcome in mmHg. DBP, BMI, FBS, and Female will be our four predictors. These measurements come from the same examination. We are practicing prediction of recorded SBP, not predicting a future event or a causal effect.

dataset_sbp <- read.csv("dataset/sbp_dataset_korea_2013-2014.csv")
dataset_sbp$Female <- ifelse(dataset_sbp$SEX == 2, 1, 0)
model_data <- dataset_sbp[, c("SBP", "DBP", "BMI", "FBS", "Female", "DIS")]
model_data <- model_data[complete.cases(model_data), ]

set.seed(2026)
small <- model_data[sample(nrow(model_data), 1000), ]
head(small)

SEX is 1 = Male and 2 = Female. Female is now 0 = Male and 1 = Female. Zero is a category here, not missing data.

[, c(...)] selects columns. complete.cases() keeps rows with no missing values in these six columns. We keep DIS for the classification section. It is not a predictor in the four SBP regression models. We use 1,000 rows so that the practice runs quickly. set.seed() makes the random selection reproducible.

Training data and test data

set.seed(2026)
train_id <- sample(seq_len(nrow(small)), 700)
train_data <- small[train_id, ]
test_data <- small[-train_id, ]
c(Training = nrow(train_data), Test = nrow(test_data))
## Training     Test 
##      700      300

seq_len(nrow(small)) gives the row numbers. The minus sign in small[-train_id, ] means leave out these rows. We will keep the same 700/300 split for all four models.

Fit the model using the training data. Use the test data to check its predictions afterwards. Do not choose variables or settings using test results and then call the same test set an independent evaluation.

X and Y

Some functions use a formula such as SBP ~ DBP + BMI. Others ask us to supply X and Y separately. Let’s prepare those now.

predictors <- c("DBP", "BMI", "FBS", "Female")
X_train <- as.matrix(train_data[, predictors])
X_test <- as.matrix(test_data[, predictors])
y_train <- train_data$SBP
Y_train <- as.matrix(train_data[, "SBP", drop = FALSE])
dim(X_train)
## [1] 700   4
dim(Y_train)
## [1] 700   1

X has one row per person and one column per predictor. SBP is Y, so we leave SBP out of X. as.matrix() makes a numeric matrix.

y_train is a vector for glmnet. Y_train is the same outcome in a one-column matrix for mixOmics. drop = FALSE keeps that column as a table before converting it. The test columns must be in the same order.

Random forest (RF)

A decision tree asks a sequence of questions about the predictors. For regression, each tree predicts a number. A random forest grows many trees and averages their predictions.

Each tree uses a bootstrap sample of the training rows, sampled with replacement. At each split, it tries a random subset of the predictors.

Fit the model

set.seed(2026)
rf_fit <- randomForest::randomForest(
  SBP ~ DBP + BMI + FBS + Female, data = train_data,
  ntree = 200, mtry = 2)

The formula has the same direction as lm(): outcome on the left, predictors on the right.

  • ntree = 200: grow 200 trees.
  • mtry = 2: try two candidate predictors at each split.

mtry = 2 does not mean two trees or two predictors for the whole forest. Because SBP is numeric, this is a regression forest. A categorical outcome would require a classification model instead.

Predict

rf_pred <- as.numeric(predict(rf_fit, newdata = test_data))
head(data.frame(Observed = test_data$SBP, Predicted = rf_pred))

newdata contains the people we kept aside. Each prediction is in mmHg. For example, three trees predicting 118, 122, and 120 would average to 120. This is averaging, rather than a majority vote between disease classes.

Lasso regression

Let’s start from a linear regression, but add a penalty for large coefficients. Lasso uses the sum of the absolute values of the slope coefficients. It can shrink some coefficients all the way to zero.

The model still predicts a number from the predictors. Now some predictors may drop out. A zero coefficient does not prove that the variable is biologically unimportant.

Choose the penalty using training data

set.seed(2026)
lasso_fit <- glmnet::cv.glmnet(
  X_train, y_train, alpha = 1, nfolds = 5,
  type.measure = "mse", standardize = TRUE)
plot(lasso_fit)

  • alpha = 1: use lasso. This is a model setting, not a significance level.
  • nfolds = 5: five-fold cross-validation within the training data.
  • standardize = TRUE: scale predictors for fitting. The function handles it.

In five-fold cross-validation, fit on four parts and check predictions on the remaining part. Repeat so that every part takes a turn.

The plot shows mean cross-validation error for different penalties. Here, lower is better. lambda controls the penalty strength. lambda.min has the smallest mean error. lambda.1se is the largest penalty within one standard error of that minimum; it often gives a simpler model. Let’s use lambda.1se today.

Read the coefficients, then predict

coef(lasso_fit, s = "lambda.1se")
## 5 x 1 sparse Matrix of class "dgCMatrix"
##             lambda.1se
## (Intercept) 47.2037650
## DBP          0.9162167
## BMI          0.2074373
## FBS          .        
## Female       .
lasso_pred <- as.numeric(predict(lasso_fit, newx = X_test, s = "lambda.1se"))

In the printed coefficient table, a dot means zero. Check FBS and Female. With this sample and setting, their coefficients are zero. The retained predictors are DBP and BMI. This may change with another sample or penalty.

newx is the predictor matrix for new people. as.numeric() turns the one-column prediction matrix into a simple vector.

Partial least squares (PLS)

What if several predictors carry similar information? PLS makes a few components, or weighted scores, from the predictors, and uses them to predict Y. It uses information from both X and Y when finding the components.

Here is a small example to see what a weighted score means. These weights and standardized values are made up for calculation.

DBP_z <- 1
BMI_z <- 2
FBS_z <- -1
Female_z <- 0
component1 <- 0.6 * DBP_z + 0.5 * BMI_z + 0.4 * FBS_z + 0.1 * Female_z
component1
## [1] 1.2

The score is 1.2. We have combined four numbers into one number. This is a component score, not a predicted SBP. The fitted model learns its own weights and uses its components to predict SBP. Ordinary PLS does not impose sparse variable selection.

Fit PLS regression

pls_fit <- mixOmics::pls(X_train, Y_train, ncomp = 2,
                        mode = "regression", scale = TRUE)
round(pls_fit$loadings$X, 3)
##         comp1  comp2
## DBP     0.865  0.479
## BMI     0.407 -0.520
## FBS     0.219 -0.416
## Female -0.194  0.572
  • ncomp = 2: use two components, not two original predictors.
  • mode = "regression": predict Y from X.
  • scale = TRUE: center and scale using training data.

loadings$X shows the X weights for the components. The second component is formed after the first component’s information has been removed in the PLS algorithm. It adds information beyond the first one. We use two components as an example today, not as a proven best choice.

Predict with two components

pls_array <- predict(pls_fit, newdata = X_test)$predict
dim(pls_array)
## [1] 300   1   2
pls_pred <- as.numeric(pls_array[, 1, 2])

This output has three dimensions: person, outcome, number of components. [, 1, 2] means all people, the first outcome (SBP), using two components. It is the prediction using the first two components together.

The fitted model applies its training centering/scaling to the test data. We do not scale the test data separately using its own mean and SD.

Sparse partial least squares (sPLS)

PLS summarizes predictors. Sparse PLS also selects predictors by making some component weights zero. Think of combining variables while leaving some out of each component.

spls_fit <- mixOmics::spls(X_train, Y_train, ncomp = 2,
                          keepX = c(2, 2), mode = "regression", scale = TRUE)
round(spls_fit$loadings$X, 3)
##        comp1  comp2
## DBP     0.96  0.000
## BMI     0.28 -0.835
## FBS     0.00  0.550
## Female  0.00  0.000

keepX = c(2, 2) keeps two predictors in component 1 and two in component 2. It does not necessarily mean two different predictors in the whole model.

Let’s read the names directly from the fitted model.

mixOmics::selectVar(spls_fit, comp = 1)$X$name
## [1] "DBP" "BMI"
mixOmics::selectVar(spls_fit, comp = 2)$X$name
## [1] "BMI" "FBS"

Here, component 1 selects DBP and BMI. Component 2 selects BMI and FBS. So the two components use three distinct predictors altogether. These are component loadings, not the final SBP regression coefficients.

Predict

spls_array <- predict(spls_fit, newdata = X_test)$predict
spls_pred <- as.numeric(spls_array[, 1, 2])

Voila! The prediction syntax is almost the same as PLS. ncomp = 2 and keepX = c(2, 2) are teaching choices here. We would compare candidate settings using cross-validation inside the training set before using them in a real prediction study.

We are using PLS and sPLS regression. PLS-DA and sPLS-DA are their related methods for categorical outcomes. This first part keeps SBP continuous. Later, we use a separate binary measurement label for a classification exercise.

Compare the predictions

We have four sets of predictions for the same 300 test participants.

predictions <- data.frame(Observed = test_data$SBP,
                          RF = rf_pred, Lasso = lasso_pred,
                          PLS = pls_pred, sPLS = spls_pred)
head(round(predictions, 1))

How far were the predictions from the observations?

RMSE is the root mean squared error. Subtract the predictions from the observations, square the differences, average them, then take the square root. It has the same unit as SBP: mmHg.

For two made-up people, observed SBP is 120 and 130; predicted SBP is 118 and 132. The differences are 2 and -2. RMSE is 2 mmHg.

sqrt(mean((c(120, 130) - c(118, 132))^2))
## [1] 2

Let’s do the same calculation for each model.

test_rmse <- c(
  RF = sqrt(mean((test_data$SBP - rf_pred)^2)),
  Lasso = sqrt(mean((test_data$SBP - lasso_pred)^2)),
  PLS = sqrt(mean((test_data$SBP - pls_pred)^2)),
  sPLS = sqrt(mean((test_data$SBP - spls_pred)^2)))
round(test_rmse, 2)
##    RF Lasso   PLS  sPLS 
##  9.81  9.68  9.64  9.60

Lower RMSE means smaller prediction error for these test observations. Our values are around 9.6 to 9.8 mmHg. The differences are small.

This is a syntax exercise, not evidence that one method always wins. We selected lasso’s penalty by cross-validation, while the other models’ settings were fixed for teaching. A fuller comparison would tune every model within the training data and evaluate the final choices on held-out data.

Have a look

plot(test_data$SBP, spls_pred,
     xlab = "Observed SBP (mmHg)", ylab = "Predicted SBP (mmHg)",
     pch = 16, col = "grey50", asp = 1)
abline(a = 0, b = 1, col = "red", lwd = 2)

On the red line, observed and predicted SBP agree. Points away from it show prediction error. This is a base R plot: pch chooses the point shape, col its colour, and abline(a = 0, b = 1) adds the line y = x.

Before we finish regression

Model Main idea Settings used here
RF Average many regression trees ntree = 200, mtry = 2
Lasso Shrink coefficients; some become zero alpha = 1, s = "lambda.1se"
PLS Summarize X into components useful for predicting Y ncomp = 2
sPLS Make components and select their predictors ncomp = 2, keepX = c(2, 2)

Try these before looking at the answers:

  1. Does mtry = 2 mean the forest has two trees?
  2. Does ncomp = 2 mean PLS uses only two predictors?
  3. Does keepX = c(2, 2) guarantee exactly two distinct predictors overall?
  4. Can we choose the model settings from the test RMSE, then report that same RMSE as an independent test?
Click for the answers
  1. No. It is the number of candidate predictors at each split.
  2. No. It is the number of components. Each can combine several predictors.
  3. No. Each component keeps two predictors; they may overlap or differ.
  4. No. Once test results guide model selection, that set has also helped choose the model. Use training cross-validation for those choices.

One more comparison: lm()

We already know lm(). Does a more complicated model necessarily predict better? Let’s include the ordinary linear model as a reference.

lm_fit <- lm(SBP ~ DBP + BMI + FBS + Female, data = train_data)
lm_pred <- predict(lm_fit, newdata = test_data)
sqrt(mean((test_data$SBP - lm_pred)^2))
## [1] 9.61379

Compare its test RMSE with the four values above. With only four predictors, a simple linear model can be competitive. More complicated is not always better.

Now, a binary outcome

So far, we predicted a number: SBP in mmHg. Let’s change the question. Can we identify a person whose recorded BP is above our cut-off?

We will make four sets of predictions: history only, ordinary logistic regression, lasso logistic regression, and random forest classification. The same 700 people train the models; the same 300 people test them.

History and the examination measurement are different

Remember DIS? This is disease history in our teaching file.

DIS History HistoryHTN
1 Hypertension and diabetes 1
2 Hypertension 1
3 Diabetes 0
4 Neither condition 0

Here, ElevatedBP = 1 means recorded SBP >= 140 OR DBP >= 90 mmHg. Zero means both measurements are below these cut-offs. This is a teaching label for the recorded examination, not a confirmed clinical diagnosis or a future hypertension event. The Korean adult guideline uses 140/90 mmHg as the office BP diagnostic threshold, with appropriate confirmation of measurements. Our file also includes younger age groups. We use this fixed cut-off only to practice classification; it is not an age-specific clinical diagnosis.

DIS is not an earlier year’s BP measurement. We do not have paired BP measurements from two dates in this file. A person can have hypertension history but BP below the cut-off at the examination, for example with treatment. This file does not tell us whether that explanation applies.

binary_data <- small
binary_data$HistoryHTN <- ifelse(binary_data$DIS %in% c(1, 2), 1, 0)
binary_data$ElevatedBP <- ifelse(
  binary_data$SBP >= 140 | binary_data$DBP >= 90, 1, 0)
binary_data$BPclass <- factor(binary_data$ElevatedBP,
                              levels = c(0, 1),
                              labels = c("Below", "Elevated"))
binary_train <- binary_data[train_id, ]
binary_test <- binary_data[-train_id, ]

%in% c(1, 2) asks whether DIS is either 1 or 2. The symbol | means OR. factor() tells the random forest that the outcome contains categories. We keep the numeric 0/1 outcome too, for logistic regression and ROC.

with(binary_test, table(HistoryHTN, ElevatedBP))
##           ElevatedBP
## HistoryHTN   0   1
##          0 225  17
##          1  47  11

Rows show history; columns show the examination label. These are two different definitions, so an off-diagonal cell is not automatically an error. In our test set, 28 of 300 people have ElevatedBP = 1.

Do not give SBP or DBP to these classifiers. We just used those values to define the answer. Including them as predictors would give the model the answer rule. That would be target leakage, not an interesting prediction.

1. What if we only know the history?

Let’s use the training data to estimate the probability of elevated BP for people with and without hypertension history.

history_fit <- glm(ElevatedBP ~ HistoryHTN,
                   data = binary_train, family = binomial)
prob_history <- predict(history_fit, newdata = binary_test,
                         type = "response")

family = binomial fits logistic regression. type = "response" gives probabilities between 0 and 1, rather than log-odds. This model can give only two probability values because HistoryHTN is 0/1.

2. Ordinary logistic regression

We already learned this one. Now add BMI, FBS, and Female to the history. These same four inputs will also go into lasso and random forest.

logistic_fit <- glm(ElevatedBP ~ BMI + FBS + Female + HistoryHTN,
                    data = binary_train, family = binomial)
prob_logistic <- predict(logistic_fit, newdata = binary_test,
                         type = "response")

The short example leaves age group out so that we can reuse our simple numeric predictor matrix. These are teaching models, not complete clinical prediction tools.

3. Lasso, but for a binary outcome

The matrix syntax is the same as before. Add family = "binomial".

binary_predictors <- c("BMI", "FBS", "Female", "HistoryHTN")
X_binary_train <- as.matrix(binary_train[, binary_predictors])
X_binary_test <- as.matrix(binary_test[, binary_predictors])

set.seed(2026)
binary_lasso <- glmnet::cv.glmnet(
  X_binary_train, binary_train$ElevatedBP,
  family = "binomial", alpha = 1, nfolds = 5,
  type.measure = "deviance", standardize = TRUE)
prob_lasso <- as.numeric(predict(binary_lasso,
  newx = X_binary_test, s = "lambda.1se", type = "response"))

Cross-validation still happens inside the training data. Here, it compares binomial deviance, a measure of probability prediction error; smaller is better. We do not choose lambda by looking at test AUC.

4. Random forest, but for categories

set.seed(2026)
binary_rf <- randomForest::randomForest(
  BPclass ~ BMI + FBS + Female + HistoryHTN,
  data = binary_train, ntree = 200, mtry = 2)
prob_rf <- predict(binary_rf, newdata = binary_test,
                    type = "prob")[, "Elevated"]

The outcome is a factor, so this is classification. type = "prob" returns a score for each class. We select the Elevated column. For this forest, the score is the fraction of trees voting for that class. It is useful for ranking people, but is not automatically a calibrated clinical probability.

binary_predictions <- data.frame(
  Observed = binary_test$ElevatedBP,
  History = prob_history, Logistic = prob_logistic,
  Lasso = prob_lasso, RF = prob_rf)
head(round(binary_predictions, 3))

We now have four scores for each of the same test participants. Keep these scores for ROC; do not turn them into 0/1 predictions first.

Let’s draw ROC curves

A classification threshold decides when a score counts as positive. Changing the threshold changes sensitivity and specificity.

  • Sensitivity: among people with ElevatedBP = 1, how many do we find?
  • Specificity: among people with ElevatedBP = 0, how many do we correctly label negative?
  • The ROC curve plots sensitivity against 1 - specificity over thresholds.
roc_history <- pROC::roc(binary_test$ElevatedBP, prob_history,
  levels = c(0, 1), direction = "<", quiet = TRUE)
roc_logistic <- pROC::roc(binary_test$ElevatedBP, prob_logistic,
  levels = c(0, 1), direction = "<", quiet = TRUE)
roc_lasso <- pROC::roc(binary_test$ElevatedBP, prob_lasso,
  levels = c(0, 1), direction = "<", quiet = TRUE)
roc_rf <- pROC::roc(binary_test$ElevatedBP, prob_rf,
  levels = c(0, 1), direction = "<", quiet = TRUE)

levels = c(0, 1) makes 0 the negative group and 1 the positive group. direction = "<" fixes the interpretation: higher scores predict the positive group. We do not let the test outcomes choose a direction that makes an unhelpful score look better.

par(pty = "s")
plot(1 - roc_history$specificities, roc_history$sensitivities,
     type = "l", col = "grey50", lwd = 2,
     xlim = c(0, 1), ylim = c(0, 1),
     xlab = "1 - specificity (false positive rate)",
     ylab = "Sensitivity (true positive rate)",
     main = "ROC curves: the same 300 test participants", asp = 1,
     xaxs = "i", yaxs = "i")
lines(1 - roc_logistic$specificities, roc_logistic$sensitivities,
      col = "black", lwd = 2)
lines(1 - roc_lasso$specificities, roc_lasso$sensitivities,
      col = "red", lwd = 2, lty = 2)
lines(1 - roc_rf$specificities, roc_rf$sensitivities,
      col = "blue", lwd = 2)
abline(a = 0, b = 1, lty = 3, col = "grey70")
legend("bottomright", c("History only", "Logistic", "Lasso", "RF"),
       col = c("grey50", "black", "red", "blue"),
       lty = c(1, 1, 2, 1), lwd = 2, bty = "n")

plot() starts the figure. lines() adds the other curves. We use 1 minus specificity on the x-axis, so abline(a = 0, b = 1) draws the diagonal. The history-only curve has very few corners because it has only two possible scores.

AUC: one number to summarize the ranking

AUC is the area under the ROC curve. It is also the probability that a randomly chosen positive person receives a higher score than a randomly chosen negative person, counting a tie as half a success. An AUC of 0.8 does not mean 80% of people were correctly classified.

test_auc <- c(
  History = as.numeric(pROC::auc(roc_history)),
  Logistic = as.numeric(pROC::auc(roc_logistic)),
  Lasso = as.numeric(pROC::auc(roc_lasso)),
  RF = as.numeric(pROC::auc(roc_rf)))
round(test_auc, 3)
##  History Logistic    Lasso       RF 
##    0.610    0.704    0.705    0.656

An AUC of 0.5 corresponds to chance ranking; 1 means perfect ranking. AUC does not tell us whether the probabilities are calibrated or which threshold should be used in practice.

A good accuracy can hide missed cases

Let’s turn the RF scores into categories using 0.5, just to see what happens. This cut-off is for illustration, not a recommended clinical decision rule.

rf_class <- ifelse(prob_rf >= 0.5, 1, 0)
confusion <- table(
  Observed = factor(binary_test$ElevatedBP, levels = c(0, 1)),
  Predicted = factor(rf_class, levels = c(0, 1)))
confusion
##         Predicted
## Observed   0   1
##        0 267   5
##        1  26   2
TP <- confusion["1", "1"]
FN <- confusion["1", "0"]
TN <- confusion["0", "0"]
FP <- confusion["0", "1"]
c(Sensitivity = TP / (TP + FN),
  Specificity = TN / (TN + FP),
  Accuracy = (TP + TN) / sum(confusion))
## Sensitivity Specificity    Accuracy 
##  0.07142857  0.98161765  0.89666667

Compare this with a very lazy classifier:

mean(binary_test$ElevatedBP == 0)
## [1] 0.9066667

Calling everybody negative gives 90.7% accuracy here, but sensitivity is zero. That is why we look beyond accuracy. Lowering a threshold usually finds more positives and creates more false positives too. Decide how to choose a threshold using training/validation data and the consequences of errors, not by repeatedly trying the test set.

So, is ML better?

Our test AUCs are history only 0.610, ordinary logistic 0.704, lasso 0.705, and RF 0.656. Let’s read the comparison carefully.

Here, the models using additional measurements have higher test AUC than history alone. Ordinary logistic regression and lasso are very close; RF ranks below both. This run does not show an advantage of RF over the ordinary logistic model.

History only versus the other models asks whether more information helps. Logistic, lasso, and RF all use the same four predictors, so their comparison is more informative about the modeling method.

History and examination BP disagree for some people; that does not mean the history is wrong. Treatment and different measurement occasions could matter. We have no earlier BP or medication data to resolve this here.

If a model has the largest AUC, we can say it ranked these test participants best in this run. This small split does not establish that it is generally superior, and adding predictors is not proof that an ML algorithm is better. Only lasso was tuned by training CV here; the RF settings were fixed.

Try explaining these in your own words:

  1. Why would putting SBP and DBP into these classifiers be a problem?
  2. Why can a history-positive person have ElevatedBP = 0?
  3. Does AUC = 0.8 mean accuracy = 80% at the 0.5 cut-off?
  4. If RF beats history only but loses to logistic regression, what did we learn?
Click for the answers
  1. Those measurements define the label; the model would be given the answer rule.
  2. History and the current examination measure different things. Treatment is one possible explanation, which this file cannot confirm.
  3. No. AUC evaluates ranking over thresholds, not accuracy at one threshold.
  4. More inputs may help, but the result does not show an advantage of RF over ordinary logistic regression with those same inputs.