-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathML_random_forest_hyperparameter_tune.R
More file actions
2052 lines (1613 loc) · 87 KB
/
ML_random_forest_hyperparameter_tune.R
File metadata and controls
2052 lines (1613 loc) · 87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Random Forest Workflow - Metagenomics Data
# load libraries
library(ggplot2)
library(cowplot)
library(patchwork)
library(tidyverse)
library(compositions)
library(randomForest)
library(caret)
library(pROC)
library(Boruta)
library(ParBayesianOptimization)
library(doParallel)
library(fastshap)
library(viridis)
library(ggrepel)
# setwd
setwd("/Users/kristinvandenham/kmvanden/RStudio/")
### load data
# metadata
meta <- read.table("metadata.txt", header = TRUE)
rownames(meta) <- meta$sample_name
meta$condition <- as.factor(meta$condition) # convert condition column into a factor
table(meta$condition)
meta <- meta[, -3] # remove unnecessary meta column
# feature table
feat <- read.table("feature_table.txt", header = TRUE)
### filter species present in less than 10% of samples
feat_t <- as.data.frame(t(feat)) # transpose feature table
min_prevalence <- 0.10
feat_filtered <- feat_t[, colMeans(feat_t > 0) >= min_prevalence] # subset the feature table to only include features present in at least 10% of samples
dim(feat_filtered) # 70 935
# convert feature table to relative abundances
feat_rel_abund <- feat_filtered/rowSums(feat_filtered)
# add pseudocount and perform CLR transformation
feat_clr <- clr(feat_rel_abund + 1e-6)
feat_clr <- as.data.frame(feat_clr)
# rownames of metadata need to match the rownames of the feature table
all(rownames(meta) == rownames(feat_clr))
feat_clr$sample_name <- rownames(feat_clr) # add column sample_name
### merge metadata and feature table
metagen <- merge(meta, feat_clr, by = "sample_name", all.x = TRUE)
metagen <- metagen[,-1] # remove sample_name
# make sure names are syntactically valid
colnames(metagen) <- make.names(colnames(metagen))
###############################################################################
### BASELINE RANDOM FOREST MODEL - 5-FOLD CROSS-VALIDATION + 50 REPEATS ###
###############################################################################
# data to be used in the model
str(metagen)
# column names for features to be included in model (full predictor set)
all_feat_cols <- setdiff(colnames(metagen), "condition")
# create lists to store metrics
feature_importances <- list() # list to store feature importances
performance_metrics <- list() # list to store performance metrics
feature_frequencies <- list() # list to store feature selection frequencies
# repeat cross-validation 50 times
for (r in 1:50) {
cat("Repeat:", r, "\n")
# create 5-folds for cross-validation (stratified on condition)
set.seed(1234 + r*100)
folds <- createFolds(metagen$condition, k = 5, list = TRUE)
# loop through the folds
for (f in 1:5) {
# splits the dataset into training and testing sets for the current fold
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- metagen[-test_idx, ] # training data (all rows not in fold f)
test_data <- metagen[test_idx, ] # testing data (fold f)
# train random forest model
rf_model <- randomForest(x = train_data[, all_feat_cols],
y = as.factor(train_data$condition),
ntree = 500,
importance = TRUE)
# evaluate on test set
test_predictions <- predict(rf_model, newdata = test_data[, all_feat_cols], type = "response") # predicted class labels for cm
test_probabilities <- predict(rf_model, newdata = test_data[, all_feat_cols], type = "prob") # class probabilities (ROC/AUC)
# evaluate model on training set
train_predictions <- predict(rf_model, newdata = train_data[, all_feat_cols], type = "response")
train_probabilities <- predict(rf_model, newdata = train_data[, all_feat_cols], type = "prob")
# calculate AUC on test set
test_roc_obj <- roc(response = test_data$condition,
predictor = test_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
test_auc <- auc(test_roc_obj)
# store test ROC coordinates
test_roc_df <- data.frame(specificity = test_roc_obj$specificities,
sensitivity = test_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Test")
# calculate AUC on train set
train_roc_obj <- roc(response = train_data$condition,
predictor = train_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
train_auc <- auc(train_roc_obj)
# store train ROC coordinates
train_roc_df <- data.frame(specificity = train_roc_obj$specificities,
sensitivity = train_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Train")
# count how often each feature is used in the trees
tree_split_vars <- unlist(lapply(1:rf_model$ntree, function(t) {
tree <- getTree(rf_model, k = t, labelVar = TRUE)
as.character(tree$`split var`[tree$`split var` != "<leaf>"])
}))
# count the occurrences of each feature
split_counts <- table(tree_split_vars)
# generate confusion matrices
test_cm <- confusionMatrix(test_predictions, as.factor(test_data$condition), positive = "disease")
train_cm <- confusionMatrix(train_predictions, as.factor(train_data$condition), positive = "disease")
### store with repeat (r) and fold (f) index
key <- paste0("Repeat_", r, "_Fold_", f)
feature_frequencies[[key]] <- as.data.frame(split_counts) # store feature frequencies
performance_metrics[[key]] <- list(test_cm = test_cm, test_auc = test_auc,
train_cm = train_cm, train_auc = train_auc,
test_roc_df = test_roc_df, train_roc_df = train_roc_df) # store performance metrics (test and train)
feature_importances[[key]] <- importance(rf_model) # store feature importances
}
}
### calculate feature frequencies and relative frequency of feature selection
feature_split_summary <- bind_rows(feature_frequencies, .id = "Repeat_Fold") %>%
rename(Feature = tree_split_vars) %>%
group_by(Feature) %>% # group stability metrics by feature
summarise(total_count = sum(Freq, na.rm = TRUE),
mean_count = mean(Freq, na.rm = TRUE),
n_models = n()) %>%
mutate(prop_models = n_models / length(feature_frequencies),
avg_per_tree = total_count / (length(feature_frequencies) * rf_model$ntree)) %>%
arrange(desc(total_count))
head(as.data.frame(feature_split_summary), 20)
# plot total number of models where feature was used at least once
ggplot(feature_split_summary[1:30, ], aes(x = reorder(Feature, total_count), y = n_models)) +
geom_col(fill = "steelblue") + coord_flip() + theme_minimal() +
labs(title = "Top 30 most frequently selected features - models",
x = "Feature", y = "Number of models")
# plot average number of times feature was used in a split per tree (across all models)
ggplot(feature_split_summary[1:30, ], aes(x = reorder(Feature, total_count), y = avg_per_tree)) +
geom_col(fill = "steelblue") + coord_flip() + theme_minimal() +
labs(title = "Top 30 most frequently selected features - splits",
x = "Feature", y = "Average splits per tree")
### calculate feature importances
# combine all feature_importances data.frames into one data.frame
all_features_importances <- do.call(rbind, lapply(names(feature_importances), function(name) {
df <- as.data.frame(feature_importances[[name]])
df$Feature <- rownames(df)
df$Repeat_Fold <- name
return(df)
}))
# group importance metrics by feature and sort by overall importance
mean_importance <- all_features_importances %>%
group_by(Feature) %>%
summarise(mean_healthy = mean(healthy, na.rm = TRUE),
mean_disease = mean(disease, na.rm = TRUE),
mean_MeanDecreaseAccuracy = mean(MeanDecreaseAccuracy, na.rm = TRUE),
mean_MeanDecreaseGini = mean(MeanDecreaseGini, na.rm = TRUE)) %>%
arrange(desc(mean_MeanDecreaseAccuracy))
head(mean_importance, 20)
### plot species with highest MeanDecreaseAccuracy
ggplot(metagen, aes(x = Lachnoclostridium_sp._YL32)) +
geom_density(aes(fill = condition), alpha = 0.5) +
labs(title = "Abundance of discriminative species",
subtitle = "Lachnoclostridium sp. YL32",
x = "Abundance", y = "Density of Samples", fill = "Condition") +
theme_minimal()
### plot split frequency versus feature importance
# top 20 features by split frequency
top_features <- feature_split_summary %>%
arrange(desc(avg_per_tree)) %>%
slice(1:20) # top 20 features by split frequency
# merge with mean_importance data.frame
top_features_importance <- top_features %>%
left_join(mean_importance, by = c("Feature"))
# plot meanMDA versus split frequency
ggplot(top_features_importance, aes(x = avg_per_tree, y = mean_MeanDecreaseAccuracy, label = Feature)) +
geom_point(color = "steelblue", size = 3) + geom_text_repel(size = 3, max.overlaps = 8) + theme_minimal() +
labs(x = "Split frequency", y = "Mean MDA",
title = "Split frequency versus permutation importance")
# long data.frame for plotting importance by condition
top_features_long <- top_features_importance %>%
select(Feature, avg_per_tree, mean_healthy, mean_disease) %>%
pivot_longer(cols = c(mean_healthy, mean_disease),
names_to = "Condition",
values_to = "Importance") %>%
mutate(Condition = recode(Condition,
mean_healthy = "Healthy",
mean_disease = "Disease"))
# plot meanMDA by condition versus split frequency
ggplot(top_features_long, aes(x = avg_per_tree, y = Importance, color = Condition)) +
geom_point(size = 3, alpha = 0.7) + theme_minimal() +
labs(x = "Split frequency", y = "Mean MDA by condition",
title = "Split frequency versus permutation importance by condition", color = "Condition") +
scale_color_manual(values = c("Healthy" = "steelblue", "Disease" = "indianred3"))
### calculate performance statistics
perf_stats <- function(performance_metrics, type = c("test", "train", "gap")) {
# match type argument
type <- match.arg(type)
# create vectors to store metrics - test
test_balanced_accuracy <- numeric()
test_f1_score <- numeric()
test_sensitivity <- numeric()
test_specificity <- numeric()
test_auc_vals <- numeric()
# create vectors to store metrics - train
train_balanced_accuracy <- numeric()
train_f1_score <- numeric()
train_sensitivity <- numeric()
train_specificity <- numeric()
train_auc_vals <- numeric()
# extract metrics from the stored confusion matrices
for (perf in performance_metrics) {
test_cm <- perf$test_cm
test_auc_val <- as.numeric(perf$test_auc[])
train_cm <- perf$train_cm
train_auc_val <- as.numeric(perf$train_auc[])
# confusion matrix metrics and auc (test)
test_balanced_accuracy <- c(test_balanced_accuracy, test_cm$byClass["Balanced Accuracy"])
test_f1_score <- c(test_f1_score, test_cm$byClass["F1"])
test_sensitivity <- c(test_sensitivity, test_cm$byClass["Sensitivity"])
test_specificity <- c(test_specificity, test_cm$byClass["Specificity"])
test_auc_vals <- c(test_auc_vals, test_auc_val)
# confusion matrix metrics and auc (train)
train_balanced_accuracy <- c(train_balanced_accuracy, train_cm$byClass["Balanced Accuracy"])
train_f1_score <- c(train_f1_score, train_cm$byClass["F1"])
train_sensitivity <- c(train_sensitivity, train_cm$byClass["Sensitivity"])
train_specificity <- c(train_specificity, train_cm$byClass["Specificity"])
train_auc_vals <- c(train_auc_vals, train_auc_val)
}
# test metric summary
test_metric_summary <- data.frame(mean_bal_acc = mean(test_balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(test_balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(test_f1_score, na.rm = TRUE),
sd_f1 = sd(test_f1_score, na.rm = TRUE),
mean_sens = mean(test_sensitivity, na.rm = TRUE),
sd_sens = sd(test_sensitivity, na.rm = TRUE),
mean_spec = mean(test_specificity, na.rm = TRUE),
sd_spec = sd(test_specificity, na.rm = TRUE),
mean_auc = mean(test_auc_vals, na.rm = TRUE),
sd_auc = sd(test_auc_vals, na.rm = TRUE))
# train metric summary
train_metric_summary <- data.frame(mean_bal_acc = mean(train_balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(train_balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(train_f1_score, na.rm = TRUE),
sd_f1 = sd(train_f1_score, na.rm = TRUE),
mean_sens = mean(train_sensitivity, na.rm = TRUE),
sd_sens = sd(train_sensitivity, na.rm = TRUE),
mean_spec = mean(train_specificity, na.rm = TRUE),
sd_spec = sd(train_specificity, na.rm = TRUE),
mean_auc = mean(train_auc_vals, na.rm = TRUE),
sd_auc = sd(train_auc_vals, na.rm = TRUE))
# gap metric summary
gap_metric_summary <- data.frame(mean_bal_acc = mean(train_balanced_accuracy - test_balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(train_balanced_accuracy - test_balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(train_f1_score - test_f1_score, na.rm = TRUE),
sd_f1 = sd(train_f1_score - test_f1_score, na.rm = TRUE),
mean_sens = mean(train_sensitivity - test_sensitivity, na.rm = TRUE),
sd_sens = sd(train_sensitivity - test_sensitivity, na.rm = TRUE),
mean_spec = mean(train_specificity - test_specificity, na.rm = TRUE),
sd_spec = sd(train_specificity - test_specificity, na.rm = TRUE),
mean_auc = mean(train_auc_vals - test_auc_vals, na.rm = TRUE),
sd_auc = sd(train_auc_vals - test_auc_vals, na.rm = TRUE))
# summary to return
result <- switch(type, "test" = test_metric_summary,
"train" = train_metric_summary,
"gap" = gap_metric_summary)
return(result)
}
perf_stats(performance_metrics, type = "test")
perf_stats(performance_metrics, type = "train")
perf_stats(performance_metrics, type = "gap")
### plot average ROC curve across folds
plot_roc <- function(performance_metrics) {
# combine train and test ROC data frames
all_roc_curves <- bind_rows(lapply(performance_metrics, function(x) bind_rows(x$train_roc_df, x$test_roc_df)))
# compute average ROC curves for train and test set
fpr_grid <- seq(0, 1, length.out = 100)
interp_roc <- all_roc_curves %>%
group_by(Set, Repeat, Fold) %>%
reframe(tpr_interp = approx(1 - specificity, sensitivity, xout = fpr_grid, ties = mean)$y,
.groups = "drop") %>%
mutate(fpr = rep(fpr_grid, times = n() / length(fpr_grid)))
mean_roc <- interp_roc %>%
group_by(Set, fpr) %>%
summarise(mean_tpr = mean(tpr_interp, na.rm = TRUE),
lower_tpr = quantile(tpr_interp, 0.025, na.rm = TRUE),
upper_tpr = quantile(tpr_interp, 0.975, na.rm = TRUE),
.groups = "drop")
# plot train and test ROC curves
p <- ggplot(mean_roc, aes(x = fpr, y = mean_tpr, color = Set, fill = Set)) +
geom_line(linewidth = 1.2) + coord_equal() + theme_minimal() +
geom_ribbon(aes(ymin = lower_tpr, ymax = upper_tpr), alpha = 0.2, color = NA) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "gray50") +
scale_color_manual(values = c("Train" = "indianred3", "Test" = "steelblue")) +
scale_fill_manual(values = c("Train" = "indianred3", "Test" = "steelblue")) +
labs(title = "Average ROC curves across CV folds",
x = "False positive rate (1 - specificity)", y = "True positive rate (sensitivity)",
color = "Dataset", fill = "Dataset")
return(p)
}
plot_roc(performance_metrics)
##################################################################
### RANDOM FOREST - OPTIMAL HYPERPARAMETER VALUES - CLASSWT ###
##################################################################
# data to be used in the model
str(metagen)
# column names for features to be included in model
subset_feat_cols <- setdiff(colnames(metagen), "condition")
# create list of class weight settings
weight_grid <- list(healthy = c(healthy = 2, disease = 1),
equal = c(healthy = 1, disease = 1),
disease = c(healthy = 1, disease = 2))
# create list to store performance metrics
performance_metrics <- list() # list to store performance metrics
# loop through class weight
for (i in names(weight_grid)) {
classwt <- weight_grid[[i]]
cat("Class weight:", i, "\n")
# repeat cross-validation 50 times
for (r in 1:50) {
cat("Repeat:", r, "\n")
set.seed(1234 + r*100)
# create 5-folds for cross-validation (stratified on condition)
folds <- createFolds(metagen$condition, k = 5, list = TRUE)
# loop through the folds
for (f in 1:5) {
# splits the dataset into training and testing sets for the current fold
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- metagen[-test_idx, ] # training data (all rows not in fold f)
test_data <- metagen[test_idx, ] # testing data (fold f)
# train random forest model using full features to rank features
rf_model <- randomForest(x = train_data[, subset_feat_cols],
y = as.factor(train_data$condition),
ntree = 500,
importance = TRUE,
classwt = classwt)
# evaluate on test set
test_predictions <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "response") # predicted class labels for cm
test_probabilities <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "prob") # class probabilities (ROC/AUC)
# evaluate model on training set
train_predictions <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "response")
train_probabilities <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "prob")
# calculate AUC on test set
test_roc_obj <- roc(response = test_data$condition,
predictor = test_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
test_auc <- auc(test_roc_obj)
# store test ROC coordinates
test_roc_df <- data.frame(specificity = test_roc_obj$specificities,
sensitivity = test_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Test")
# calculate AUC on train set
train_roc_obj <- roc(response = train_data$condition,
predictor = train_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
train_auc <- auc(train_roc_obj)
# store train ROC coordinates
train_roc_df <- data.frame(specificity = train_roc_obj$specificities,
sensitivity = train_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Train")
# generate confusion matrices
test_cm <- confusionMatrix(test_predictions, as.factor(test_data$condition), positive = "disease")
train_cm <- confusionMatrix(train_predictions, as.factor(train_data$condition), positive = "disease")
### store with repeat (r) and fold (f) index
key <- paste0("classwt", i, "_Repeat_", r, "_Fold_", f)
performance_metrics[[key]] <- list(test_cm = test_cm, test_auc = test_auc,
train_cm = train_cm, train_auc = train_auc,
test_roc_df = test_roc_df, train_roc_df = train_roc_df,
param_value = i) # store performance metrics (test and train)
}
}
}
### calculate performance statistics
grid_perf_stats <- function(performance_metrics, type = c("test", "train", "gap")) {
# match type argument
type <- match.arg(type)
# get unique hyperparameter values
param_values <- unique(sapply(performance_metrics, function(x) x$param_value))
# initialize list to store summaries
summary_list <- list()
for (i in param_values) {
# filter metrics for this class weight
perf_subset <- performance_metrics[sapply(performance_metrics, function(x) x$param_value == i)]
# create vectors to store metrics - test
test_balanced_accuracy <- numeric()
test_f1_score <- numeric()
test_sensitivity <- numeric()
test_specificity <- numeric()
test_auc_vals <- numeric()
# create vectors to store metrics - train
train_balanced_accuracy <- numeric()
train_f1_score <- numeric()
train_sensitivity <- numeric()
train_specificity <- numeric()
train_auc_vals <- numeric()
# extract metrics from the stored confusion matrices
for (perf in perf_subset) {
test_cm <- perf$test_cm
test_auc_val <- as.numeric(perf$test_auc[])
train_cm <- perf$train_cm
train_auc_val <- as.numeric(perf$train_auc[])
# confusion matrix metrics and auc (test)
test_balanced_accuracy <- c(test_balanced_accuracy, test_cm$byClass["Balanced Accuracy"])
test_f1_score <- c(test_f1_score, test_cm$byClass["F1"])
test_sensitivity <- c(test_sensitivity, test_cm$byClass["Sensitivity"])
test_specificity <- c(test_specificity, test_cm$byClass["Specificity"])
test_auc_vals <- c(test_auc_vals, test_auc_val)
# confusion matrix metrics and auc (train)
train_balanced_accuracy <- c(train_balanced_accuracy, train_cm$byClass["Balanced Accuracy"])
train_f1_score <- c(train_f1_score, train_cm$byClass["F1"])
train_sensitivity <- c(train_sensitivity, train_cm$byClass["Sensitivity"])
train_specificity <- c(train_specificity, train_cm$byClass["Specificity"])
train_auc_vals <- c(train_auc_vals, train_auc_val)
}
# compute summary per type
if (type == "test") {
df <- data.frame(param_value = i,
mean_bal_acc = mean(test_balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(test_balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(test_f1_score, na.rm = TRUE),
sd_f1 = sd(test_f1_score, na.rm = TRUE),
mean_sens = mean(test_sensitivity, na.rm = TRUE),
sd_sens = sd(test_sensitivity, na.rm = TRUE),
mean_spec = mean(test_specificity, na.rm = TRUE),
sd_spec = sd(test_specificity, na.rm = TRUE),
mean_auc = mean(test_auc_vals, na.rm = TRUE),
sd_auc = sd(test_auc_vals, na.rm = TRUE))
} else if (type == "train") {
df <- data.frame(param_value = i,
mean_bal_acc = mean(train_balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(train_balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(train_f1_score, na.rm = TRUE),
sd_f1 = sd(train_f1_score, na.rm = TRUE),
mean_sens = mean(train_sensitivity, na.rm = TRUE),
sd_sens = sd(train_sensitivity, na.rm = TRUE),
mean_spec = mean(train_specificity, na.rm = TRUE),
sd_spec = sd(train_specificity, na.rm = TRUE),
mean_auc = mean(train_auc_vals, na.rm = TRUE),
sd_auc = sd(train_auc_vals, na.rm = TRUE))
} else if (type == "gap") {
df <- data.frame(param_value = i,
mean_bal_acc = mean(train_balanced_accuracy - test_balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(train_balanced_accuracy - test_balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(train_f1_score - test_f1_score, na.rm = TRUE),
sd_f1 = sd(train_f1_score - test_f1_score, na.rm = TRUE),
mean_sens = mean(train_sensitivity - test_sensitivity, na.rm = TRUE),
sd_sens = sd(train_sensitivity - test_sensitivity, na.rm = TRUE),
mean_spec = mean(train_specificity - test_specificity, na.rm = TRUE),
sd_spec = sd(train_specificity - test_specificity, na.rm = TRUE),
mean_auc = mean(train_auc_vals - test_auc_vals, na.rm = TRUE),
sd_auc = sd(train_auc_vals - test_auc_vals, na.rm = TRUE))
}
summary_list[[i]] <- df
}
# combine all param value summaries
summary_df <- bind_rows(summary_list)
return(summary_df)
}
grid_perf_stats(performance_metrics, type = "test")
grid_perf_stats(performance_metrics, type = "train")
grid_perf_stats(performance_metrics, type = "gap")
### plot average ROC curve across folds
grid_plot_roc <- function(performance_metrics) {
# get unique hyperparameter values
param_values <- unique(sapply(performance_metrics, function(x) x$param_value))
# function to compute mean ROC per hyperparameter value
mean_roc_per_param <- function(param_val) {
# filter performance metrics by this hyperparameter value
perf_subset <- performance_metrics[sapply(performance_metrics, function(x) x$param_value == param_val)]
# combine train and test ROC data frames
all_roc_curves <- bind_rows(lapply(perf_subset, function(x) bind_rows(x$train_roc_df, x$test_roc_df)))
fpr_grid <- seq(0, 1, length.out = 100)
interp_roc <- all_roc_curves %>%
group_by(Set, Repeat, Fold) %>%
reframe(tpr_interp = approx(1 - specificity, sensitivity, xout = fpr_grid, ties = mean)$y,
.groups = "drop") %>%
mutate(fpr = rep(fpr_grid, times = n() / length(fpr_grid)))
# compute mean and 95% CI
mean_roc <- interp_roc %>%
group_by(Set, fpr) %>%
summarise(mean_tpr = mean(tpr_interp, na.rm = TRUE),
lower_tpr = quantile(tpr_interp, 0.025, na.rm = TRUE),
upper_tpr = quantile(tpr_interp, 0.975, na.rm = TRUE),
.groups = "drop") %>%
mutate(param_value = param_val)
return(mean_roc)
}
# compute mean ROC for all hyperparameter values
roc_list <- lapply(param_values, mean_roc_per_param)
roc_df <- bind_rows(roc_list)
# plot train and test ROC curves
p <- ggplot(roc_df, aes(x = fpr, y = mean_tpr, color = Set, fill = Set)) +
geom_line(linewidth = 0.5) + coord_equal() + theme_minimal() +
facet_wrap(~ param_value, ncol = 2, nrow = 3) +
geom_ribbon(aes(ymin = lower_tpr, ymax = upper_tpr), alpha = 0.2, color = NA) +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "gray50") +
scale_color_manual(values = c("Train" = "indianred3", "Test" = "steelblue")) +
scale_fill_manual(values = c("Train" = "indianred3", "Test" = "steelblue")) +
labs(title = "Average ROC curves across CV folds",
x = "False positive rate (1 - specificity)", y = "True positive rate (sensitivity)",
color = "Dataset", fill = "Dataset")
return(p)
}
grid_plot_roc(performance_metrics)
################################################################
### RANDOM FOREST - OPTIMAL HYPERPARAMETER VALUES - NTREE ###
################################################################
# data to be used in the model
str(metagen)
# column names for features to be included in model
subset_feat_cols <- setdiff(colnames(metagen), "condition")
# ntree values to test
ntree_values <- c(125, 250, 500, 1000, 2000)
# create list to store performance metrics
performance_metrics <- list() # list to store performance metrics
# loop through ntree values
for (i in ntree_values) {
cat("ntree:", i, "\n")
# repeat cross-validation 50 times
for (r in 1:50) {
cat("Repeat:", r, "\n")
set.seed(1234 + r*100)
# create 5-folds for cross-validation (stratified on condition)
folds <- createFolds(metagen$condition, k = 5, list = TRUE)
# loop through the folds
for (f in 1:5) {
# splits the dataset into training and testing sets for the current fold
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- metagen[-test_idx, ] # training data (all rows not in fold f)
test_data <- metagen[test_idx, ] # testing data (fold f)
# train random forest model using full features to rank features
rf_model <- randomForest(x = train_data[, subset_feat_cols],
y = as.factor(train_data$condition),
ntree = i,
importance = TRUE)
# evaluate on test set
test_predictions <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "response") # predicted class labels for cm
test_probabilities <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "prob") # class probabilities (ROC/AUC)
# evaluate model on training set
train_predictions <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "response")
train_probabilities <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "prob")
# calculate AUC on test set
test_roc_obj <- roc(response = test_data$condition,
predictor = test_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
test_auc <- auc(test_roc_obj)
# store test ROC coordinates
test_roc_df <- data.frame(specificity = test_roc_obj$specificities,
sensitivity = test_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Test")
# calculate AUC on train set
train_roc_obj <- roc(response = train_data$condition,
predictor = train_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
train_auc <- auc(train_roc_obj)
# store train ROC coordinates
train_roc_df <- data.frame(specificity = train_roc_obj$specificities,
sensitivity = train_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Train")
# generate confusion matrices
test_cm <- confusionMatrix(test_predictions, as.factor(test_data$condition), positive = "disease")
train_cm <- confusionMatrix(train_predictions, as.factor(train_data$condition), positive = "disease")
### store with repeat (r) and fold (f) index
key <- paste0("ntree_", i, "_Repeat_", r, "_Fold_", f)
performance_metrics[[key]] <- list(test_cm = test_cm, test_auc = test_auc,
train_cm = train_cm, train_auc = train_auc,
test_roc_df = test_roc_df, train_roc_df = train_roc_df,
param_value = i) # store performance metrics (test and train)
}
}
}
### calculate performance statistics
grid_perf_stats(performance_metrics, type = "test")
grid_perf_stats(performance_metrics, type = "train")
grid_perf_stats(performance_metrics, type = "gap")
### plot average ROC curve across folds
grid_plot_roc(performance_metrics)
###############################################################
### RANDOM FOREST - OPTIMAL HYPERPARAMETER VALUES - MTRY ###
###############################################################
# data to be used in the model
str(metagen)
# column names for features to be included in model (full predictor set)
subset_feat_cols <- setdiff(colnames(metagen), "condition")
# mtry values to test
mtry_values <- c(1, 2, 3, 4, 5, 6)
# create list to store performance metrics
performance_metrics <- list() # list to store performance metrics
# loop through mtry values
for (i in mtry_values) {
cat("mtry:", i, "\n")
# repeat cross-validation 50 times
for (r in 1:50) {
cat("Repeat:", r, "\n")
set.seed(1234 + r*100)
# create 5-folds for cross-validation (stratified on condition)
folds <- createFolds(metagen$condition, k = 5, list = TRUE)
# loop through the folds
for (f in 1:5) {
# splits the dataset into training and testing sets for the current fold
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- metagen[-test_idx, ] # training data (all rows not in fold f)
test_data <- metagen[test_idx, ] # testing data (fold f)
# train random forest model using full features to rank features
rf_model <- randomForest(x = train_data[, subset_feat_cols],
y = as.factor(train_data$condition),
ntree = 500,
importance = TRUE,
mtry = i)
# evaluate on test set
test_predictions <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "response") # predicted class labels for cm
test_probabilities <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "prob") # class probabilities (ROC/AUC)
# evaluate model on training set
train_predictions <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "response")
train_probabilities <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "prob")
# calculate AUC on test set
test_roc_obj <- roc(response = test_data$condition,
predictor = test_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
test_auc <- auc(test_roc_obj)
# store test ROC coordinates
test_roc_df <- data.frame(specificity = test_roc_obj$specificities,
sensitivity = test_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Test")
# calculate AUC on train set
train_roc_obj <- roc(response = train_data$condition,
predictor = train_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
train_auc <- auc(train_roc_obj)
# store train ROC coordinates
train_roc_df <- data.frame(specificity = train_roc_obj$specificities,
sensitivity = train_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Train")
# generate confusion matrices
test_cm <- confusionMatrix(test_predictions, as.factor(test_data$condition), positive = "disease")
train_cm <- confusionMatrix(train_predictions, as.factor(train_data$condition), positive = "disease")
### store with repeat (r) and fold (f) index
key <- paste0("mtry_", i, "_Repeat_", r, "_Fold_", f)
performance_metrics[[key]] <- list(test_cm = test_cm, test_auc = test_auc,
train_cm = train_cm, train_auc = train_auc,
test_roc_df = test_roc_df, train_roc_df = train_roc_df,
param_value = i) # store performance metrics (test and train)
}
}
}
### calculate performance statistics
grid_perf_stats(performance_metrics, type = "test")
grid_perf_stats(performance_metrics, type = "train")
grid_perf_stats(performance_metrics, type = "gap")
### plot average ROC curve across folds
grid_plot_roc(performance_metrics)
###################################################################
### RANDOM FOREST - OPTIMAL HYPERPARAMETER VALUES - NODESIZE ###
###################################################################
# data to be used in the model
str(metagen)
# column names for features to be included in model (full predictor set)
subset_feat_cols <- setdiff(colnames(metagen), "condition")
# nodesize values to test
nodesize_values <- c(1, 2, 3, 4, 5, 6)
# create list to store performance metrics
performance_metrics <- list() # list to store performance metrics
# loop through nodesize values
for (i in nodesize_values) {
cat("nodesize:", i, "\n")
# repeat cross-validation 50 times
for (r in 1:50) {
cat("Repeat:", r, "\n")
set.seed(1234 + r*100)
# create 5-folds for cross-validation (stratified on condition)
folds <- createFolds(metagen$condition, k = 5, list = TRUE)
# loop through the folds
for (f in 1:5) {
# splits the dataset into training and testing sets for the current fold
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- metagen[-test_idx, ] # training data (all rows not in fold f)
test_data <- metagen[test_idx, ] # testing data (fold f)
# train random forest model using full features to rank features
rf_model <- randomForest(x = train_data[, subset_feat_cols],
y = as.factor(train_data$condition),
ntree = 500,
importance = TRUE,
nodesize = i)
# evaluate on test set
test_predictions <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "response") # predicted class labels for cm
test_probabilities <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "prob") # class probabilities (ROC/AUC)
# evaluate model on training set
train_predictions <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "response")
train_probabilities <- predict(rf_model, newdata = train_data[, subset_feat_cols], type = "prob")
# calculate AUC on test set
test_roc_obj <- roc(response = test_data$condition,
predictor = test_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
test_auc <- auc(test_roc_obj)
# store test ROC coordinates
test_roc_df <- data.frame(specificity = test_roc_obj$specificities,
sensitivity = test_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Test")
# calculate AUC on train set
train_roc_obj <- roc(response = train_data$condition,
predictor = train_probabilities[, "disease"],
levels = c("healthy", "disease"),
direction = "<")
train_auc <- auc(train_roc_obj)
# store train ROC coordinates
train_roc_df <- data.frame(specificity = train_roc_obj$specificities,
sensitivity = train_roc_obj$sensitivities,
Repeat = r, Fold = f, Set = "Train")
# generate confusion matrices
test_cm <- confusionMatrix(test_predictions, as.factor(test_data$condition), positive = "disease")
train_cm <- confusionMatrix(train_predictions, as.factor(train_data$condition), positive = "disease")
### store with repeat (r) and fold (f) index
key <- paste0("nodesize_", i, "_Repeat_", r, "_Fold_", f)
performance_metrics[[key]] <- list(test_cm = test_cm, test_auc = test_auc,
train_cm = train_cm, train_auc = train_auc,
test_roc_df = test_roc_df, train_roc_df = train_roc_df,
param_value = i) # store performance metrics (test and train)
}
}
}
### calculate performance statistics
grid_perf_stats(performance_metrics, type = "test")
grid_perf_stats(performance_metrics, type = "train")
grid_perf_stats(performance_metrics, type = "gap")
### plot average ROC curve across folds
grid_plot_roc(performance_metrics)
###########################################################################################################
######## RANDOM FOREST - BAYESIAN OPTIMIZATION OF HYPERPARAMETERS - PARALLELIZATION OF BAYES OPT #######
###########################################################################################################
# data to be used in the model
str(metagen)
# column names for features to be included in model
subset_feat_cols <- setdiff(colnames(metagen), "condition")
# create list of class weight settings
weight_grid <- list(healthy = c(healthy = 2, disease = 1),
equal = c(healthy = 1, disease = 1),
disease = c(healthy = 1, disease = 2))
# define the set of categorical labels with numeric indices
label_keys <- c("healthy", "equal", "disease")
# scoring function
scoring_function <- function(mtry, ntree, nodesize, classwt_label) {
# set seed
set.seed(1234)
# parameters
mtry <- as.integer(mtry)
ntree <- as.integer(ntree)
nodesize <- as.integer(nodesize)
# convert numeric index of classwt_label back to character label for scoring function
classwt_label <- as.integer(classwt_label)
label_str <- label_keys[classwt_label]
classwt <- weight_grid[[label_str]]
repeats <- 10
repeat_auc <- numeric(repeats)
# loop over each repeat
for (r in 1:repeats) {
# create 5-folds for cross-validation (stratified on condition)
folds <- caret::createFolds(metagen$condition, k = 5, list = TRUE, returnTrain = FALSE)
fold_aucs <- numeric(length(folds))
# loop through the folds
for (f in seq_along(folds)) {
# splits the dataset into training and testing sets for the current fold
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- metagen[-test_idx, ] # training data (all rows not in fold f)
test_data <- metagen[test_idx, ] # testing data (fold f)
# train random forest model using full features to rank features
rf_model <- randomForest(x = train_data[, subset_feat_cols],
y = as.factor(train_data$condition),
mtry = mtry,
ntree = ntree,
nodesize = nodesize,
classwt = classwt,
importance = TRUE)
# evaluate on test set
probabilities <- predict(rf_model, newdata = test_data[, subset_feat_cols], type = "prob") # class probabilities (ROC/AUC)
# calculate AUC
roc_obj <- tryCatch({
roc(response = test_data$condition,
predictor = probabilities[, "disease"],
levels = c("healthy", "disease"),