-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathERS_binary.R
More file actions
1436 lines (1169 loc) · 60.2 KB
/
Copy pathERS_binary.R
File metadata and controls
1436 lines (1169 loc) · 60.2 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
#-------------------------------------------------------------------------------
## Reproducible and generalisable script for calculating an exposomic risk score (ERS) for a binary outcome using XGBoost with nested cross-validation
#
# Method: Double Machine Learning (DML) - residualizing exposures on adjustment variables (cohort membership and/or covariates)
#
# Steps:
# - Step 1 [optional, multi-cohort]: W_j = X_j - E[X_j | cohort] -> each exposure is cleaned of between-cohort differences
# - Step 2: W2_j = W_j - E[W_j | covariates] -> each exposure is additionally cleaned of covariate effects
# - Step 3: ERS = f(W2) -> ERS = predicted log-odds from doubly-adjusted exposures
#
#
# How to use the ERS in a final model:
# - glm(y ~ ers + age + sex + bmi, data=sim_data, family=binomial())
# - or stratify into tertiles for OR and AUROC
#
# Settings to adjust before running:
# - use_cohort: TRUE/FALSE
# - cov_names: names of covariate adjustment variables
# - ers_metric: metric for ERS model tuning (step 3), with one of: "AUROC", "F1", "LogLoss"
#-------------------------------------------------------------------------------
#----------------------------------------------------------------
#### Configurations ####
## Disabling memory torture
gctorture(FALSE)
## Installing and loading packages
pack_needed<-c("data.table","tidyverse","mllrnrs","broom","doParallel","foreach","splitTools","conflicted","grid","gridExtra","RColorBrewer","mlbench",
"mlexperiments","caret","MLmetrics","patchwork","performance","xgboost","parallel","here","scales","dplyr","ggplot2","tidyr",
"tibble","mgcv","ggforce","gratia","Rcpp","Metrics","MASS","pROC","iml")
is_installed<-pack_needed %in% rownames(installed.packages(all.available=TRUE))
if(any(is_installed==FALSE)){
install.packages(pack_needed[!is_installed],repos="http://cran.us.r-project.org")
}
invisible(lapply(pack_needed, library, character.only=TRUE))
## Preventing package conflicts
conflict_prefer("select","dplyr")
conflict_prefer("filter","dplyr")
conflict_prefer("slice","dplyr")
conflict_prefer("alpha","scales")
conflict_prefer("auc","pROC")
conflict_prefer("roc","pROC")
conflicts_prefer(caret::lift)
## Setting the working directory
here::here("XGBoost - ERS calculation - binary outcome")
## Setting seed
seed<-123
## Setting cores
if(isTRUE(as.logical(Sys.getenv("_R_CHECK_LIMIT_CORES_")))){
ncores<-2L
}else{
ncores<-ifelse(test=parallel::detectCores()>4,yes=4L,no=ifelse(test=parallel::detectCores()<2L,yes=1L,no=parallel::detectCores()))
}
## Setting mlexperiments package options
options("mlexperiments.bayesian.max_init"=10L)
options("mlexperiments.optim.xgb.nrounds"=100L)
options("mlexperiments.optim.xgb.early_stopping_rounds"=10L)
#----------------------------------------------------------------
#### Creating functions ####
#- - - - - -
## Function for plotting SHAP values
plot.shap.summary<-function(data_long){
x_bound<-max(abs(data_long$value))
require('ggforce')
plot1<-ggplot(data=data_long)+
coord_flip() +
geom_sina(aes(x=variable, y=value, color=stdfvalue)) +
geom_text(data=unique(data_long[, c("variable", "mean_value"), with=F]),
aes(x=variable, y=-Inf, label=sprintf("%.3f", mean_value)),
size=3, alpha=0.7,hjust=-0.2, fontface="bold") +
scale_color_gradient(low="#FFCC33", high="#6600CC", breaks=c(0,1), labels=c("Low","High")) +
theme_bw() +
theme(axis.line.y=element_blank(), axis.ticks.y=element_blank(), legend.position="bottom") +
geom_hline(yintercept=0) +
scale_y_continuous(limits=c(-x_bound, x_bound)) +
scale_x_discrete(limits=rev(levels(data_long$variable))) +
labs(y="SHAP value (impact on model output)", x="", color="Feature value")
return(plot1)
}
#- - - - - -
## Standardizing feature values into [0,1]
std1<-function(x){
return((x - min(x, na.rm=T))/(max(x, na.rm=T) - min(x, na.rm=T)))
}
#- - - - - -
## Formatting summary statistics for display
test_format<-function(x){
x<-as.numeric(x)
sign_x<-if_else(x<0,"neg","pos")
x<-abs(x)
x_raw<-x
if(is.na(x)|is.infinite(x)) x_raw<-0
if(x_raw>=100){
virg_pos<-str_locate(as.character(x_raw),"[.]")[1]
if(!is.na(virg_pos)&as.numeric(substr(x_raw,virg_pos+1,virg_pos+1))>=5){
x<-x+1
x<-as.numeric(substr(x,1,virg_pos-1))
}
}
if(is.na(x)|is.infinite(x)){
x<-""
}else{
if(x<0.05|x>=10000){
x<-format(signif(x,3), scientific=TRUE)
}else{
x_save<-x
x<-signif(x,3)
if(nchar(x)==6) x<-as.numeric(substr(x,1,5))
if(nchar(x)==5){
if(as.numeric(substr(x,5,5))>=5){
x<-x+0.01
x<-substr(x,1,4)
}else{
x<-substr(x,1,4)
}
}else{
if(x>=1000) x<-as.character(signif(x_save,4)) else x<-as.character(x)
}
}
}
if(sign_x=="neg"&x_raw!=0) x<-paste("-",x,sep="")
if(x=="0e+00") x<-"0"
return(x)
}
#- - - - - -
## Custom ggplot theme
theme_Gaia<-function(){
theme_bw() +
theme(strip.text=element_text(size=12, colour="black", face="bold"),
strip.background=element_rect(fill="#CAE1FF",colour="black"),
axis.text=element_text(size=12, color="black"),
axis.title=element_text(size=12, face="bold", color="black"),
legend.text=element_text(size=12),
legend.title=element_text(size=12, face="bold"),
axis.line=element_line(color="black", linewidth=0.1))
}
#- - - - - -
## Functions for determining feature direction from SHAP values (i.e.: how a feature impacts the model)
# Approach 1: conventional (mean SHAP sign)
conventional_direction<-function(df, feature_col, shap_col){
s<-df[[shap_col]]
mean_s<-mean(s, na.rm=TRUE)
if(abs(mean_s)<1e-10) return("neutral")
ifelse(mean_s>0, "promoting", "mitigating")
}
# Approach 2: GAM derivative + Spearman fallback
gam_direction<-function(df, feature_col, shap_col){
x<-df[[feature_col]]
s<-df[[shap_col]]
valid<-complete.cases(x, s)
x<-x[valid]
s<-s[valid]
if(length(unique(x)) <= 1 || length(unique(s)) <= 1) return("undefined")
# Binary or sparse
if(length(unique(x)) <= 2 || quantile(x, 0.75, na.rm=TRUE) == 0){
mean_diff<-mean(s[x > 0], na.rm=TRUE) - mean(s[x <= 0], na.rm=TRUE)
return(ifelse(mean_diff > 0, "promoting",ifelse(mean_diff < 0, "mitigating", "neutral")))
}
# Continuous: GAM
tryCatch({
gam_m<-mgcv::gam(s ~ s(x, bs="cr", k=8), method="REML")
derivs<-gratia::derivatives(gam_m, term="s(x)")
mean_d<-mean(derivs$derivative, na.rm=TRUE)
if(abs(mean_d) < 1e-10) return("neutral")
return(ifelse(mean_d > 0, "promoting", "mitigating"))
}, error=function(e){
rho<-suppressWarnings(cor(x, s, method="spearman"))
if(is.na(rho) || abs(rho) < 0.05) return("neutral")
return(ifelse(rho > 0, "promoting", "mitigating"))
})
}
# Approach 3: Pairwise bin concordance (Rcpp)
# Compiling C++ function
if(!exists("bin_pairwise_counts")){
Rcpp::cppFunction('
Rcpp::List bin_pairwise_counts(NumericVector bx, NumericVector bs,
NumericVector bc){
int B=bx.size();
double pos=0.0, neg=0.0, total=0.0;
for (int i=0; i < B; ++i){
for (int j=i+1; j < B; ++j){
double ci=bc[i], cj=bc[j];
if(ci <= 0.0 || cj <= 0.0) continue;
double pairs=ci * cj;
if(bx[i] > bx[j]){
total += pairs;
if(bs[i] > bs[j]) pos += pairs;
else if(bs[i] < bs[j]) neg += pairs;
} else if(bx[j] > bx[i]){
total += pairs;
if(bs[j] > bs[i]) pos += pairs;
else if(bs[j] < bs[i]) neg += pairs;
}
}
}
return Rcpp::List::create(
Rcpp::Named("pos") =pos,
Rcpp::Named("neg") =neg,
Rcpp::Named("total")=total);
}', depends="Rcpp")
}
pairwise_direction<-function(df, feature_col, shap_col,majority_threshold=0.55,n_quantile_bins=200){
x<-df[[feature_col]]
s<-df[[shap_col]]
valid<-complete.cases(x, s)
x<-x[valid]
s<-s[valid]
if(length(unique(x)) <= 1 || length(unique(s)) <= 1) return("undefined")
# Binary / sparse
if(length(unique(x)) <= 2 || quantile(x, 0.75, na.rm=TRUE) == 0){
lv<-min(x)
hv<-max(x)
g0<-s[x==lv]
g1<-s[x==hv]
if(length(g0)==0 || length(g1)==0) return("neutral")
g0s<-sort(g0)
pos<-sum(findInterval(g1, g0s, left.open=TRUE))
tot<-as.double(length(g0)) * as.double(length(g1))
pp<-pos/tot
if(pp>=majority_threshold) return("promoting")
if(pp<=1-majority_threshold) return("mitigating")
return("neutral")
}
# Continuous: binning
probs<-seq(0, 1, length.out=n_quantile_bins+1)
breaks<-unique(quantile(x, probs=probs, na.rm=TRUE, type=7))
if(length(breaks) <= 2)
breaks<-seq(min(x,na.rm=TRUE), max(x,na.rm=TRUE), length.out=3)
bins<-cut(x, breaks=breaks, include.lowest=TRUE)
bx<-as.numeric(tapply(x, bins, mean, na.rm=TRUE))
bs<-as.numeric(tapply(s, bins, mean, na.rm=TRUE))
bc<-as.numeric(tapply(s, bins, length))
ok<-!is.na(bx) & !is.na(bs) & !is.na(bc)
bx<-bx[ok]
bs<-bs[ok]
bc<-bc[ok]
if(length(bx)<2) return("neutral")
cnts<-bin_pairwise_counts(bx, bs, bc)
pos_p<-as.numeric(cnts$pos)
neg_p<-as.numeric(cnts$neg)
tot_p<-as.numeric(cnts$total)
if(tot_p <= 0) return("neutral")
pp<-pos_p/tot_p
np<-neg_p/tot_p
if(pp>=majority_threshold) return("promoting")
if(np>=majority_threshold) return("mitigating")
return("neutral")
}
## Wrapper for computing SHAP directions from wide-format data
compute_shap_directions<-function(data_df, feature_cols,shap_prefix="shap_",
methods=c("conventional","gam","pairwise"),
threshold=0.55,n_bins=200){
res<-lapply(feature_cols, function(f){
sc<-paste0(shap_prefix, f)
if(!sc %in% names(data_df)){
message("SHAP column not found for: ", f); return(NULL)
}
row<-data.frame(feature=f,
mean_shap=round(mean(data_df[[sc]], na.rm=TRUE), 5),
median_shap=round(median(data_df[[sc]],na.rm=TRUE),5))
if("conventional" %in% methods)
row$conventional<-conventional_direction(data_df, f, sc)
if("gam" %in% methods)
row$gam_deriv<-gam_direction(data_df, f, sc)
if("pairwise" %in% methods)
row$pairwise_bins<-pairwise_direction(data_df, f, sc, majority_threshold=threshold,n_quantile_bins=n_bins)
row
})
do.call(rbind, Filter(Negate(is.null), res))
}
## Wrapper for computing SHAP directions from long-format data
compute_shap_directions_long<-function(long_df,threshold,n_bins){
long_df %>%
group_split(feature) %>%
map_dfr(function(df_feat){
f<-as.character(df_feat$feature[1])
tmp<-data.frame(x=df_feat$feature_value, s=df_feat$shap_value)
tibble(feature=f,
n=nrow(df_feat),
mean_shap=mean(df_feat$shap_value, na.rm=TRUE),
median_shap=median(df_feat$shap_value, na.rm=TRUE),
conventional=conventional_direction(tmp, "x", "s"),
gam=gam_direction(tmp, "x", "s"),
pairwise=pairwise_direction(tmp, "x", "s",majority_threshold=threshold,n_quantile_bins=n_bins))
})
}
#- - - - - -
## not-in operator
`%ni%`<-Negate('%in%')
#- - - - - -
## SHAP interaction summary
#
# Goal: to summarize SHAP interaction values
#
# Outputs: dataset with columns:
# - feature: feature name
# - interaction_strength: mean absolute off-diagonal SHAP interaction -> high values indicate this feature interacts strongly with others
# - main_effect_mean: mean absolute diagonal (main effect) SHAP -> useful to compare interaction vs. main effect magnitude
# - features with high interaction_strength may have non-monotone effects due to interactions
# - if main_effect_mean >> interaction_strength, the feature is mostly additive
shap_interaction_summary<-function(xgb_fit, X_mat, feature_cols){
inter<-predict(xgb_fit, X_mat, predinteraction = TRUE)
p<-length(feature_cols)
arr<-if(length(dim(inter)) == 3){
inter
}else{
array(inter, dim = c(nrow(X_mat), p + 1, p + 1))
}
dplyr::bind_rows(lapply(seq_len(p), function(j){
off<-arr[, j, 1:p, drop = FALSE]
if(length(dim(off)) == 3) off<-off[, 1, , drop = FALSE]
main<-arr[, j, j]
offdiag<-rowSums(abs(off), na.rm = TRUE) - abs(main)
data.frame(feature = feature_cols[j],
interaction_strength = mean(offdiag, na.rm = TRUE),
main_effect_mean = mean(main, na.rm = TRUE))
}))
}
#- - - - - -
## Finding optimal classification threshold by maximizing the chosen metric on a dataset
find_optimal_threshold<-function(probs, obs, metric){
thresholds<-seq(0.01, 0.99, by=0.01)
perf<-sapply(thresholds, function(thr){
pred_bin<-as.integer(probs >= thr)
if(length(unique(pred_bin))<2) return(NA)
tryCatch({
if(metric=="AUROC"){
## AUROC is threshold-independent; use 0.5 as default
return(NA)
}else if(metric=="F1"){
MLmetrics::F1_Score(pred_bin, obs)
}else if(metric=="LogLoss"){
## LogLoss is threshold-independent; use 0.5 as default
return(NA)
}
}, error=function(e) NA)
})
if(all(is.na(perf))) return(0.5)
## For threshold-independent metrics (AUROC, LogLoss): use prevalence as threshold
if(metric %in% c("AUROC","LogLoss")) return(mean(obs, na.rm=TRUE))
thresholds[which.max(perf)]
}
#- - - - - -
## Computing all binary classification metrics between an exposure (or its residual) and Y
compute_binary_metrics<-function(x_vec, y_bin){
x_num<-as.numeric(x_vec)
y_int<-as.integer(y_bin)
## AUROC
AUROC<-round(tryCatch(as.numeric(pROC::auc(pROC::roc(y_int,x_num,quiet=TRUE))),error=function(e) NA),3)
## PRAUC
PRAUC<-round(tryCatch(MLmetrics::PRAUC(x_num,y_int),error=function(e) NA),3)
## LogLoss: rank-based probability proxy to handle raw continuous values outside [0,1]
prob_proxy<-rank(x_num,na.last="keep")/(sum(!is.na(x_num))+1)
LogLoss<-round(tryCatch(MLmetrics::LogLoss(prob_proxy,y_int),error=function(e) NA),3)
## Binarizing at median for threshold-dependent metrics
thresh<-median(x_num,na.rm=TRUE)
x_bin<-as.integer(x_num>thresh)
F1<-round(tryCatch(MLmetrics::F1_Score(x_bin,y_int),error=function(e) NA),3)
Sensitivity<-round(tryCatch(MLmetrics::Sensitivity(x_bin,y_int),error=function(e) NA),3)
Specificity<-round(tryCatch(MLmetrics::Specificity(x_bin,y_int),error=function(e) NA),3)
Balanced_accuracy<-round((Sensitivity+Specificity)/2,3)
return(data.frame(AUROC=AUROC,PRAUC=PRAUC,LogLoss=LogLoss,F1=F1,Sensitivity=Sensitivity,Specificity=Specificity,Balanced_accuracy=Balanced_accuracy))
}
#- - - - - -
## Fitting XGBoost with nested CV for exposure adjustment (one exposure at a time)
#
# Rationale:
# - this function residualizes an exposure (not the outcome Y) on adjustment variables (e.g., cohort and/or covariates), following the double machine learning framework.
# - the objective follows the nature of the exposure being modeled (the dependent variable of this function).
#
# Arguments:
# - X: matrix of adjustment variables (cohort dummies and/or covariates)
# - y: numeric vector of the exposure to adjust
# - is_binary_exposure: TRUE if y is binary (0/1), FALSE if continuous/ordinal
# - nb_outer_fold, nb_inner_fold: number of folds for nested CV
# - param_grid: optional custom hyperparameter grid
#
# Returns: OOF predicted values for the full dataset, on the original exposure scale. Residual = exposure - OOF_pred (computed outside this function)
fit_adjustment_oof<-function(X, y, is_binary_exposure=FALSE, nb_outer_fold=5, nb_inner_fold=5, param_grid=NULL){
y<-as.numeric(y)
## If constant exposure, residual = 0 for all observations
if(max(y, na.rm=TRUE)==min(y, na.rm=TRUE)) return(rep(y[1], length(y)))
if(is_binary_exposure){
## Binary exposure
y_model<-as.integer(y)
objective_<-"binary:logistic"
eval_metric_<-"logloss"
## scale_pos_weight to account for class imbalance within the exposure itself
tbl<-table(y_model)
spw<-if(length(tbl)==2) as.numeric(max(tbl)/min(tbl)) else 1
fold_type<-"stratified"
}else{
## Continuous or ordinal exposure
y_model<-y
objective_<-"reg:squarederror"
eval_metric_<-"rmse"
spw<-1
fold_type<-"basic"
}
## Default parameter grid if none provided
if(is.null(param_grid)){
param_grid<-expand.grid(subsample=seq(0.5,1,0.25),
colsample_bytree=seq(0.5,1,0.25),
min_child_weight=c(1,5,10),
learning_rate=c(0.05,0.1,0.3),
max_depth=c(3,5,7)) %>%
dplyr::slice_sample(n=30, replace=TRUE) # Limiting space to 30 combinations for computational efficiency and environmental sustainability considerations
}
## Creating outer folds (stratified for binary exposures, basic otherwise)
outer_folds<-splitTools::create_folds(y_model, k=nb_outer_fold, type=fold_type, seed=seed)
oof_preds<-rep(NA, length(y_model))
best_params_all<-list()
for(outer_idx in seq_along(outer_folds)){
val_idx<-outer_folds[[outer_idx]]
train_idx<-setdiff(seq_len(length(y_model)), val_idx)
X_tr<-X[train_idx,,drop=FALSE]
y_tr<-y_model[train_idx]
X_val<-X[val_idx,,drop=FALSE]
y_val<-y_model[val_idx]
## Computing scale_pos_weight per outer fold for binary exposures
spw_fold<-if(is_binary_exposure){
tbl_tr<-table(y_tr)
if(length(tbl_tr)==2) as.numeric(max(tbl_tr)/min(tbl_tr)) else 1
}else{ 1 }
## Inner CV
best_perf<-Inf # both logloss and rmse are minimized
best_params<-NULL
for(i in seq_len(nrow(param_grid))){
params_i<-list(objective=objective_,eval_metric=eval_metric_,subsample=param_grid$subsample[i],colsample_bytree=param_grid$colsample_bytree[i],
min_child_weight=param_grid$min_child_weight[i],eta=param_grid$learning_rate[i],max_depth=param_grid$max_depth[i],
scale_pos_weight=spw_fold)
dtrain_inner<-xgboost::xgb.DMatrix(data=X_tr, label=y_tr)
## stratified=TRUE only meaningful (and used) for binary exposures
cv_res<-tryCatch(suppressWarnings(xgboost::xgb.cv(params=params_i, data=dtrain_inner,nrounds=100, nfold=nb_inner_fold,
early_stopping_rounds=10, verbose=0,stratified=is_binary_exposure)),error=function(e) NULL)
if(is.null(cv_res)) next
## Extracting best performance across rounds (lower = better for both logloss and rmse)
metric_col<-paste0("test_",eval_metric_,"_mean")
best_val<-tryCatch(min(cv_res$evaluation_log[[metric_col]], na.rm=TRUE),error=function(e) NA)
if(!is.na(best_val) && best_val<best_perf){
best_perf<-best_val
best_params<-params_i
}
}
## Fallback to default params if all tuning attempts failed
if(is.null(best_params)){
best_params<-list(objective=objective_,eval_metric=eval_metric_,subsample=1, colsample_bytree=1, min_child_weight=1,
eta=0.1, max_depth=3, scale_pos_weight=spw_fold)
}
best_params_all[[outer_idx]]<-best_params
## Training outer model and predicting on validation fold
dtrain_outer<-xgboost::xgb.DMatrix(data=X_tr, label=y_tr)
mod<-xgboost::xgb.train(params=best_params, data=dtrain_outer, nrounds=100, verbose=0)
oof_preds[val_idx]<-predict(mod, xgboost::xgb.DMatrix(X_val))
}
return(oof_preds)
}
#- - - - - -
## Fitting XGBoost ERS model on doubly-adjusted exposures with nested CV
#
# scale_pos_weight is computed per outer fold to account for class imbalance.
#
# Arguments:
# - dataset_dt: dataset with binary outcome in col 1, residualized exposures in remaining cols
# - target_col: name of the binary outcome column (0/1)
# - feature_cols: vector of residualized exposure column names
# - ers_metric: metric for hyperparameter tuning and best fold selection (one of: "AUROC" (higher=better), "F1" (higher=better), "LogLoss" (lower=better))
# - train_split, test_split: dataset split proportions (training and holdout test)
# - nb_inner_fold, nb_outer_fold: number of folds for nested CV
# - param_grid: optional custom hyperparameter grid
fit_ers_binary<-function(dataset_dt,
target_col,
feature_cols,
ers_metric="AUROC",
train_split=0.7,
test_split=0.3,
nb_inner_fold=5,
nb_outer_fold=5,
param_grid=NULL){
## Validating ers_metric
valid_metrics<-c("AUROC","F1","LogLoss")
if(!ers_metric %in% valid_metrics){
stop("ers_metric not recognised. Please choose one of:\n",
"'AUROC': area under the ROC curve (recommended for balanced or moderately imbalanced datasets)\n",
"'F1': harmonic mean of precision and recall (recommended when class imbalance is a concern)\n",
"'LogLoss': log-loss / cross-entropy (recommended when predicted probability calibration matters)",
call.=FALSE)
}
## Mapping ers_metric to the corresponding native XGBoost eval_metric: AUROC -> "auc", LogLoss -> "logloss", F1 -> "aucpr" (best native XGBoost proxy for F1)
xgb_eval_metric<-switch(ers_metric,
"AUROC"="auc",
"LogLoss"="logloss",
"F1"="aucpr")
## Whether higher or lower is better for the chosen eval_metric
higher_better_inner<-switch(ers_metric,
"AUROC"=TRUE,
"LogLoss"=FALSE,
"F1"=TRUE)
## Ensuring splits are in correct format
train_split<-as.numeric(train_split)
test_split<-as.numeric(test_split)
if((train_split+test_split>1)|is.na(test_split)|is.na(train_split)){
train_split<-0.7
test_split<-0.3
}
## Ensuring fold numbers are in correct format
nb_inner_fold<-as.numeric(nb_inner_fold)
if(is.na(nb_inner_fold)|nb_inner_fold<2) nb_inner_fold<-5
nb_outer_fold<-as.numeric(nb_outer_fold)
if(is.na(nb_outer_fold)|nb_outer_fold<2) nb_outer_fold<-5
## Creating a stratified train/test split (stratified on Y to preserve class balance)
data_split<-splitTools::partition(y=dataset_dt[[target_col]],
p=c(train=train_split, test=test_split),
type="stratified", seed=seed)
## Creating training and test datasets
X_train<-as.matrix(dataset_dt[data_split$train, ..feature_cols])
y_train<-as.integer(dataset_dt[[target_col]][data_split$train])
X_test<-as.matrix(dataset_dt[data_split$test, ..feature_cols])
y_test<-as.integer(dataset_dt[[target_col]][data_split$test])
## Computing global scale_pos_weight (ratio of majority to minority class)
spw<-max(table(y_train))/min(table(y_train))
## Default parameter grid if none provided
if(is.null(param_grid)){
param_grid<-expand.grid(subsample=seq(0.5,1,0.25),
colsample_bytree=seq(0.5,1,0.25),
min_child_weight=c(1,5,10),
learning_rate=c(0.05,0.1,0.3),
max_depth=c(3,5,7)) %>%
dplyr::slice_sample(n=30, replace=TRUE) # Limiting space to 30 combinations for computational efficiency and environmental sustainability considerations
}
## Creating outer folds for nested CV
outer_folds<-splitTools::create_folds(y_train, k=nb_outer_fold, type="stratified", seed=seed)
outer_results<-list()
best_params_all<-list()
for(outer_idx in seq_along(outer_folds)){
val_idx<-outer_folds[[outer_idx]]
train_idx_cv<-setdiff(seq_len(nrow(X_train)), val_idx)
X_tr<-X_train[train_idx_cv,, drop=FALSE]
y_tr<-y_train[train_idx_cv]
X_val<-X_train[val_idx,, drop=FALSE]
y_val<-y_train[val_idx]
## Skipping outer fold if it contains only one class (cannot evaluate)
if(length(unique(y_val))<2){
cat("Outer fold",outer_idx,": skipped (single class in validation set)\n")
best_params_all[[outer_idx]]<-NULL
next
}
## Computing scale_pos_weight per outer fold
spw_fold<-max(table(y_tr))/min(table(y_tr))
## Initializing best performance tracker for inner CV
best_inner_perf<-if(higher_better_inner) -Inf else Inf
best_params<-NULL
for(i in seq_len(nrow(param_grid))){
## Building parameter list with the eval_metric matching the chosen ers_metric
params_i<-list(objective="binary:logistic",
eval_metric=xgb_eval_metric,
subsample=param_grid$subsample[i],
colsample_bytree=param_grid$colsample_bytree[i],
min_child_weight=param_grid$min_child_weight[i],
learning_rate=param_grid$learning_rate[i],
max_depth=param_grid$max_depth[i],
scale_pos_weight=spw_fold)
dtrain_inner<-xgboost::xgb.DMatrix(data=X_tr, label=y_tr)
## Inner CV via xgb.cv with stratified=TRUE to guarantee both classes in every inner fold
cv_res<-tryCatch(suppressWarnings(xgboost::xgb.cv(params=params_i,data=dtrain_inner,nrounds=100,nfold=nb_inner_fold,early_stopping_rounds=10,verbose=0,stratified=TRUE)),
error=function(e) NULL)
if(is.null(cv_res)) next
## Extracting best performance across rounds for the chosen metric
metric_col<-paste0("test_",xgb_eval_metric,"_mean")
mean_perf<-tryCatch({
vals<-cv_res$evaluation_log[[metric_col]]
if(higher_better_inner) max(vals, na.rm=TRUE) else min(vals, na.rm=TRUE)
}, error=function(e) NA)
if(!is.na(mean_perf)){
better<-if(higher_better_inner) mean_perf>best_inner_perf else mean_perf<best_inner_perf
if(better){
best_inner_perf<-mean_perf
best_params<-params_i
}
}
}
## Fallback to default params if all tuning attempts failed
if(is.null(best_params)){
best_params<-list(objective="binary:logistic",
eval_metric=xgb_eval_metric,
subsample=1,
colsample_bytree=1,
min_child_weight=1,
learning_rate=0.1,
max_depth=3,
scale_pos_weight=spw_fold)
}
best_params_all[[outer_idx]]<-best_params
## Training outer model and evaluating on outer validation fold
dtrain_outer<-xgboost::xgb.DMatrix(data=X_tr, label=y_tr)
xgb_outer<-xgboost::xgb.train(params=best_params,data=dtrain_outer,nrounds=100,verbose=0)
val_pred<-predict(xgb_outer, xgboost::xgb.DMatrix(X_val))
## Finding optimal classification threshold on the outer training fold predictions
tr_pred<-predict(xgb_outer, xgboost::xgb.DMatrix(X_tr))
opt_threshold<-find_optimal_threshold(tr_pred, y_tr, ers_metric)
val_pred_bin<-as.integer(val_pred >= opt_threshold)
## Computing all performance metrics on outer fold
AUROC<-tryCatch(as.numeric(pROC::auc(pROC::roc(y_val, val_pred, quiet=TRUE))), error=function(e) NA)
F1<-tryCatch(MLmetrics::F1_Score(val_pred_bin, y_val),error=function(e) NA)
logloss<-tryCatch(MLmetrics::LogLoss(val_pred, y_val), error=function(e) NA)
PRAUC<-tryCatch(MLmetrics::PRAUC(val_pred, y_val), error=function(e) NA)
Sensitivity<-tryCatch(MLmetrics::Sensitivity(val_pred_bin, y_val), error=function(e) NA)
Specificity<-tryCatch(MLmetrics::Specificity(val_pred_bin, y_val), error=function(e) NA)
Balanced_accuracy<-tryCatch((Sensitivity+Specificity)/2, error=function(e) NA)
outer_results[[outer_idx]]<-data.frame(Fold=outer_idx, AUROC=AUROC, PRAUC=PRAUC,F1=F1, LogLoss=logloss,Sensitivity=Sensitivity, Specificity=Specificity,
Balanced_accuracy=Balanced_accuracy)
}
outer_summary<-dplyr::bind_rows(outer_results)
cat("\nNested CV summary (all metrics):\n")
print(outer_summary)
cat("\nMetric used for hyperparameter selection:",ers_metric,"(XGBoost eval_metric:",xgb_eval_metric,")\n")
## Selecting best outer fold based on the chosen metric
best_idx<-switch(ers_metric,
"AUROC"=which.max(outer_summary$AUROC),
"F1"=which.max(outer_summary$F1),
"LogLoss"=which.min(outer_summary$LogLoss))
final_params<-best_params_all[[best_idx]]
## Retraining final model on full training set with best hyperparameters
final_params$scale_pos_weight<-spw
dtrain_full<-xgboost::xgb.DMatrix(data=X_train, label=y_train)
final_model<-xgboost::xgb.train(params=final_params,data=dtrain_full,nrounds=100,verbose=0)
## Finding optimal threshold on full training set predictions
train_preds_for_thr<-predict(final_model, xgboost::xgb.DMatrix(X_train))
final_threshold<-find_optimal_threshold(train_preds_for_thr, y_train, ers_metric)
## Computing OOF predictions on the full dataset (train + test)
# - Train: predicted by per-fold models (each observation predicted by model not trained on it)
# - Test: predicted by final model (trained on train only, no leakage)
oof_preds_full<-rep(NA, nrow(dataset_dt))
for(outer_idx in seq_along(outer_folds)){
if(is.null(best_params_all[[outer_idx]])) next
val_idx_global<-data_split$train[outer_folds[[outer_idx]]]
train_idx_cv<-setdiff(seq_len(length(data_split$train)), outer_folds[[outer_idx]])
X_tr_oof<-X_train[train_idx_cv,, drop=FALSE]
y_tr_oof<-y_train[train_idx_cv]
spw_oof <-max(table(y_tr_oof))/min(table(y_tr_oof))
## Updating scale_pos_weight for this OOF fold while keeping all other best params
params_oof<-best_params_all[[outer_idx]]
params_oof$scale_pos_weight<-spw_oof
dtrain_oof<-xgboost::xgb.DMatrix(data=X_tr_oof, label=y_tr_oof)
mod_oof<-xgboost::xgb.train(params=params_oof, data=dtrain_oof, nrounds=100, verbose=0)
oof_preds_full[val_idx_global]<-predict(mod_oof,xgboost::xgb.DMatrix(X_train[outer_folds[[outer_idx]],, drop=FALSE]))
}
## For test observations: use final model (no leakage since it was trained on train only)
oof_preds_full[data_split$test]<-predict(final_model, xgboost::xgb.DMatrix(X_test))
## Test set performance (all metrics computed regardless of ers_metric)
test_preds<-predict(final_model, xgboost::xgb.DMatrix(X_test))
test_preds_bin<-as.integer(test_preds >= final_threshold)
test_preds_fac<-factor(test_preds_bin,levels=c(0,1))
y_test_fac<-factor(y_test,levels=c(0,1))
## Computing performance metrics
roc_curve_test<-pROC::roc(y_test, test_preds, quiet=TRUE)
AUROC_test<-as.numeric(pROC::auc(roc_curve_test))
AUC_CI<-signif(pROC::ci.auc(roc_curve_test), 3)
AUC_CI_str<-paste(AUC_CI[2]," (",AUC_CI[1],"; ",AUC_CI[3],")", sep="")
F1_test<-tryCatch(MLmetrics::F1_Score(test_preds_bin, y_test), error=function(e) NA)
logloss_test<-tryCatch(MLmetrics::LogLoss(test_preds, y_test), error=function(e) NA)
PRAUC_test<-tryCatch(MLmetrics::PRAUC(test_preds, y_test),error=function(e) NA)
conf_mat<-caret::confusionMatrix(factor(test_preds_bin), factor(y_test), mode="everything", positive="1")
Sensitivity_test<-conf_mat$byClass[["Sensitivity"]]
Specificity_test<-conf_mat$byClass[["Specificity"]]
Balanced_accuracy_test<-(Sensitivity_test+Specificity_test)/2
PPV_test<-conf_mat$byClass[["Pos Pred Value"]]
NPV_test<-conf_mat$byClass[["Neg Pred Value"]]
cat("\nTest set performance (all metrics):\n")
cat("AUROC:",round(AUROC_test,3),"[",AUC_CI_str,"]\n")
cat("PRAUC:",round(PRAUC_test,3)," F1:",round(F1_test,3)," LogLoss:",round(logloss_test,3),"\n")
cat("Sensitivity:",round(Sensitivity_test,3)," Specificity:",round(Specificity_test,3)," Balanced accuracy:",round(Balanced_accuracy_test,3),"\n")
cat("PPV:",round(PPV_test,3)," NPV:",round(NPV_test,3),"\n")
cat("Metric used for model selection:",ers_metric,"\n")
metric_test<-as_tibble(data.frame(metric_used_for_selection=ers_metric,AUROC=AUROC_test, AUROC_CI=AUC_CI_str,PRAUC=PRAUC_test, F1=F1_test,
LogLoss=logloss_test,Sensitivity=Sensitivity_test, Specificity=Specificity_test,Balanced_accuracy=Balanced_accuracy_test,
PPV=PPV_test, NPV=NPV_test))
return(list(oof_preds=oof_preds_full,
test_preds=test_preds,
final_model=final_model,
outer_summary=outer_summary,
final_params=final_params,
data_split=data_split,
metric_test=metric_test,
X_test=X_test,
y_test=y_test))
}
#----------------------------------------------------------------
#### Settings ####
## Set to TRUE if data comes from multiple cohorts (activates Step 1)
use_cohort<-TRUE
## Names of covariates to adjust for in Step 2
cov_names<-c("age","sex","bmi")
## Metric used for ERS model (Step 3) hyperparameter tuning and best fold selection. Choose one of:
# - "AUROC": area under the ROC curve -> recommended for balanced or moderately imbalanced datasets
# - "F1": harmonic mean of precision/recall -> recommended when class imbalance is a concern
# - "LogLoss": log-loss / cross-entropy -> recommended when predicted probability calibration matters
ers_metric<-"AUROC"
#----------------------------------------------------------------
#### Data import and preprocessing (replace simulation with your own data) ####
## Simulating data
set.seed(seed)
n<-800
K<-8
## Simulating continuous exposures
expo_df<-as.data.frame(exp(MASS::mvrnorm(n,rep(0,K),0.5^as.matrix(dist(1:K)))/3))
## Simulating a binary exposure
expo_df2<-data.frame(X9=sample(x=c(0,1),n,replace=TRUE))
expo_df<-bind_cols(expo_df,expo_df2)
colnames(expo_df)<-paste0("X",1:(K+1))
expo_names<-colnames(expo_df)
## Building exposure matrix: log1p for continuous, untransformed for binary
expo_mat<-as.matrix(cbind(log1p(expo_df[,paste0("X",1:K)]), # log-transform continuous only
expo_df[,"X9",drop=FALSE])) # binary untransformed
colnames(expo_mat)<-expo_names
## Covariates and cohort
cov_df<-data.frame(age=rnorm(n,50,10),sex=rbinom(n,1,0.5),bmi=rnorm(n,26,4))
cohort<-sample(c("cohort_A","cohort_B","cohort_C"),n,replace=TRUE)
## Cohort effect on the log-odds scale
cohort_eff<-ifelse(cohort=="cohort_A",0,ifelse(cohort=="cohort_B",1.5,-1))
## True exposure effect (i.e., what ERS should capture after removing cohort + covariate effects)
h_z<-as.numeric(as.matrix(expo_mat)%*%c(0.5,0.3,-0.2,0.1,0.4,-0.1,0.05,0.05,1))
## Computing the linear predictor without intercept
log_odds_no_intercept<-0.03*cov_df$age + 0.5*cov_df$sex + 0.1*cov_df$bmi + cohort_eff + h_z
## Calibrating intercept so that prevalence is around 50%
intercept_calibrated<- -median(log_odds_no_intercept)
## Binary outcome via logistic link
y<-rbinom(n, 1, plogis(intercept_calibrated + log_odds_no_intercept))
cat("Observed prevalence:", round(mean(y),3), "- Cases:", sum(y==1), "- Controls:", sum(y==0), "\n")
## Assembling full dataset
sim_data<-cbind(data.frame(y=y,cohort=cohort),cov_df,expo_mat)
## Names of binary exposures in your dataset (all others treated as continuous/ordinal)
expo_binary<-c("X9") # adapt to your data
#----------------------------------------------------------------
#### Step 1 (optional): adjusting exposures for cohort membership (only if multi-cohort) ####
# Goal: to remove between-cohort differences from each exposure so that the ERS is not driven by which cohort a participant belongs to.
# - Residualization is applied to exposures (not Y) to preserve the binary nature of Y.
# - DML framework: W_j = X_j - E[X_j | cohort].
# - All exposures use binary:logistic after [0,1] rescaling (see fit_adjustment_oof).
# Method:
# - for each exposure X_j, fit XGBoost (binary:logistic on rescaled X_j) predicting X_j from cohort.
# - W_j = X_j - predicted(cohort): exposure cleaned of cohort effects.
# - OOF predictions used for all observations to avoid overfitting residuals.
# Output:
# - expo_mat_W: matrix of exposure residuals after cohort adjustment
# - All binary metrics (exposure ~ Y) before and after adjustment
if(use_cohort){
## One-hot encoding of cohort membership (no intercept to avoid collinearity)
Z_mat<-model.matrix(~as.factor(sim_data$cohort)-1)
colnames(Z_mat)<-paste0("cohort_",levels(as.factor(sim_data$cohort)))
## Residualizing each exposure on cohort. W_j = X_j - E[X_j | cohort]
cat("\nStep 1 - adjusting all exposures for cohort\n")
expo_hat_cohort_list<-lapply(expo_names, function(j){
is_bin<-j %in% expo_binary
cat("Adjusting:",j, if(is_bin) "[binary]" else "[continuous]","\n")
fit_adjustment_oof(X=Z_mat, y=expo_mat[,j],is_binary_exposure=is_bin,nb_outer_fold=5, nb_inner_fold=5)
})
expo_hat_cohort<-do.call(cbind,expo_hat_cohort_list)
colnames(expo_hat_cohort)<-expo_names
## W = X - E[X|cohort]: exposures cleaned of cohort effects
expo_mat_W<-expo_mat-expo_hat_cohort
## All binary metrics (exposure ~ Y) before and after cohort adjustment
metrics_before_cohort<-do.call(rbind,lapply(expo_names,function(j)
cbind(data.frame(exposure=j,adjustment="before"),compute_binary_metrics(expo_mat[,j],y))))
metrics_after_cohort<-do.call(rbind,lapply(expo_names,function(j)
cbind(data.frame(exposure=j,adjustment="after"),compute_binary_metrics(expo_mat_W[,j],y))))
metrics_cohort<-bind_rows(metrics_before_cohort,metrics_after_cohort)
cat("\nAll binary metrics (exposure ~ Y) before and after cohort adjustment:\n")
metrics_cohort %>% pivot_wider(names_from=adjustment, values_from=c(AUROC,PRAUC,F1,LogLoss,Sensitivity,Specificity,Balanced_accuracy))
}else{
expo_mat_W<-expo_mat
}
#----------------------------------------------------------------
#### Step 2: adjusting exposures for covariates ####
# Second DML stage: W2_j = W_j - E[W_j | covariates].
# Goal: to remove the effects of age, sex, BMI or any other covariates from each exposure so that the ERS captures only the exposure-specific signal independent of classical covariates.
cov_mat<-as.matrix(sim_data[,cov_names])
## Adjusting each exposure residual for covariates. W2_j = W_j - E[W_j | covariates]
cat("\nStep 2 - adjusting all exposures for covariates\n")
expo_hat_cov_list<-lapply(expo_names,function(j){
is_bin<-j %in% expo_binary
cat("Adjusting:",j, if(is_bin) "[binary]" else "[continuous]","\n")
fit_adjustment_oof(X=cov_mat,y=expo_mat_W[,j],is_binary_exposure=is_bin,nb_outer_fold=5,nb_inner_fold=5)
})
expo_hat_cov<-do.call(cbind,expo_hat_cov_list)
colnames(expo_hat_cov)<-expo_names
## W2 = W - E[W|covariates]: exposures cleaned of both cohort and covariate effects
expo_mat_W2<-expo_mat_W-expo_hat_cov
## All binary metrics (exposure ~ Y) before and after covariate adjustment
metrics_before_cov<-do.call(rbind,lapply(expo_names,function(j)
cbind(data.frame(exposure=j,adjustment="before"),compute_binary_metrics(expo_mat_W[,j],y))))
metrics_after_cov<-do.call(rbind,lapply(expo_names,function(j)
cbind(data.frame(exposure=j,adjustment="after"),compute_binary_metrics(expo_mat_W2[,j],y))))
metrics_cov<-bind_rows(metrics_before_cov,metrics_after_cov)
cat("\nAll binary metrics (exposure ~ Y) before and after covariate adjustment:\n")
metrics_cov %>% pivot_wider(names_from=adjustment, values_from=c(AUROC,PRAUC,F1,LogLoss,Sensitivity,Specificity,Balanced_accuracy))
#----------------------------------------------------------------
#### Step 3: Fitting ERS model on doubly-adjusted exposures (nested CV) ####
# Goal: to model the binary outcome Y using doubly-adjusted exposures W2 only. Because exposures have been cleaned of cohort and covariate effects (Steps 1-2),
# the predicted log-odds f(W2) represent the exposure-driven component of Y (= ERS), cleanly separated from cohort and covariate effects.
colnames(expo_mat_W2)<-expo_names
dataset_step3<-as.data.table(cbind(data.frame(y=y),as.data.frame(expo_mat_W2)))
step3_result<-fit_ers_binary(dataset_dt=dataset_step3,
target_col="y",
feature_cols=expo_names,
ers_metric=ers_metric,
train_split=0.7,
test_split=0.3,
nb_outer_fold=5,
nb_inner_fold=5)
## ERS = predicted log-odds from doubly-adjusted exposures on the full dataset
ers<-predict(step3_result$final_model,xgboost::xgb.DMatrix(expo_mat_W2))
sim_data$ers<-ers
## Evaluating ERS against the original binary outcome
ers_metrics_full<-compute_binary_metrics(ers,y)
roc_ers<-pROC::roc(y,ers,quiet=TRUE)
AUROC_ers<-round(as.numeric(pROC::auc(roc_ers)),3)
AUC_CI_ers<-signif(pROC::ci.auc(roc_ers),3)