-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathML_random_forest_stratified.R
More file actions
1196 lines (954 loc) · 52.7 KB
/
ML_random_forest_stratified.R
File metadata and controls
1196 lines (954 loc) · 52.7 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 - Stratification by Metadata Variables
# load libraries
library(curatedMetagenomicData)
library(ggplot2)
library(tidyverse)
library(randomForest)
library(caret)
library(vegan)
library(mice)
library(e1071)
library(VennDiagram)
# set.seed
set.seed(1234)
# setwd
setwd("/Users/kristinvandenham/kmvanden/RStudio/")
### load data from curatedMetagenomicData
ibdmdb <- curatedMetagenomicData("2021-10-14.HMP_2019_ibdmdb.relative_abundance", dryrun = FALSE, counts = TRUE, rownames = "short")
ibd <- ibdmdb[[1]]
str(ibd)
### METADATA
# extract metadata
ibd_meta <- colData(ibd)
ibd_meta <- as.data.frame(ibd_meta)
ibd_meta$sample_id <- rownames(ibd_meta)
# keep only one sample from the first visit for each subject
table(ibd_meta$visit_number)
length(unique(ibd_meta$subject_id))
ibd_meta_first <- ibd_meta %>%
filter(visit_number == 1) # only keep samples from the first visit
ibd_meta_filt <- ibd_meta_first %>%
group_by(subject_id) %>%
filter(n() == 1 | grepl("_P$", sample_id)) %>%
ungroup() # only keep one sample per subject from the first visit
ibd_meta_filt <- as.data.frame(ibd_meta_filt)
rownames(ibd_meta_filt) <- ibd_meta_filt$sample_id
head(ibd_meta_filt)
# remove metadata columns that only have one value
ibd_meta_filt <- ibd_meta_filt[, sapply(ibd_meta_filt, function(col) length(unique(col)) > 1)]
# remove metadata categories that won't be used in model fitting
# study_condition == disease
ibd_meta_filt <- ibd_meta_filt[, !(colnames(ibd_meta_filt) %in% c("study_condition", "PMID", "number_reads",
"number_bases", "minimum_read_length",
"median_read_length", "sample_id",
"age_category", "subject_id"))]
# change NAs to "healthy" in disease_subtype
ibd_meta_filt$disease_subtype[is.na(ibd_meta_filt$disease_subtype)] <- "healthy"
# shorten column name
colnames(ibd_meta_filt)[which(colnames(ibd_meta_filt) == "antibiotics_current_use")] <- "antibiotics"
# format variables correctly for modeling (as factor or numeric)
head(ibd_meta_filt)
ibd_meta_filt <- ibd_meta_filt %>%
mutate(across(c(antibiotics, disease, gender, location, disease_subtype), as.factor)) # change variables to factors
ibd_meta_filt$age <- as.numeric(ibd_meta_filt$age) # change variable to numeric
str(ibd_meta_filt)
# add sample name column to metadata
ibd_meta_filt$sample_name <- rownames(ibd_meta_filt)
### FEATURE TABLE
# extract feature table
ibd_feat <- assay(ibd, "relative_abundance")
ibd_feat <- as.data.frame(ibd_feat)
# format rownames
rownames(ibd_feat)[1:10]
rownames(ibd_feat) <- rownames(ibd_feat) %>%
sub("^species:", "", .) %>%
gsub("\\[|\\]", "", .) %>%
gsub(" sp\\. ", "_", .) %>%
gsub(" ", "_", .) %>%
gsub(":", "_", .)
rownames(ibd_feat)[1:10]
# subset feature table to samples that were retained in the metadata (one sample per subject)
dim(ibd_feat) # 585 1627
all(rownames(ibd_meta_filt) %in% colnames(ibd_feat))
ibd_feat_filt <- ibd_feat[, colnames(ibd_feat) %in% rownames(ibd_meta_filt)]
all(colnames(ibd_feat_filt) == rownames(ibd_meta_filt)) # column names of feature data should exactly match rownames of metadata
dim(ibd_feat_filt) # 585 130 (from 1627 samples to 130 --> one sample for each subject)
# convert feature table to relative abundances
ibd_feat_rel <- sweep(ibd_feat_filt, 2, colSums(ibd_feat_filt), FUN = "/")
ibd_feat_rel <- as.data.frame(ibd_feat_rel)
### add pseudocount and perform log-transform
log_n0 <- 1e-6 # pseudocount
ibd_feat_log <- t(ibd_feat_rel) # transpose feature table
ibd_feat_log <- log(ibd_feat_log + log_n0)
ibd_feat_log <- as.data.frame(ibd_feat_log)
# perform row-wise L2 normalization (SIAMCAT)
n_p <- 2 # L2 norm
ibd_row_norms <- sqrt(rowSums(ibd_feat_log^n_p))
ibd_feat_lognorm <- sweep(ibd_feat_log, 1, ibd_row_norms, FUN = "/")
ibd_feat <- as.data.frame(ibd_feat_lognorm)
# rownames of metadata need to match the rownames of the feature table
all(rownames(ibd_meta_filt) == rownames(ibd_feat))
ibd_feat$sample_name <- rownames(ibd_feat) # add sample_name column to feature table
### merge metadata and feature table
ibd_merge <- merge(ibd_meta_filt, ibd_feat, by = "sample_name", all.x = TRUE)
ibd_merge <- ibd_merge[,-1] # remove sample_name
ibd_merge[1:10, 1:10]
############################################
### HANDLING MISSING METADATA VALUES ###
############################################
### MISSING VALUES: BMI
# over 1/3 of samples do not have a BMI measurement
sum(is.na(ibd_merge$BMI))/length(ibd_merge$BMI) # 0.3692308
# create column indicating whether BMI measurement is present
ibd_merge$BMI_avail <- !is.na(ibd_merge$BMI)
### BMI_avail significantly associated with other metadata variables
# antibiotics
table(ibd_merge$antibiotics, ibd_merge$BMI_avail)
chisq.test(table(ibd_merge$antibiotics, ibd_merge$BMI_avail)) # p-value = 1
# disease
table(ibd_merge$disease, ibd_merge$BMI_avail)
chisq.test(table(ibd_merge$disease, ibd_merge$BMI_avail)) # p-value = 0.2686
# age
t.test(age ~ BMI_avail, data = ibd_merge) # p-value = 0.3145
# gender
table(ibd_merge$gender, ibd_merge$BMI_avail)
chisq.test(table(ibd_merge$gender, ibd_merge$BMI_avail)) # p-value = 0.9621
# location
table_location <- table(ibd_merge$location, ibd_merge$BMI_avail)
fisher.test(table_location) # p-value = 0.0001104
# disease subtype
table_disease_subtype <- table(ibd_merge$disease_subtype, ibd_merge$BMI_avail)
fisher.test(table_disease_subtype) # p-value = 0.3981
### BMI_avail is significantly associated with location (but not other metadata variables)
### BMI_avail significantly associated with microbiome structure
# feature table should only include microbiome features
ibd_feat_adonis <- ibd_feat # use transposed feature table used in merge
ibd_feat_adonis <- ibd_feat_adonis[,-586] # removed sample_name
# metadata should only contain metadata
ibd_meta_adonis <- ibd_meta_filt[, -8] # remove sample name
ibd_meta_adonis$BMI_avail <- ibd_merge$BMI_avail # add BMI_avail
# rownames need to match
all(rownames(ibd_feat_adonis) == rownames(ibd_meta_adonis))
# PERMANOVA using euclidean method (to handle the log unit normalization)
adonis2(ibd_feat_adonis ~ BMI_avail, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.00766 | p-value: 0.435
### BMI_avail is not significantly associated with the microbiome structure
### remove BMI as a metadata variable
ibd_merge <- ibd_merge[, -c(6, 593)] # remove BMI and BMI_avail from merged data.frame (to be used in modeling)
ibd_meta_adonis <- ibd_meta_adonis[, -c(6, 8)] # remove BMI and BMI_avail from ibd_meta_adonis (used for PERMANOVA)
### MISSING VALUES: AGE
# missing metadata values for age (<5% of samples don't have a value for age)
sum(is.na(ibd_merge$age))/length(ibd_merge$age) # 0.04615385
### impute missing values using MICE
# subset metadata columns for imputation (age + variables that could help impute age values)
meta_impute <- ibd_merge[, c("age", "antibiotics", "disease", "gender", "location", "disease_subtype")]
# impute age values using MICE and pmm method (predictive mean matching for numeric variables)
imputed_data <- mice(meta_impute, m = 50, method = "pmm", maxit = 10, seed = 123)
# run linear regression on each imputed dataset and pool results
fit <- with(imputed_data, lm(age ~ antibiotics + disease + gender + location + disease_subtype))
pooled_results <- pool(fit)
pooled_results # check pooled results
# extract completed datasets into a list
imputed_list <- lapply(1:50, function(i) mice::complete(imputed_data, i))
# average imputed ages across all imputations
age_matrix <- sapply(imputed_list, function(df) df$age)
mean_imputed_age <- rowMeans(age_matrix)
mean_imputed_age <- round(mean_imputed_age)
# replace age with age_imputed (NAs in age column replaced by average imputed age values)
ibd_merge$age <- mean_imputed_age
colnames(ibd_merge)[colnames(ibd_merge) == "age"] <- "age_imputed" # change name to age_imputed
ibd_meta_adonis$age <- mean_imputed_age
colnames(ibd_meta_adonis)[colnames(ibd_meta_adonis) == "age"] <- "age_imputed" # change name to age_imputed
##########################################
### CHECKING METADATA ASSOCIATIONS ###
##########################################
# identify and account for confounders
### are metadata variables associated with the microbiome structure
# ibd_feat_adonis (feature data (numeric))
# ibd_meta_adonis (metadata variables (antibiotics, disease, age, gender, location, disease_subtype and age_imputed)
all(rownames(ibd_feat_adonis) == rownames(ibd_meta_adonis)) # rownames (sample_ids need to match)
# antibiotics
adonis2(ibd_feat_adonis ~ antibiotics, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.00949 | p-value = 0.158
# imputed age
adonis2(ibd_feat_adonis ~ age_imputed, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.01484 | p-value = 0.019
# gender
adonis2(ibd_feat_adonis ~ gender, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.01642 | 0.006
# location
adonis2(ibd_feat_adonis ~ location, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.02813 | p-value = 0.094
# disease
adonis2(ibd_feat_adonis ~ disease, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.01153 | p-value = 0.054
# disease_subtype
adonis2(ibd_feat_adonis ~ disease_subtype, data = ibd_meta_adonis, method = "euclidean") # R2 = 0.02124 | p-value = 0.049
### use disease as label for modeling
# perform subgroup analysis with disease_subtype later
### are metadata variables significantly different between healthy and IBD patients
# ibd_meta_adonis: contains only the metadata values (not the features)
# imputed age
kruskal.test(age_imputed ~ disease, data = ibd_meta_adonis) # p-value = 0.9519
# antibiotics
fisher.test(table(ibd_meta_adonis$antibiotics, ibd_meta_adonis$disease)) # p-value = 0.1215
# gender
# >5 values for each category --> chisq.test
chisq.test(table(ibd_meta_adonis$gender, ibd_meta_adonis$disease)) # p-value = 0.7319
# location
fisher.test(table(ibd_meta_adonis$location, ibd_meta_adonis$disease)) # p-value = 0.005405
### retain disease, disease_subtype, age_imputed, gender and location in the metadata
# location is significantly different between healthy and IBD patients and slightly associated with the microbiome structure (possible confounder)
# age_imputed and gender significantly associated with the microbiome structure (predictive signal)
# disease and disease_subtype are slightly associated with microbiome structure
# antibiotics is not significantly associated with disease_subtype or with microbiome structure
ibd_merge <- ibd_merge[, -1] # remove antibiotics from merged data set
### check visually for batch effects using NMDS
# calculate dissimilarity matrix (Euclidean)
dist_matrix <- dist(ibd_feat_adonis, method = "euclidean")
# perform NMDS
nmds <- metaMDS(dist_matrix, k = 2, trymax = 100)
# prepare NMDS data for plotting
nmds_df <- as.data.frame(nmds$points)
nmds_df$location <- ibd_merge$location
nmds_df$disease <- ibd_merge$disease
# plot NMDS
ggplot(nmds_df, aes(x = MDS1, y = MDS2, color = location, shape = disease)) +
geom_point(size = 3) + theme_minimal() +
labs(title = "NMDS of microbiome structure (Euclidean)")
##################################################################################
### OVERALL RANDOM FOREST - 5-FOLD CROSS-VALIDATION + 50 REPEATS - DISEASE ###
##################################################################################
# set seed
set.seed(1234)
# column names for microbiome features
micro_feat_cols <- setdiff(colnames(ibd_merge), c("disease", "disease_subtype", "age_imputed", "gender", "location"))
# column names for microbiome features + relevant metadata (full predictor set)
all_feat_cols <- c(micro_feat_cols, "age_imputed", "gender", "location")
# 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 disease)
folds <- createFolds(ibd_merge$disease, 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 <- ibd_merge[-test_idx, ] # training data (all rows not in fold f)
test_data <- ibd_merge[test_idx, ] # testing data (fold f)
# train random forest model
# x = all data in data.frame subset by all_feat_cols (predictor values)
# y = target variable as factor
rf_model <- randomForest(x = train_data[, all_feat_cols],
y = as.factor(train_data$disease),
ntree = 500, importance = TRUE)
# evaluate on test set
predictions <- predict(rf_model, newdata = test_data[, all_feat_cols])
# 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 matrix
cm <- confusionMatrix(predictions, as.factor(test_data$disease), positive = "IBD")
# store with repeat (r) and fold (f) index
# performance_metrics and feature_importances will be lists of 250 elements (50 repeats x 5 folds)
key <- paste0("Repeat_", r, "_Fold_", f)
feature_frequencies[[key]] <- as.data.frame(split_counts) # store feature freqeuncies
performance_metrics[[key]] <- cm # store performance metrics
feature_importances[[key]] <- importance(rf_model) # store feature importances
}
}
### calculate feature frequencies
all_splits <- bind_rows(feature_frequencies, .id = "Repeat_Fold") # combine frequencies into a single data.frame
colnames(all_splits) <- c("Repeat_Fold", "Feature", "Count") # rename columns
# summarize total and average counts
feature_split_summary <- all_splits %>%
group_by(Feature) %>%
summarise(total_count = sum(Count, na.rm = TRUE),
mean_count = mean(Count, na.rm = TRUE),
n_models = n()) %>%
arrange(desc(total_count))
head(feature_split_summary, 20)
# calculate relative frequency of feature selection
feature_split_summary <- feature_split_summary %>%
mutate(prop_models = n_models / length(feature_frequencies),
avg_per_tree = total_count / (length(feature_frequencies) * rf_model$ntree))
### calculate performance statistics
# create vectors to store metrics
balanced_accuracy <- numeric()
f1_score <- numeric()
sensitivity <- numeric()
specificity <- numeric()
# extract metrics from the stored confusion matrices (50 repeats x 5 folds = 250 values)
for (cm in performance_metrics) {
balanced_accuracy <- c(balanced_accuracy, cm$byClass["Balanced Accuracy"])
f1_score <- c(f1_score, cm$byClass["F1"])
sensitivity <- c(sensitivity, cm$byClass["Sensitivity"])
specificity <- c(specificity, cm$byClass["Specificity"])
}
# combine metrics in a summary table
metric_summary <- data.frame(mean_bal_acc = mean(balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(f1_score, na.rm = TRUE),
sd_f1 = sd(f1_score, na.rm = TRUE),
mean_sens = mean(sensitivity, na.rm = TRUE),
sd_sens = sd(sensitivity, na.rm = TRUE),
mean_spec = mean(specificity, na.rm = TRUE),
sd_spec = sd(specificity, na.rm = TRUE))
metric_summary
### 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_MeanDecreaseAccuracy: overall importance of feature on model accuracy
# mean_MeanDecreaseGini: frequency and usefulness in splitting (how much a feature reduces impurity when used to split the decision trees)
# Gini is sensitive to splits, NOT predictive value
mean_importance <- all_features_importances %>%
group_by(Feature) %>%
summarise(mean_healthy = mean(healthy, na.rm = TRUE),
mean_IBD = mean(IBD, na.rm = TRUE),
mean_MeanDecreaseAccuracy = mean(MeanDecreaseAccuracy, na.rm = TRUE),
mean_MeanDecreaseGini = mean(MeanDecreaseGini, na.rm = TRUE)) %>%
arrange(desc(mean_MeanDecreaseGini))
head(mean_importance, 10)
# same data from full model for comparison
full_model_feature_split_summary <- feature_split_summary
full_model_metric_summary <- metric_summary
full_model_mean_importance <- mean_importance
### age_imputed and gender both have negative mean_MeanDecreaseAccuracy values (but age_imputed has a high mean_MeanDecreaseGini value)
# age_imputed is useful for splitting the microbiome data, but not useful for predicting for disease classification
# the association of age_imputed and gender with the microbiome is likely orthogonal to disease
##########################################################################################
### OVERALL RANDOM FOREST - 5-FOLD CROSS-VALIDATION + 50 REPEATS - DISEASE_SUBTYPE ###
##########################################################################################
# multi-class classification
# set seed
set.seed(1234)
# column names for microbiome features
micro_feat_cols <- setdiff(colnames(ibd_merge), c("disease", "disease_subtype", "age_imputed", "gender", "location"))
# column names for microbiome features + relevant metadata (full predictor set)
all_feat_cols <- c(micro_feat_cols, "age_imputed", "gender", "location")
# 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 disease_subtype)
folds <- createFolds(ibd_merge$disease_subtype, 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 <- ibd_merge[-test_idx, ] # training data (all rows not in fold f)
test_data <- ibd_merge[test_idx, ] # testing data (fold f)
# train random forest model
# x = all data in data.frame subset by all_feat_cols (predictor values)
# y = target variable as factor
rf_model <- randomForest(x = train_data[, all_feat_cols],
y = as.factor(train_data$disease_subtype),
ntree = 500, importance = TRUE)
# evaluate on test set
predictions <- predict(rf_model, newdata = test_data[, all_feat_cols])
# 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 matrix
cm <- confusionMatrix(predictions, as.factor(test_data$disease_subtype))
# store with repeat (r) and fold (f) index
# performance_metrics and feature_importances will be lists of 250 elements (50 repeats x 5 folds)
key <- paste0("Repeat_", r, "_Fold_", f)
feature_frequencies[[key]] <- as.data.frame(split_counts) # store feature freqeuncies
performance_metrics[[key]] <- cm # store performance metrics
feature_importances[[key]] <- importance(rf_model) # store feature importances
}
}
### calculate feature frequencies
all_splits <- bind_rows(feature_frequencies, .id = "Repeat_Fold") # combine frequencies into a single data.frame
colnames(all_splits) <- c("Repeat_Fold", "Feature", "Count") # rename columns
# summarize total and average counts
feature_split_summary <- all_splits %>%
group_by(Feature) %>%
summarise(total_count = sum(Count, na.rm = TRUE),
mean_count = mean(Count, na.rm = TRUE),
n_models = n()) %>%
arrange(desc(total_count))
head(feature_split_summary, 20)
# calculate relative frequency of feature selection
feature_split_summary <- feature_split_summary %>%
mutate(prop_models = n_models / length(feature_frequencies),
avg_per_tree = total_count / (length(feature_frequencies) * rf_model$ntree))
### calculate performance statistics (multi-class)
# each confusion matrix now returns a matrix with cm$byClass
# get macro-averaged metrics across the 3 classes (healthy, CD, UC)
# create vectors to store metrics
balanced_accuracy <- numeric()
f1_score <- numeric()
sensitivity <- numeric()
specificity <- numeric()
# extract metrics from the stored confusion matrices (50 repeats x 5 folds = 250 values)
for (cm in performance_metrics) {
if (is.matrix(cm$byClass)) {
balanced_accuracy <- c(balanced_accuracy, mean(cm$byClass[,"Balanced Accuracy"], na.rm = TRUE))
f1_score <- c(f1_score, mean(cm$byClass[,"F1"], na.rm = TRUE))
sensitivity <- c(sensitivity, mean(cm$byClass[,"Sensitivity"], na.rm = TRUE))
specificity <- c(specificity, mean(cm$byClass[,"Specificity"], na.rm = TRUE))
}
}
# combine metrics in a summary table
metric_summary <- data.frame(mean_bal_acc = mean(balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(f1_score, na.rm = TRUE),
sd_f1 = sd(f1_score, na.rm = TRUE),
mean_sens = mean(sensitivity, na.rm = TRUE),
sd_sens = sd(sensitivity, na.rm = TRUE),
mean_spec = mean(specificity, na.rm = TRUE),
sd_spec = sd(specificity, na.rm = TRUE))
metric_summary
### 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_MeanDecreaseAccuracy: overall importance of feature on model accuracy
# mean_MeanDecreaseGini: frequency and usefulness in splitting (how much a feature reduces impurity when used to split the decision trees)
# Gini is sensitive to splits, NOT predictive value
mean_importance <- all_features_importances %>%
group_by(Feature) %>%
summarise(mean_healthy = mean(healthy, na.rm = TRUE),
mean_CD = mean(CD, na.rm = TRUE),
mean_UC = mean(UC, na.rm = TRUE),
mean_MeanDecreaseAccuracy = mean(MeanDecreaseAccuracy, na.rm = TRUE),
mean_MeanDecreaseGini = mean(MeanDecreaseGini, na.rm = TRUE)) %>%
arrange(desc(mean_MeanDecreaseGini))
head(mean_importance, 10)
# same data from full model for comparison
disease_sub_feature_split_summary <- feature_split_summary
disease_sub_metric_summary <- metric_summary
disease_sub_mean_importance <- mean_importance
### comparison of disease versus disease_subtype as model label
full_model_feature_split_summary # disease
disease_sub_feature_split_summary # disease_subtype
full_model_metric_summary # disease
disease_sub_metric_summary # disease_subtype
full_model_mean_importance # disease
disease_sub_mean_importance # disease_subtype
### disease has very high sensitivity, but very low specificity
### disease_subtype has lower overall performance, but performance across classes is better balanced (doesn't over predict disease as much)
### age_imputed has a very high Gini (appears in every tree), but decreases model accuracy
### location has a modes impact on accuracy
### gender has a very low Gini and decreases model accuracy
############################################################################################################
### OVERALL RANDOM FOREST - 5-FOLD CROSS-VALIDATION + 50 REPEATS - DISEASE_SUBTYPE - MICROBIOME ONLY ###
############################################################################################################
# using only microbiome features to train the model
# set seed
set.seed(1234)
# column names for microbiome features
micro_feat_cols <- setdiff(colnames(ibd_merge), c("disease", "disease_subtype", "age_imputed", "gender", "location"))
# column names for microbiome features + relevant metadata (full predictor set)
all_feat_cols <- micro_feat_cols ### only include microbiome features in this model
# 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 disease_subtype)
folds <- createFolds(ibd_merge$disease_subtype, 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 <- ibd_merge[-test_idx, ] # training data (all rows not in fold f)
test_data <- ibd_merge[test_idx, ] # testing data (fold f)
# train random forest model
# x = all data in data.frame subset by all_feat_cols (predictor values)
# y = target variable as factor
rf_model <- randomForest(x = train_data[, all_feat_cols],
y = as.factor(train_data$disease_subtype),
ntree = 500, importance = TRUE)
# evaluate on test set
predictions <- predict(rf_model, newdata = test_data[, all_feat_cols])
# 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 matrix
cm <- confusionMatrix(predictions, as.factor(test_data$disease_subtype))
# store with repeat (r) and fold (f) index
# performance_metrics and feature_importances will be lists of 250 elements (50 repeats x 5 folds)
key <- paste0("Repeat_", r, "_Fold_", f)
feature_frequencies[[key]] <- as.data.frame(split_counts) # store feature freqeuncies
performance_metrics[[key]] <- cm # store performance metrics
feature_importances[[key]] <- importance(rf_model) # store feature importances
}
}
### calculate feature frequencies
all_splits <- bind_rows(feature_frequencies, .id = "Repeat_Fold") # combine frequencies into a single data.frame
colnames(all_splits) <- c("Repeat_Fold", "Feature", "Count") # rename columns
# summarize total and average counts
feature_split_summary <- all_splits %>%
group_by(Feature) %>%
summarise(total_count = sum(Count, na.rm = TRUE),
mean_count = mean(Count, na.rm = TRUE),
n_models = n()) %>%
arrange(desc(total_count))
head(feature_split_summary, 20)
# calculate relative frequency of feature selection
feature_split_summary <- feature_split_summary %>%
mutate(prop_models = n_models / length(feature_frequencies),
avg_per_tree = total_count / (length(feature_frequencies) * rf_model$ntree))
### calculate performance statistics (multi-class)
# each confusion matrix now returns a matrix with cm$byClass
# get macro-averaged metrics across the 3 classes (healthy, CD, UC)
# create vectors to store metrics
balanced_accuracy <- numeric()
f1_score <- numeric()
sensitivity <- numeric()
specificity <- numeric()
# extract metrics from the stored confusion matrices (50 repeats x 5 folds = 250 values)
for (cm in performance_metrics) {
if (is.matrix(cm$byClass)) {
balanced_accuracy <- c(balanced_accuracy, mean(cm$byClass[,"Balanced Accuracy"], na.rm = TRUE))
f1_score <- c(f1_score, mean(cm$byClass[,"F1"], na.rm = TRUE))
sensitivity <- c(sensitivity, mean(cm$byClass[,"Sensitivity"], na.rm = TRUE))
specificity <- c(specificity, mean(cm$byClass[,"Specificity"], na.rm = TRUE))
}
}
# combine metrics in a summary table
metric_summary <- data.frame(mean_bal_acc = mean(balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(f1_score, na.rm = TRUE),
sd_f1 = sd(f1_score, na.rm = TRUE),
mean_sens = mean(sensitivity, na.rm = TRUE),
sd_sens = sd(sensitivity, na.rm = TRUE),
mean_spec = mean(specificity, na.rm = TRUE),
sd_spec = sd(specificity, na.rm = TRUE))
metric_summary
### 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_MeanDecreaseAccuracy: overall importance of feature on model accuracy
# mean_MeanDecreaseGini: frequency and usefulness in splitting (how much a feature reduces impurity when used to split the decision trees)
# Gini is sensitive to splits, NOT predictive value
mean_importance <- all_features_importances %>%
group_by(Feature) %>%
summarise(mean_healthy = mean(healthy, na.rm = TRUE),
mean_CD = mean(CD, na.rm = TRUE),
mean_UC = mean(UC, na.rm = TRUE),
mean_MeanDecreaseAccuracy = mean(MeanDecreaseAccuracy, na.rm = TRUE),
mean_MeanDecreaseGini = mean(MeanDecreaseGini, na.rm = TRUE)) %>%
arrange(desc(mean_MeanDecreaseGini))
head(mean_importance, 10)
# same data from full model for comparison
microbiome_only_feature_split_summary <- feature_split_summary
microbiome_only_metric_summary <- metric_summary
microbiome_only_mean_importance <- mean_importance
### comparison of disease_subtype full model versus microbiome only model
disease_sub_feature_split_summary # full model
microbiome_only_feature_split_summary # microbiome only
disease_sub_metric_summary # full model
microbiome_only_metric_summary # microbiome only
disease_sub_mean_importance # full model
microbiome_only_mean_importance # microbiome only
### model performance metrics are essentially identical
# microbiome features alone are capturing most of the discriminative signal
### top microbiome features are stable across both models
#########################################################################################################
### OVERALL RANDOM FOREST - 5-FOLD CV + 50 REPEATS - DISEASE_SUBTYPE - MICROBIOME ONLY - STRATIFIED ###
#########################################################################################################
# stratified performance analysis (sex and age)
# evaluate whether model performance and feature importance varies across subgroups
# split age into two groups by the median
median_age <- median(ibd_merge$age_imputed, na.rm = TRUE)
ibd_merge$age_group <- ifelse(ibd_merge$age_imputed <= median_age, "younger", "older")
# set seed
set.seed(1234)
# column names for microbiome features
micro_feat_cols <- setdiff(colnames(ibd_merge), c("disease", "disease_subtype", "age_imputed", "gender", "location"))
# column names for microbiome features + relevant metadata (full predictor set)
all_feat_cols <- micro_feat_cols ### only include microbiome features in this model
### set stratification variable
strat_var <- "gender" # "gender" or "age_group"
# get the levels to compare
subgroups <- unique(ibd_merge[[strat_var]])
# create lists to store stratified metrics
stratified_metrics <- list()
stratified_importance <- list()
# loop over subgroups
for (group in subgroups){
cat("Analyzing subgroup:", group, "\n")
# subset data by the stratificiation variable
data_sub <- ibd_merge[ibd_merge[[strat_var]] == group, ]
# create lists to store metrics
feature_importances <- list() # list to store feature importances
performance_metrics <- list() # list to store performance metrics
# repeat cross-validation 50 times
for (r in 1:50) {
cat("Repeat:", r, "\n")
# create 5-folds for cross-validation (stratified on disease_subtype) using data subset on the stratification variable
folds <- createFolds(data_sub$disease_subtype, 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 (data already subset on stratification variable)
test_idx <- folds[[f]] # test indices for the f-th fold
train_data <- data_sub[-test_idx, ] # training data (all rows not in fold f)
test_data <- data_sub[test_idx, ] # testing data (fold f)
# train random forest model
# x = all data in data.frame subset by all_feat_cols (predictor values)
# y = target variable as factor
rf_model <- randomForest(x = train_data[, all_feat_cols],
y = as.factor(train_data$disease_subtype),
ntree = 500, importance = TRUE)
# evaluate on test set
predictions <- predict(rf_model, newdata = test_data[, all_feat_cols])
# generate confusion matrix
cm <- confusionMatrix(predictions, as.factor(test_data$disease_subtype))
# store with repeat (r) and fold (f) index
# performance_metrics and feature_importances will be lists of 250 elements (50 repeats x 5 folds)
key <- paste0("Repeat_", r, "_Fold_", f)
performance_metrics[[key]] <- cm # store performance metrics
feature_importances[[key]] <- importance(rf_model) # store feature importances
}
}
### calculate performance statistics
# create vectors to store metrics
balanced_accuracy <- numeric()
f1_score <- numeric()
sensitivity <- numeric()
specificity <- numeric()
# extract metrics from the stored confusion matrices (50 repeats x 5 folds = 250 values)
for (cm in performance_metrics) {
if (is.matrix(cm$byClass)) {
balanced_accuracy <- c(balanced_accuracy, mean(cm$byClass[,"Balanced Accuracy"], na.rm = TRUE))
f1_score <- c(f1_score, mean(cm$byClass[,"F1"], na.rm = TRUE))
sensitivity <- c(sensitivity, mean(cm$byClass[,"Sensitivity"], na.rm = TRUE))
specificity <- c(specificity, mean(cm$byClass[,"Specificity"], na.rm = TRUE))
}
}
# combine metrics in a summary table
metric_summary <- data.frame(mean_bal_acc = mean(balanced_accuracy, na.rm = TRUE),
sd_bal_acc = sd(balanced_accuracy, na.rm = TRUE),
mean_f1 = mean(f1_score, na.rm = TRUE),
sd_f1 = sd(f1_score, na.rm = TRUE),
mean_sens = mean(sensitivity, na.rm = TRUE),
sd_sens = sd(sensitivity, na.rm = TRUE),
mean_spec = mean(specificity, na.rm = TRUE),
sd_spec = sd(specificity, na.rm = TRUE))
# add group name to summary metrics info
metric_summary$Group <- group
# store stratified performance metrics (each group has a list of two elements: summary and full metrics)
stratified_metrics[[group]] <- list(summary = metric_summary,
full_metrics = performance_metrics)
### 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_MeanDecreaseAccuracy: overall importance of feature on model accuracy
# mean_MeanDecreaseGini: frequency and usefulness in splitting (how much a feature reduces impurity when used to split the decision trees)
# Gini is sensitive to splits, NOT predictive value
mean_importance <- all_features_importances %>%
group_by(Feature) %>%
summarise(mean_healthy = mean(healthy, na.rm = TRUE),
mean_CD = mean(CD, na.rm = TRUE),
mean_UC = mean(UC, na.rm = TRUE),
mean_MeanDecreaseAccuracy = mean(MeanDecreaseAccuracy, na.rm = TRUE),
mean_MeanDecreaseGini = mean(MeanDecreaseGini, na.rm = TRUE)) %>%
arrange(desc(mean_MeanDecreaseGini))
head(mean_importance, 10)
stratified_importance[[group]] <- mean_importance
}
### does the model perform statistically differently across the subgroups
# function to extract metrics from confusion matrices
extract_metric <- function(metric_name, cm_list) {
sapply(cm_list, function(cm) {
if (!is.null(cm) && is.matrix(cm$byClass)) {
mean(cm$byClass[, metric_name], na.rm = TRUE)
} else {
NA
}
})
}
# function to extract and average metric across folds per repeat (per repeat averages)
get_repeat_averages <- function(group, metric) {
vals <- extract_metric(metric, stratified_metrics[[group]]$full_metrics)
rowMeans(matrix(vals, nrow = 50, byrow = TRUE), na.rm = TRUE)
}
# MALE VS FEMALE
# balanced accuracy
bal_acc_male_avg <- get_repeat_averages("male", "Balanced Accuracy")
bal_acc_female_avg <- get_repeat_averages("female", "Balanced Accuracy")
wilcox.test(bal_acc_male_avg, bal_acc_female_avg) # p-value = 1.47e-14
perf_df <- data.frame(BalancedAccuracy = c(bal_acc_male_avg, bal_acc_female_avg),
Group = rep(c("Male", "Female"), each = 50))
ggplot(perf_df, aes(x = Group, y = BalancedAccuracy, fill = Group)) +
geom_boxplot(width = 0.6, alpha = 0.5, outlier.size = 1) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1) +
scale_fill_manual(values = c("Male" = "skyblue", "Female" = "pink")) +
labs(title = "Balanced accuracy by gender", y = "Balanced accuracy", x = NULL) +
theme_minimal() + theme(legend.position = "none")
# f1 score
f1_male_avg <- get_repeat_averages("male", "F1")
f1_female_avg <- get_repeat_averages("female", "F1")
wilcox.test(f1_male_avg, f1_female_avg) # p-value = 0.759
perf_df <- data.frame(F1_score = c(f1_male_avg, f1_female_avg),
Group = rep(c("Male", "Female"), each = 50))
ggplot(perf_df, aes(x = Group, y = F1_score, fill = Group)) +
geom_boxplot(width = 0.6, alpha = 0.5, outlier.size = 1) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1) +
scale_fill_manual(values = c("Male" = "skyblue", "Female" = "pink")) +
labs(title = "F1 score by gender", y = "F1 score", x = NULL) +
theme_minimal() + theme(legend.position = "none")
# sensitivity
sens_male_avg <- get_repeat_averages("male", "Sensitivity")
sens_female_avg <- get_repeat_averages("female", "Sensitivity")
wilcox.test(sens_male_avg, sens_female_avg) # p-value = 2.509e-13
perf_df <- data.frame(Sens = c(sens_male_avg, sens_female_avg),
Group = rep(c("Male", "Female"), each = 50))
ggplot(perf_df, aes(x = Group, y = Sens, fill = Group)) +
geom_boxplot(width = 0.6, alpha = 0.5, outlier.size = 1) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1) +
scale_fill_manual(values = c("Male" = "skyblue", "Female" = "pink")) +
labs(title = "Sensitivity by gender", y = "Sensitivity", x = NULL) +
theme_minimal() + theme(legend.position = "none")
# specificity
spec_male_avg <- get_repeat_averages("male", "Specificity")
spec_female_avg <- get_repeat_averages("female", "Specificity")
wilcox.test(spec_male_avg, spec_female_avg) # p-value = 5.037e-16
perf_df <- data.frame(Spec = c(spec_male_avg, spec_female_avg),
Group = rep(c("Male", "Female"), each = 50))
ggplot(perf_df, aes(x = Group, y = Spec, fill = Group)) +
geom_boxplot(width = 0.6, alpha = 0.5, outlier.size = 1) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1) +
scale_fill_manual(values = c("Male" = "skyblue", "Female" = "pink")) +
labs(title = "Specificity by gender", y = "Specificity", x = NULL) +
theme_minimal() + theme(legend.position = "none")
# YOUNGER VS OLDER
# balanced accuracy
bal_acc_younger_avg <- get_repeat_averages("younger", "Balanced Accuracy")
bal_acc_older_avg <- get_repeat_averages("older", "Balanced Accuracy")
wilcox.test(bal_acc_younger_avg, bal_acc_older_avg) # p-value = 0.003999
perf_df <- data.frame(BalancedAccuracy = c(bal_acc_younger_avg, bal_acc_older_avg),
Group = rep(c("Younger", "Older"), each = 50))
ggplot(perf_df, aes(x = Group, y = BalancedAccuracy, fill = Group)) +
geom_boxplot(width = 0.6, alpha = 0.5, outlier.size = 1) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1) +
scale_fill_manual(values = c("Younger" = "skyblue", "Older" = "pink")) +
labs(title = "Balanced accuracy by age", y = "Balanced accuracy", x = NULL) +
theme_minimal() + theme(legend.position = "none")
# f1 score
f1_younger_avg <- get_repeat_averages("younger", "F1")
f1_older_avg <- get_repeat_averages("older", "F1")
wilcox.test(f1_younger_avg, f1_older_avg) # p-value < 2.2e-16
perf_df <- data.frame(F1 = c(f1_younger_avg, f1_older_avg),
Group = rep(c("Younger", "Older"), each = 50))
ggplot(perf_df, aes(x = Group, y = F1, fill = Group)) +
geom_boxplot(width = 0.6, alpha = 0.5, outlier.size = 1) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1) +
scale_fill_manual(values = c("Younger" = "skyblue", "Older" = "pink")) +
labs(title = "F1 score by age", y = "F1 score", x = NULL) +
theme_minimal() + theme(legend.position = "none")