-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathERS_survival.R
More file actions
1603 lines (1313 loc) · 65.7 KB
/
Copy pathERS_survival.R
File metadata and controls
1603 lines (1313 loc) · 65.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
#-------------------------------------------------------------------------------
## Reproducible and generalisable script for calculating an exposomic risk score (ERS) for a survival outcome using XGBoost with nested cross-validation
#
# Method: Double Machine Learning (DML) - residualizing exposures on adjustment variables (cohort membership and/or covariates) to preserve the survival outcome structure.
#
# 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 partial hazard from doubly-adjusted exposures
#
# How to use the ERS in a final model:
# - coxph(Surv(time, event) ~ ers + age + sex + bmi, data=sim_data)
# - or stratify into tertiles for HR and KM curves.
#
# Settings to adjust before running:
# - use_cohort: TRUE/FALSE
# - cov_names: names of covariate adjustment variables
# - surv_time_col: name of the time-to-event column
# - surv_event_col: name of the event indicator column (1=event, 0=censored)
#-------------------------------------------------------------------------------
#----------------------------------------------------------------
#### Configurations ####
## Disabling memory torture
gctorture(FALSE)
## Installing and loading packages
pack_needed<-c("data.table","tidyverse","mllrnrs","mlsurvlrnrs","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","survival","survminer","ggkm","R6","kdry","pROC","iml","ggsurvfit",
"gtsummary","GGally","cmprsk","tidycmprsk","ggstats")
if(!("ggkm"%in%.packages(all.available=TRUE))){
pak::pak("sachsmc/ggkm")
}
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")
conflicts_prefer(caret::lift)
## Setting the working directory
here::here("XGBoost - ERS calculation - survival 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%')
#- - - - - -
## Computing concordance-based metrics between an exposure (or its residual) and the survival outcome
#
# Interpretation: a C-index > 0.5 means the exposure tends to rank higher-risk individuals correctly.
compute_survival_metrics<-function(x_vec, surv_time, surv_event){
x_num<-as.numeric(x_vec)
## C-index (Harrell's concordance index)
cindex<-tryCatch({
srv<-Surv(time=surv_time, event=surv_event)
round(survival::concordance(srv~x_num)$concordance, 3)
}, error=function(e) NA)
## Log partial hazard association via univariate Cox (log hazard ratio + p-value)
cox_res<-tryCatch({
df_tmp<-data.frame(time=surv_time, event=surv_event, x=x_num)
fit<-survival::coxph(Surv(time, event)~x, data=df_tmp)
s<-summary(fit)
list(logHR=round(coef(fit),3),
HR=round(exp(coef(fit)),3),
p=round(s$logtest["pvalue"],3))
}, error=function(e) list(logHR=NA, HR=NA, p=NA))
return(data.frame(C_index=cindex,
logHR=cox_res$logHR,
HR=cox_res$HR,
Cox_p=cox_res$p))
}
#- - - - - -
## Fitting XGBoost with nested CV for exposure adjustment (one exposure at a time)
#
# Rationale:
# - this function residualizes an exposure 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)
}
#- - - - - -
## Custom survival XGBoost learner with sample weight support
#
# Method: Inherits from mlsurvlrnrs::LearnerSurvXgboostCox and adds per-observation weights to account for event imbalance (few events vs. many censored observations).
LearnerSurvXgboostCoxWeighted<-R6::R6Class(classname="LearnerSurvXgboostCoxWeighted",inherit=mlsurvlrnrs::LearnerSurvXgboostCox,
public=list(sample_weight=NULL,
set_sample_weight=function(w){ self$sample_weight<-w },
train=function(x, y, ...){
if(!is.null(self$sample_weight)){
super$train(x=x, y=y, sample_weight=self$sample_weight, ...)
}else{
super$train(x=x, y=y, ...)
}
}))
#- - - - - -
## Fitting XGBoost ERS model on doubly-adjusted exposures with nested CV
#
# Method : Performance is measured by Harrell's C-index (concordance index), with higher C-index = better discrimination of event timing.
#
## Arguments:
# - dataset_dt: data.table with time and event columns + residualized exposures
# - surv_time_col: name of the time-to-event column
# - surv_event_col: name of the event indicator column (1=event, 0=censored)
# - feature_cols: vector of doubly-adjusted exposure column names
# - train_split, test_split: dataset split proportions
# - nb_inner_fold, nb_outer_fold: number of folds for nested CV
# - param_grid: optional custom hyperparameter grid
#
# Outputs (list):
# - oof_preds: OOF predicted log partial hazard scores for the full dataset
# - test_preds: predicted scores on holdout test set
# - metric_test: C-index and Cox performance on test set
# - final_model: model retrained on full training set with best hyperparameters
# - outer_summary: CV C-index summary
# - final_params: best hyperparameters selected
fit_ers_survival<-function(dataset_dt,
surv_time_col,
surv_event_col,
feature_cols,
train_split=0.7,
test_split=0.3,
nb_inner_fold=5,
nb_outer_fold=5,
param_grid=NULL){
## 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
## Extracting survival outcome
surv_time<-as.numeric(dataset_dt[[surv_time_col]])
surv_event<-as.integer(dataset_dt[[surv_event_col]])
## Creating stratified train/test split using kmeans multi-strata on (time, event) to ensure both splits have similar event rates and time distributions
surv_cols_dt<-dataset_dt[, .SD, .SDcols=c(surv_time_col, surv_event_col)]
split_vector<-splitTools::multi_strata(df=surv_cols_dt, strategy="kmeans", k=4)
data_split<-splitTools::partition(y=split_vector, p=c(train=train_split, test=test_split),type="stratified", seed=seed)
## Verifying no overlap between train and test
stopifnot(length(intersect(data_split$train, data_split$test))==0)
## Creating training and test datasets
X_train<-as.matrix(dataset_dt[data_split$train, ..feature_cols])
t_train<-surv_time[data_split$train]
e_train<-surv_event[data_split$train]
y_train<-Surv(time=t_train, event=e_train)
X_test<-as.matrix(dataset_dt[data_split$test, ..feature_cols])
t_test<-surv_time[data_split$test]
e_test<-surv_event[data_split$test]
y_test<-Surv(time=t_test, event=e_test)
## Computing sample weights to account for event imbalance (observations with rare events receive higher weight)
event_dt<-data.table(event=e_train)
event_counts<-event_dt[, .N, by=event][, weight:=1/N]
train_weights<-event_counts[event_dt, on="event", weight]
## Creating stratified CV folds on training set (stratified on survival strata)
surv_cols_train<-dataset_dt[data_split$train, .SD, .SDcols=c(surv_time_col, surv_event_col)]
split_vector_train<-splitTools::multi_strata(df=surv_cols_train, strategy="kmeans", k=4)
outer_folds<-splitTools::create_folds(y=split_vector_train, k=nb_outer_fold, type="stratified",seed=seq(1,nb_outer_fold,1)*seed)
## Default parameter grid if none provided
if(is.null(param_grid)){
param_grid<-expand.grid(learning_rate=c(0.05,0.1),
max_depth=c(3,4,5),
min_child_weight=c(5,10,20),
subsample=c(0.7,0.9,1.0),
colsample_bytree=c(0.7,0.9,1.0),
nrounds=c(50,100,200)) %>%
dplyr::slice_sample(n=30, replace=FALSE) # Limiting space to 30 combinations for computational efficiency and environmental sustainability considerations
}
## Defining learner arguments
learner_args<-list(objective="survival:cox", eval_metric="cox-nloglik", nthread=ncores)
## Outer CV
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]
t_tr<-t_train[train_idx_cv]
e_tr<-e_train[train_idx_cv]
w_tr<-train_weights[train_idx_cv]
X_val<-X_train[val_idx,,drop=FALSE]
y_val<-y_train[val_idx]
t_val<-t_train[val_idx]
e_val<-e_train[val_idx]
## Skipping outer fold if it contains no events (C-index undefined)
if(sum(e_val)==0){
cat("Outer fold",outer_idx,": skipped (no events in validation set)\n")
best_params_all[[outer_idx]]<-NULL
next
}
## Inner CV folds
surv_cols_tr<-data.table(time=t_tr, event=e_tr)
split_vec_tr<-splitTools::multi_strata(df=surv_cols_tr, strategy="kmeans", k=4)
inner_folds<-splitTools::create_folds(y=split_vec_tr, k=nb_inner_fold, type="stratified",seed=seq(1,nb_inner_fold,1)*seed)
## Hyperparameter tuning using weighted survival Cox learner
learner_inner<-LearnerSurvXgboostCoxWeighted$new(metric_optimization_higher_better=FALSE)
learner_inner$set_sample_weight(w_tr)
best_nloglik<-Inf
best_params<-NULL
for(i in seq_len(nrow(param_grid))){
xgb_cv<-mlexperiments::MLCrossValidation$new(learner=learner_inner,fold_list=inner_folds,ncores=ncores,seed=seed)
xgb_cv$learner_args<-c(as.list(param_grid[i,]), learner_args)
xgb_cv$performance_metric<-c_index
xgb_cv$set_data(x=X_tr, y=y_tr)
res_cv<-tryCatch(xgb_cv$execute(), error=function(e) NULL)
if(is.null(res_cv)) next
## Extracting mean cox-nloglik (lower = better) across inner folds
mean_nloglik<-tryCatch(
mean(sapply(res_cv$results$folds, function(f){
val<-tryCatch(f$performance, error=function(e) NA)
if(is.list(val)) val<-unlist(val)
as.numeric(val[1])
}), na.rm=TRUE),
error=function(e) NA)
if(!is.na(mean_nloglik)&&mean_nloglik<best_nloglik){
best_nloglik<-mean_nloglik
best_params<-as.list(param_grid[i,])
}
}
## Fallback to default params if tuning failed
if(is.null(best_params)) best_params<-list(learning_rate=0.1,
max_depth=3,
min_child_weight=10,
subsample=0.7,
colsample_bytree=0.7,
nrounds=100)
best_params_all[[outer_idx]]<-best_params
## Training outer model and evaluating C-index on outer validation fold
learner_outer<-LearnerSurvXgboostCoxWeighted$new(metric_optimization_higher_better=FALSE)
learner_outer$set_sample_weight(w_tr)
mod_outer<-learner_outer$fit(x=X_tr, y=y_tr, seed=seed, ncores=ncores,
objective=learner_args$objective,
eval_metric=learner_args$eval_metric,
subsample=best_params$subsample,
colsample_bytree=best_params$colsample_bytree,
min_child_weight=best_params$min_child_weight,
learning_rate=best_params$learning_rate,
nrounds=best_params$nrounds,
max_depth=best_params$max_depth)
val_pred<-predict(mod_outer, xgboost::xgb.DMatrix(X_val))
## C-index on outer validation fold
cindex_val<-tryCatch(round(survival::concordance(Surv(t_val,e_val)~val_pred)$concordance, 3),error=function(e) NA)
outer_results[[outer_idx]]<-data.frame(Fold=outer_idx, C_index=cindex_val)
}
outer_summary<-dplyr::bind_rows(outer_results)
cat("\nNested CV summary (C-index per outer fold):\n")
print(outer_summary)
cat("\nOuter mean C-index:", round(mean(outer_summary$C_index, na.rm=TRUE), 3),
"SD:", round(sd(outer_summary$C_index, na.rm=TRUE), 3), "\n")
## Selecting best hyperparameters based on highest outer CV C-index
best_idx<-which.max(outer_summary$C_index)
final_params<-best_params_all[[best_idx]]
## Retraining final model on full training set
learner_final<-LearnerSurvXgboostCoxWeighted$new(metric_optimization_higher_better=FALSE)
learner_final$set_sample_weight(train_weights)
final_model<-learner_final$fit(x=X_train, y=y_train, seed=seed, ncores=ncores,
objective=learner_args$objective,
eval_metric=learner_args$eval_metric,
subsample=final_params$subsample,
colsample_bytree=final_params$colsample_bytree,
min_child_weight=final_params$min_child_weight,
learning_rate=final_params$learning_rate,
nrounds=final_params$nrounds,
max_depth=final_params$max_depth)
## Computing OOF predicted log partial hazard scores on the full dataset
# - train: predicted by per-fold models (each observation not seen during training)
# - test: predicted by final model (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]
w_tr_oof<-train_weights[train_idx_cv]
learner_oof<-LearnerSurvXgboostCoxWeighted$new(metric_optimization_higher_better=FALSE)
learner_oof$set_sample_weight(w_tr_oof)
bp<-best_params_all[[outer_idx]]
mod_oof<-learner_oof$fit(x=X_tr_oof, y=y_tr_oof, seed=seed, ncores=ncores,
objective=learner_args$objective,
eval_metric=learner_args$eval_metric,
subsample=bp$subsample,
colsample_bytree=bp$colsample_bytree,
min_child_weight=bp$min_child_weight,
learning_rate=bp$learning_rate,
nrounds=bp$nrounds,
max_depth=bp$max_depth)
oof_preds_full[val_idx_global]<-predict(mod_oof,xgboost::xgb.DMatrix(X_train[outer_folds[[outer_idx]],,drop=FALSE]))
}
## For test observations: using final model
test_preds<-predict(final_model, xgboost::xgb.DMatrix(X_test))
oof_preds_full[data_split$test]<-test_preds
## Test set performance
cindex_test<-round(survival::concordance(Surv(t_test,e_test)~test_preds)$concordance, 3)
cox_test<-survival::coxph(Surv(t_test,e_test)~test_preds,data=data.frame(t_test=t_test, e_test=e_test, test_preds=test_preds))
cox_test_s<-summary(cox_test)
HR_test<-round(exp(coef(cox_test)), 3)
HR_CI_test<-round(exp(confint(cox_test)), 3)
HR_str<-paste(HR_test," (",HR_CI_test[1],"; ",HR_CI_test[2],")", sep="")
p_test<-round(cox_test_s$logtest["pvalue"], 3)
cat("\nTest set performance:\n")
cat("C-index:", cindex_test, "\n")
cat("HR (ERS):", HR_str, " LR p-value:", p_test, "\n")
metric_test<-as_tibble(data.frame(C_index=cindex_test,
HR_ERS=HR_test,
HR_CI=HR_str,
Cox_LR_pvalue=p_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,
t_test=t_test,
e_test=e_test))
}
#----------------------------------------------------------------
#### Settings ####
## Set to TRUE if data comes from multiple cohorts (activates Step 1)
use_cohort<-TRUE
## Names of survival outcome columns
surv_time_col<-"time" # name of the time-to-event column
surv_event_col<-"event" # name of the event indicator column (1=event, 0=censored)
## Names of covariates to adjust for in Step 2
cov_names<-c("age","sex","bmi")
#----------------------------------------------------------------
#### Data import and preprocessing (replace simulation with your own data) ####
## Simulating survival data for demonstration
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)]), expo_df[,"X9",drop=FALSE]))
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 hazard scale
cohort_eff<-ifelse(cohort=="cohort_A",0,ifelse(cohort=="cohort_B",0.3,-0.3))
## True exposure effect (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))
## Linear predictor on the log hazard scale, WITHOUT intercept
log_hazard_no_intercept<-0.02*cov_df$age + 0.3*cov_df$sex + 0.05*cov_df$bmi + cohort_eff + h_z
## Calibrating intercept so that the median event time (under Weibull) is centered around a target value (e.g., 10).
# - under Weibull(shape, scale), median = scale * (log(2))^(1/shape)
# - scale = exp(-log_hazard/shape) -> intercept shifts log_hazard so that median(scale) matches the target.
shape<-1.5
target_median_time<-10
target_scale<-target_median_time/(log(2)^(1/shape))
intercept_calibrated<- -shape*log(target_scale) - median(log_hazard_no_intercept)
log_hazard<-intercept_calibrated + log_hazard_no_intercept
## Simulating survival times from a Weibull model
scale<-exp(-log_hazard/shape)
surv_time_raw<-rweibull(n, shape=shape, scale=scale)
cat("Event time distribution (before censoring):\n")
cat("Median:", round(median(surv_time_raw),3),
"Mean:", round(mean(surv_time_raw),3),
"Max:", round(max(surv_time_raw),3), "\n")
## Simulating censoring times
target_censoring<-0.30
find_censoring_rate<-function(rate, surv_time_raw, seed_local){
set.seed(seed_local)
cens_time_tmp<-rexp(length(surv_time_raw), rate=rate)
mean(surv_time_raw > cens_time_tmp)
}
rate_grid<-exp(seq(log(1/(target_median_time*50)), log(1/(target_median_time*0.01)), length.out=300))
cens_props<-sapply(rate_grid, find_censoring_rate, surv_time_raw=surv_time_raw, seed_local=seed)
best_rate<-rate_grid[which.min(abs(cens_props - target_censoring))]
set.seed(seed)
cens_time<-rexp(n, rate=best_rate)
## Observed time and event indicator
obs_time <-pmin(surv_time_raw, cens_time)
obs_event<-as.integer(surv_time_raw <= cens_time)
cat("Event rate:", round(mean(obs_event),3),
"- Events:", sum(obs_event), "- Censored:", sum(obs_event==0), "\n")
cat("Median follow-up:", round(median(obs_time),3), "\n")
## Assembling full dataset
sim_data<-cbind(data.frame(time=obs_time, event=obs_event, cohort=cohort), cov_df, expo_mat)
dataset<-as.data.table(sim_data)
## 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 to preserve the time-to-event structure throughout. DML framework: W_j = X_j - E[X_j | cohort].
# Method:
# - for each exposure X_j, fit XGBoost 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
# - Survival metrics (C-index, HR) before and after adjustment per exposure
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)))
## Adjusting each exposure for cohort using lapply
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
## Survival metrics (exposure ~ survival outcome) before and after cohort adjustment
metrics_before_cohort<-do.call(rbind, lapply(expo_names, function(j)
cbind(data.frame(exposure=j, adjustment="before"),compute_survival_metrics(expo_mat[,j], obs_time, obs_event))))
metrics_after_cohort<-do.call(rbind, lapply(expo_names, function(j)
cbind(data.frame(exposure=j, adjustment="after"),compute_survival_metrics(expo_mat_W[,j], obs_time, obs_event))))
metrics_cohort<-bind_rows(metrics_before_cohort, metrics_after_cohort)
cat("\nSurvival metrics (exposure ~ outcome) before and after cohort adjustment:\n")
metrics_cohort %>% pivot_wider(names_from=adjustment,values_from=c(C_index,logHR,HR,Cox_p))
}else{
expo_mat_W<-expo_mat
}
#----------------------------------------------------------------
#### Step 2: adjusting exposures for covariates ####
# Goal: to remove covariate effects from each exposure residual so that the ERS captures only the exposure-specific association with survival, independent of covariates (e.g., age, sex, BMI)
# Second DML stage: W2_j = W_j - E[W_j | covariates].
cov_mat<-as.matrix(sim_data[,cov_names])
## Adjusting each exposure residual for 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
## Survival metrics (exposure ~ survival outcome) before and after covariate adjustment
metrics_before_cov<-do.call(rbind, lapply(expo_names, function(j)
cbind(data.frame(exposure=j, adjustment="before"),compute_survival_metrics(expo_mat_W[,j], obs_time, obs_event))))
metrics_after_cov<-do.call(rbind, lapply(expo_names, function(j)
cbind(data.frame(exposure=j, adjustment="after"),compute_survival_metrics(expo_mat_W2[,j], obs_time, obs_event))))
metrics_cov<-bind_rows(metrics_before_cov, metrics_after_cov)
cat("\nSurvival metrics (exposure ~ outcome) before and after covariate adjustment:\n")
metrics_cov %>% pivot_wider(names_from=adjustment,values_from=c(C_index,logHR,HR,Cox_p))
#----------------------------------------------------------------
#### Step 3: Fitting ERS model on doubly-adjusted exposures (nested CV) ####
## Goal: to model the survival outcome using doubly-adjusted exposures W2 only.
# The predicted log partial hazard f(W2) represents the exposure-driven component of the survival outcome (= ERS), cleanly separated from cohort and covariate effects
colnames(expo_mat_W2)<-expo_names
dataset_step3<-as.data.table(cbind(data.frame(time=obs_time, event=obs_event),as.data.frame(expo_mat_W2)))
step3_result<-fit_ers_survival(dataset_dt=dataset_step3,
surv_time_col=surv_time_col,
surv_event_col=surv_event_col,
feature_cols=expo_names,
train_split=0.7,
test_split=0.3,
nb_outer_fold=5,
nb_inner_fold=5)
## ERS = predicted log partial hazard from doubly-adjusted exposures on the full dataset
# Interpretation: higher ERS = higher predicted hazard -> higher risk
ers<-predict(step3_result$final_model, xgboost::xgb.DMatrix(expo_mat_W2))
sim_data$ers<-ers
## Evaluating ERS against the original survival outcome (full dataset)
ers_surv_metrics<-compute_survival_metrics(ers, obs_time, obs_event)
cindex_ers<-ers_surv_metrics$C_index
cat("\nERS performance against survival outcome (full dataset):\n")
cat("C-index:", cindex_ers, "\n")