-
Notifications
You must be signed in to change notification settings - Fork 1
/
survomics.qmd
2244 lines (1917 loc) · 105 KB
/
survomics.qmd
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
---
title: "Supplemental information for 'Tutorial on survival modeling with applications to omics data'"
date: last-modified
toc: true
toc-title: "**Table of Contents**"
---
```{r, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```
<br>
This is a step-by-step R tutorial using [The Cancer Genome Atlas](https://www.cancer.gov/about-nci/organization/ccg/research/structural-genomics/tcga) (TCGA) survival and omics data for the article [**_Tutorial on survival modeling with applications to omics data_**](https://doi.org/10.1093/bioinformatics/btae132) [@Zhao2024].
## Introduction {-}
The TCGA database provides an enormous collection of cancer data sets, including survival, clinical and multi-omics data.
:::{.callout-tip}
## We will use TCGA data to demonstrate:
- The different data types
- Preprocessing of survival and omics data
- Analysis of survival data by classical statistical methods
- Unsupervised learning for omics data
- Frequentist & Bayesian supervised learning for survival and omics data
:::
## TCGA survival and clinical data {-}
The R/Bioconductor package [**TCGAbiolinks**](https://bioconductor.org/packages/TCGAbiolinks/) [@Mounir2019] provides a few functions to download and preprocess clinical and multi-omics data from the [Genomic Data Commons](https://gdc.cancer.gov/) (GDC) Data Portal for further analysis.
First we load all necessary libraries used in this tutorial except [**mlr3** libraries](#mlr3) which will be introduced later.
Then we use function `GDCquery_clinic()` from **TCGAbiolinks** package to query and download TCGA survival and clinical data from multiple cancer types:
```{r}
#| code-fold: true
#| code-summary: "Show all R packages"
# load all libraries used in this tutorial except mlr3
library("TCGAbiolinks") # Bioconductor package
library("SummarizedExperiment") # Bioconductor package
library("DESeq2") # Bioconductor package
library("M3C") # Bioconductor package
library("dplyr")
library("ggplot2")
library("survival")
library("survminer")
library("glmnet")
library("plotmo")
library("grpreg")
library("SGL")
library("psbcGroup")
library("psbcSpeedUp")
library("BhGLM")
library("risksetROC")
library("riskRegression")
library("peperr")
library("c060")
library("rms")
library("survAUC")
library("regplot")
```
```{r}
# download the clinical data and extract data for multiple cancers using GDC api method
cancer_types <- c(
"TCGA-BLCA", "TCGA-BRCA", "TCGA-COAD", "TCGA-LIHC",
"TCGA-LUAD", "TCGA-PAAD", "TCGA-PRAD", "TCGA-THCA"
)
clin <- NULL
for (i in seq_along(cancer_types)) {
tmp <- TCGAbiolinks::GDCquery_clinic(project = cancer_types[i], type = "clinical")
clin <- rbind(clin, tmp[, c(
"project", "submitter_id", "vital_status",
"days_to_last_follow_up", "days_to_death",
"age_at_diagnosis", "gender", "race",
"ethnicity", "ajcc_pathologic_t"
)])
}
# extract the observed time for each patient and use years as unit
clin$time <- apply(clin[, c("days_to_death", "days_to_last_follow_up")], 1, max, na.rm = TRUE) / 365.25
clin$age <- clin$age_at_diagnosis / 365.25
clin$status <- clin$vital_status
clin <- clin[, c("project", "submitter_id", "status", "time", "gender", "age", "race", "ethnicity")]
# extract patients with positive overall survival time
clin <- clin[(clin$time > 0) & (clin$status %in% c("Alive", "Dead")), ]
# frequency table of the patients w.r.t. status, gender and ethnicity
clin %>%
dplyr::count(status, gender, ethnicity) %>%
group_by(status) %>%
mutate(prop = prop.table(n))
```
```{.border}
# A tibble: 12 × 5
# Groups: status [2]
status gender ethnicity n prop
<chr> <chr> <chr> <int> <dbl>
1 Alive female hispanic or latino 75 0.0240
2 Alive female not hispanic or latino 1367 0.438
3 Alive female not reported 328 0.105
4 Alive male hispanic or latino 34 0.0109
5 Alive male not hispanic or latino 1041 0.334
6 Alive male not reported 276 0.0884
7 Dead female hispanic or latino 7 0.00809
8 Dead female not hispanic or latino 377 0.436
9 Dead female not reported 64 0.0740
10 Dead male hispanic or latino 10 0.0116
11 Dead male not hispanic or latino 327 0.378
12 Dead male not reported 80 0.0925
```
```{r}
# censoring plot by cancer types
ID <- 1:nrow(clin)
clin %>%
ggplot(
aes(y = ID, x = time, colour = project, shape = factor(status))
) +
geom_segment(aes(x = time, y = ID, xend = 0, yend = ID)) +
geom_point() +
ggtitle("") +
labs(x = "Years", y = "Patients") +
scale_shape_discrete(name = "Status", labels = c("Censored", "Dead")) +
scale_color_discrete(
name = "Cancer",
labels = c("Bladder", "Breast", "Colon", "Liver", "Lung adeno", "Pancreatic", "Prostate", "Thyroid")
) +
theme(legend.position = "top", legend.direction = "vertical") +
guides(color = guide_legend(nrow = 2, byrow = TRUE))
```
![_Overall survival times and status of pan-cancer patients from TCGA._](fig/TCGA_survival.png){width=60%}
<br>
## TCGA omics data {-}
We use function `GDCquery()` to query and use `GDCdownload()` and `GDCprepare()` to download TCGA omics data from one cancer type (breast cancer).
The argument `data.category` in function `GDCquery()` specifies the type of omics data, such as `"Copy Number Variation"`, `"DNA Methylation"`, `"Transcriptome Profiling"`, `"Simple Nucleotide Variation"`.
Note that the downloaded omics data are accompanied by metadata including survival outcomes, clinical and demographic variables.
The accompanied metadata are almost the same as the clinical data downloaded via `GDCquery_clinic()` in the previous section but here only corresponding to one cancer type.
```{r}
# download TCGA breast cancer (BRCA) mRNA-Seq data using GDC api method
query <- TCGAbiolinks::GDCquery(
project = "TCGA-BRCA",
data.category = "Transcriptome Profiling",
data.type = "Gene Expression Quantification",
workflow.type = "STAR - Counts",
experimental.strategy = "RNA-Seq",
sample.type = c("Primary Tumor")
)
TCGAbiolinks::GDCdownload(query = query, method = "api")
dat <- TCGAbiolinks::GDCprepare(query = query)
SummarizedExperiment::assays(dat)$unstranded[1:5, 1:2]
```
```{r, echo=FALSE}
# save the downloaded large data on sever
save(dat, file = "TCGA_data.rda")
# load the downloaded large data and work on PC
load("TCGA_data.rda")
```
```{.border}
TCGA-A7-A26E-01B-06R-A277-07 TCGA-A2-A0CU-01A-12R-A034-07
ENSG00000000003.15 691 1429
ENSG00000000005.6 20 73
ENSG00000000419.13 335 1674
ENSG00000000457.14 1292 1018
ENSG00000000460.17 536 450
```
It is recommended to use DESeq2 or TMM normalization method for RNA-seq data before further statistical analysis [@ZhaoY2021].
Here we demonstrate how to use the R/Bioconductor package [**DESeq2**](https://bioconductor.org/packages/DESeq2/) [@Love2014] to normalize the RNA count data.
```{r}
meta <- colData(dat)[, c("project_id", "submitter_id", "age_at_diagnosis", "ethnicity", "gender", "days_to_death", "days_to_last_follow_up", "vital_status", "paper_BRCA_Subtype_PAM50", "treatments")]
meta$treatments <- unlist(lapply(meta$treatments, function(xx) {
any(xx$treatment_or_therapy == "yes")
}))
dds <- DESeq2::DESeqDataSetFromMatrix(assays(dat)$unstranded, colData = meta, design = ~1)
dds2 <- DESeq2::estimateSizeFactors(dds)
RNA_count <- DESeq2::counts(dds2, normalized = TRUE)
RNA_count[1:5, 1:2]
```
```{.border}
TCGA-A7-A26E-01B-06R-A277-07 TCGA-A2-A0CU-01A-12R-A034-07
ENSG00000000003.15 1899.76848 1419.51789
ENSG00000000005.6 54.98606 72.51561
ENSG00000000419.13 921.01656 1662.89219
ENSG00000000457.14 3552.09968 1011.24507
ENSG00000000460.17 1473.62649 447.01403
```
To perform survival analysis with both clinical/demographic variables and omics data, in the following code we extract female breast cancer patients with their corresponding survival outcomes, clinical/demographic variables and RNA-seq features.
```{r}
meta$time <- apply(meta[, c("days_to_death", "days_to_last_follow_up")], 1, max, na.rm = TRUE) / 365.25
meta$status <- meta$vital_status
meta$age <- meta$age_at_diagnosis / 365.25
clin <- subset(meta, gender == "female" & !duplicated(submitter_id) & time > 0 & !is.na(age))
clin <- clin[order(clin$submitter_id), ]
RNA_count <- RNA_count[, rownames(clin)]
```
:::{.callout-note}
- [Bioconductor](https://bioconductor.org/packages/release/bioc/html/TCGAbiolinks.html) might provide an outdated version of **TCGAbiolinks**.
Here, we use the GitHub version TCGAbiolinks_2.29.6.
If you encounter some issues when using this tutorial, please check your installed **TCGAbiolinks** version.
If necessary, you can re-install the package from its [GitHub repository](https://github.com/BioinformaticsFMRP/TCGAbiolinks.git).
Otherwise, download the data from [here](https://doi.org/10.5281/zenodo.10044741) and load the `dat` object with: `load("TCGA_data.rda")`.
- The package **TCGAbiolinks** cannot retrieve any proteomics or metabolomics data.
It is always useful to look at your data first, in particular the data type and dimensions (i.e. numbers of rows and columns for a data frame or matrix).
:::
<br>
## Survival analysis with low-dimensional input data {-}
### Nonparametric survival analysis {-}
For the data of TCGA breast cancer patients that we extracted in the previous section, Kaplan-Meier estimates of the survival probabilities can be obtained via function `survfit()` from [**survival**](https://CRAN.R-project.org/package=survival) package.
The dashed lines in the following figure indicate the median survival time.
```{r}
# Kaplan-Meier (KM) estimation
clin$status[clin$status == "Dead"] <- 1
clin$status[clin$status == "Alive"] <- 0
clin$status <- as.numeric(clin$status)
sfit <- survival::survfit(Surv(time, status) ~ 1, data = clin)
# calculate survival probability at 1-, 3- and 5-year time points
summary(sfit, times = c(1, 3, 5))
theme_set(theme_bw())
ggsurv <- survminer::ggsurvplot(sfit,
conf.int = TRUE, risk.table = TRUE,
xlab = "Time since diagnosis (year)",
legend = "none", surv.median.line = "hv"
)
ggsurv$plot <- ggsurv$plot + annotate("text", x = 20, y = 0.9, label = "+ Censor")
ggsurv
```
```{r, echo=FALSE}
pdf("TCGA_surv_km1.pdf", width = 5, height = 5)
ggsurv
dev.off()
```
![_Kaplan-Meier curve for 1061 BRCA patients data from TCGA._](fig/TCGA_surv_km1.png){width=60%}
<br>
To compare the survival curves of two groups of patients, for example, treatment (i.e. pharmaceutical or radiation therapy) or nontreatment, the `R` function `survival::survdiff()` can perform the log-rank test to compare two survival curves.
Alternatively, the `R` function `survival::survfit` with a formula including the treatment group as a covariate can return the (KM) survival probabilities for each groups.
Then the `R` function `survminer::ggsurvplot()` with a `survfit` object will draw the two survival curves and perform the log-rank test as shown in the following figure.
```{r}
survival::survdiff(Surv(time, status) ~ treatments, data = clin)
sfit2 <- survfit(Surv(time, status) ~ treatments, data = clin)
ggsurv <- ggsurvplot(sfit2,
conf.int = TRUE, risk.table = TRUE,
xlab = "Time since diagnosis (year)", legend = c(.6, .9),
legend.labs = c("No", "Yes"), legend.title = "Treatment",
risk.table.y.text.col = TRUE, risk.table.y.text = FALSE
)
ggsurv$plot <- ggsurv$plot +
annotate("text", x = 21, y = 1, label = "+ Censor") +
annotate("text", x = 22, y = .88, label = paste0("Log-rank test:\n", surv_pvalue(sfit2)$pval.txt))
ggsurv
```
```{r, echo=FALSE}
pdf("TCGA_surv_km2.pdf", width = 5, height = 5)
ggsurv
dev.off()
```
![_Kaplan-Meier curves of the BRCA patients' survival data from TCGA grouped by treatment (i.e. pharmaceutical or radiation therapy) or nontreatment. The log-rank test is to compare the two survival distributions corresponding to the two groups of patients._](fig/TCGA_surv_km2.png){width=60%}
<br>
To analyze if a continuous variable, e.g. age, is associated with the survival outcomes, we can use the `R` function `coxph()` for fitting a Cox model, which is similar to the function `lm()` for fitting linear models.
```{r}
fit_cox <- coxph(Surv(time, status) ~ age, data = clin)
summary(fit_cox)
```
```{.border}
Call:
coxph(formula = Surv(time, status) ~ age, data = clin)
n= 1047, number of events= 149
(14 observations deleted due to missingness)
coef exp(coef) se(coef) z Pr(>|z|)
age 0.034244 1.034837 0.006703 5.109 3.24e-07 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
exp(coef) exp(-coef) lower .95 upper .95
age 1.035 0.9663 1.021 1.049
Concordance= 0.639 (se = 0.029 )
Likelihood ratio test= 26.34 on 1 df, p=3e-07
Wald test = 26.1 on 1 df, p=3e-07
Score (logrank) test = 26.63 on 1 df, p=2e-07
```
The Cox model assumes proportional hazards and log-linearity of the covariates.
To check the log-linearity for a clinical or demographic variable, e.g. age, we can fit a penalized smoothing spline for age effect.
The following code shows that the nonlinear part of the smoothing spline has a significant effect ($p = 0.00013$).
Thus, the assumption of log-linearity for age is not satisfied.
```{r}
fit_cox_spline <- coxph(Surv(time, status) ~ pspline(age), data = clin)
fit_cox_spline
```
```{.border}
Call:
coxph(formula = Surv(time, status) ~ pspline(age), data = clin)
coef se(coef) se2 Chisq DF p
pspline(age), linear 0.03509 0.00577 0.00577 36.98323 1.00 1.2e-09
pspline(age), nonlin 20.69146 3.03 0.00013
Iterations: 5 outer, 15 Newton-Raphson
Theta= 0.828
Degrees of freedom for terms= 4
Likelihood ratio test=46.4 on 4.03 df, p=2e-09
n= 1047, number of events= 149
```
To check proportional hazards of age, we can add a time-dependent covariate $age \times g(t)$, where $g(t)$ is a known function e.g. $g(t) = \log t$.
The following code shows that the time-dependent age is significant using a score test ($p = 0.0087$).
Thus, the assumption of proportional hazards for age is not satisfied. The above two tests indicate a non-loglinear or time-dependent association of age with the survival outcomes.
```{r}
survival::cox.zph(fit_cox, transform = "log")
```
```{.border}
chisq df p
age 6.88 1 0.0087
GLOBAL 6.88 1 0.0087
```
:::{.info-box .note}
Here the approaches for checking log-linearity or proportional hazards can only be used in low-dimensional data settings.
When including high-dimensional omics data, there are no standard approaches for checking log-linearity or proportional hazards currently.
:::
<br>
### Feature preselection/filtering {-}
From a practical point of view, since most omics profiles contain thousands of variables and most supervised statistical methods are not suited for high dimensional omics features, it is better to filter the omics features first.
In addition, we perceive that not too many omics features are relevant to one medical problem.
We will demonstrate **three different filtering approaches for high-dimensional omics data**:
- Knowledge-based filtering
- P-value-based filtering
- Variance-based filtering
#### Knowledge filter {-}
One can be interested in only some biologically meaningful genes or only protein-coding genes in a specific study.
For example, the code below filters protein-coding genes.
```{r}
filtered_rna <- RNA_count[rowData(dat)$gene_type == "protein_coding", ]
```
#### P-value filter {-}
Before joint analyzing the associations between the thousands of omics features and survival outcomes, one can analyze the association between each omics feature and the survival outcomes, and filter omics features at a statistical significance level $0.1$ or $0.2$ (larger than 0.05 to reduce false negative identification of omics features in multivariate analysis).
For demonstration, based on the $100$ mRNA-Seq features from TCGA breast cancer patients preprocessed previously, the code below filters omics features at the statistical significance level $0.2$, i.e. $p < 0.2$.
```{r}
RNA_log2count <- log2(RNA_count[1:100, ] + 1)
pvalues <- rep(NA, nrow(RNA_log2count))
for (j in 1:nrow(RNA_log2count)) {
fit_cox <- coxph(Surv(clin$time, clin$status) ~ RNA_log2count[j, ], data = clin)
pvalues[j] <- summary(fit_cox)$coefficients[, "Pr(>|z|)"]
}
filtered_rna <- RNA_log2count[which(pvalues < 0.2), ]
```
#### Variance filter {-}
The other common and easy way to decrease the number of omics features is to filter the most variable ones for further analysis.
Note that the variance-based filtering step should be done before data standardization (i.e. calculating $z$-score), but can be performed after count data normalization and log2-transformation for instance.
The `R` package [**M3C**](https://bioconductor.org/packages/M3C/) [@John2020] provides a filter function `featurefilter()` by using different variance-type metrics, for example, variance, median absolute deviation (MAD), coefficient of variation (A) and its second order derivative (A2).
The simple variance filter can be used if the variance does not change with the corresponding mean, otherwise the coefficient of variation can be used.
If the omics data include outliers, MAD filter is more robust than the variance filter.
Based on the $60660$ mRNA-Seq features from TCGA breast cancer patients preprocessed previously, the code below extracts the $1\%$ most variable features using variance as a filtering metric.
```{r}
RNA_log2count <- log2(RNA_count + 1)
filtered <- M3C::featurefilter(RNA_log2count, percentile = 1, method = "var", topN = 5)
filtered_rna1 <- filtered$filtered_data
```
```{.border}
***feature filter function***
extracting the most variable: 1 percent
features to start with: 60660
performing calculations for variance
printing topN most variable features with statistics...
feature mean var sd
ENSG00000166509.12 ENSG00000166509.12 6.086125 31.60384 5.621729
ENSG00000110484.7 ENSG00000110484.7 11.005136 26.13755 5.112489
ENSG00000153002.12 ENSG00000153002.12 8.212895 25.89105 5.088325
ENSG00000134184.13 ENSG00000134184.13 5.371435 23.23511 4.820281
ENSG00000160182.3 ENSG00000160182.3 9.902195 21.41407 4.627534
features remaining: 607
```
Another variance-type filter is to remain features with certain percentage of **cumulative variances**, which will usually filter fewer features than the approaches above.
The code below extracts the most variable features explaining $1\%$ **cumulative variances**.
```{r}
cumsum_var <- cumsum(filtered$statistics$var)
cumsum_cutoff <- cumsum_var[length(cumsum_var)] * 0.01
filtered_names <- filtered$statistics$feature[cumsum_var < cumsum_cutoff]
```
<br>
## Survival analysis with high-dimensional input data {-}
### Unsupervised learning (omics data) {-}
In this section we will use the mRNA-Seq data of breast cancer patients from TCGA.
The following unsupervised methods can be applied to other omics data as well (the same applies to the supervised learning methods).
One important thing is that the input omics data, especially the data type and dimensions, should be suited to the methods.
Unsupervised learning for omics data can be helpful to explore subpopulations of the data, for example, patients from one cancer type can be divided to several omics-related subtypes.
We demonstrate three unsupervised learning methods, i.e. principal component analysis (PCA), $t$-stochastic neighbour embedding ($t$-SNE) and uniform manifold approximation and projection (UMAP), based on the PAM50 genes [@Parker2009].
The `R` package [**M3C**](https://bioconductor.org/packages/M3C/) [@John2020] provides the analyses and visualization of all the three methods.
```{r}
# identify indexes of the PAM50 genes in the TCGA-BRCA data
idx <- which(rowData(dat)$gene_name %in%
c("UBE2T", "BIRC5", "NUF2", "CDC6", "CCNB1", "TYMS", "MYBL2", "CEP55", "MELK", "NDC80", "RRM2", "UBE2C", "CENPF", "PTTG1", "EXO1", "ORC6", "ANLN", "CCNE1", "CDC20", "MKI67", "KIF2C", "ACTR3B", "MYC", "EGFR", "KRT5", "PHGDH", "CDH3", "MIA", "KRT17", "FOXC1", "SFRP1", "KRT14", "ESR1", "SLC39A6", "BAG1", "MAPT", "PGR", "CXXC5", "MLPH", "BCL2", "MDM2", "NAT1", "FOXA1", "BLVRA", "MMP11", "GPR160", "FGFR4", "GRB7", "TMEM45B", "ERBB2"))
# extract the PAM50 genes of TCGA-BRCA patients
TCGA_PAM50 <- RNA_count[idx, ]
# use gene symbols instead of Ensembl IDs
rownames(TCGA_PAM50) <- rowData(dat)$gene_name[idx]
# log2-transformation of the normalized count data
TCGA_PAM50 <- log2(TCGA_PAM50 + 1)
pam50 <- factor(clin$paper_BRCA_Subtype_PAM50)
M3C::pca(TCGA_PAM50, labels = pam50, dotsize = 3, legendtitle = "Subtype")
```
![_Unsupervised clustering (principal component analysis, PCA) of transcriptomic data from TCGA breast cancer patients_](fig/TCGA_pca.png){width=50%}
```{r}
M3C::tsne(TCGA_PAM50, labels = pam50, dotsize = 3, legendtitle = "Subtype")
```
![_Unsupervised clustering ($t$-stochastic neighbour embedding, $t$-SNE) of transcriptomic data from TCGA breast cancer patients_](fig/TCGA_tsne.png){width=50%}
```{r}
M3C::umap(TCGA_PAM50, labels = pam50, dotsize = 3, legendtitle = "Subtype")
```
![_Unsupervised clustering (uniform manifold approximation and projection, UMAP) of transcriptomic data from TCGA breast cancer patients_](fig/TCGA_umap.png){width=50%}
<br>
### Supervised learning (omics and survival data) {-}
To investigate the relationship between omics features and survival outcomes, regression methods (i.e. supervised learning) can be applied.
Since omics data are high-dimensional, one can use unsupervised learning methods to summarize a few components (dimension reduction) and regress the survival outcomes on the low-dimensional components by some classical statistical methods, e.g. classical Cox model.
There are also frequentist and Bayesian supervised learning methods suited to directly regress the survival outcomes on the high-dimensional omics features.
Note that preselecting/filtering ultrahigh-dimensional omics features can be useful before running the frequentist and Bayesian supervised learning methods.
#### Dimension reduction for Cox models {-}
The following code demonstrates the use of the first two principal components of PCA as covariates for the **purpose of survival prediction**.
Similarly, the first components from $t$-SNE or UMAP can also be extracted as covariates.
```{r}
# principal component regression
x_tmp <- prcomp(t(TCGA_PAM50))
# choose the top two components (subjective) as covariates
X_PC <- x_tmp$x[, 1:2]
# build classical survival model (e.g. PH Cox model)
data_tmp <- data.frame(time = clin$time, status = clin$status, X_PC)
fit <- coxph(Surv(time, status) ~ PC1 + PC2, data = data_tmp)
summary(fit)
```
```{.border}
Call:
coxph(formula = Surv(time, status) ~ PC1 + PC2, data = data_tmp)
n= 1047, number of events= 149
coef exp(coef) se(coef) z Pr(>|z|)
PC1 0.004679 1.004690 0.009675 0.484 0.62862
PC2 0.038179 1.038918 0.013233 2.885 0.00391 **
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
exp(coef) exp(-coef) lower .95 upper .95
PC1 1.005 0.9953 0.9858 1.024
PC2 1.039 0.9625 1.0123 1.066
Concordance= 0.58 (se = 0.028 )
Likelihood ratio test= 8.54 on 2 df, p=0.01
Wald test = 8.64 on 2 df, p=0.01
Score (logrank) test = 8.66 on 2 df, p=0.01
```
#### Penalized Cox models {-}
For computational efficiency, we will use only the mRNA-Seq features corresponding to the PAM50 genes [@Parker2009] instead of the variance filtered genes from the previous section.
We perform an investigation of the relationships between the mRNA-Seq features, two clinical variables (i.e. the patients' age at diagnosis and their ethnicity) and the survival outcomes.
The `R` package [**glmnet**](https://CRAN.R-project.org/package=glmnet) [@Friedman2010] is very computationally efficient to run Lasso and Elastic Net Cox models.
Lasso has a tuning parameter $\lambda$ to control the penalty strength of the coefficients which can be optimized by cross-validation (CV) via function `cv.glmnet()`.
The `glmnet()` and `cv.glmnet()` functions provide the argument `penalty.factor` to allow different shrinkage for different features, which makes sense if one includes both clinical/demographic variables and omics features and does not want to perform feature selection for the clinical/demographic variables.
```{r}
## Lasso Cox model
## for demonstration simplicity, PAM50 genes are used here
x <- cbind(age = clin$age, ethnicity = factor(clin$ethnicity), t(TCGA_PAM50))
y <- cbind(time = clin$time, status = clin$status)
# set penalty factor without penalizing the two demographical variables
pf <- c(rep(0, 2), rep(1, ncol(x) - 2))
# Lasso Cox by using cv.glmnet to obtain the 5-fold CV optimal lambda.min or lambda.1se
set.seed(123)
cvfit <- glmnet::cv.glmnet(x, y, family = "cox", nfolds = 5, penalty.factor = pf)
mod <- cvfit$glmnet.fit
lambda_optimal <- cvfit$lambda.min # optimal lambda
betas <- as.vector(coef(mod, s = lambda_optimal))
beta.positive <- colnames(x)[betas > 0]
beta.negative <- colnames(x)[betas < 0]
# get ordered list of variables as they appear at smallest lambda
allnames <- names(coef(mod)[, ncol(coef(mod))]
[order(coef(mod)[, ncol(coef(mod))], decreasing = TRUE)])
# assign colors for positive (pink) and negative (green) coefficients
cols <- rep("gray80", length(allnames))
cols[allnames %in% beta.positive] <- "seagreen3"
cols[allnames %in% beta.negative] <- "hotpink"
# draw coefficient paths of a Lasso Cox model
plotmo::plot_glmnet(mod,
label = TRUE, s = lambda_optimal, col = cols,
xlab = expression(log ~ ~lambda), ylab = expression(beta)
)
title("Lasso \n\n")
```
```{r, echo=FALSE}
pdf("TCGA_Lasso.pdf", width = 6, height = 5)
plotmo::plot_glmnet(mod,
label = TRUE, s = lambda_optimal, col = cols,
xlab = expression(log ~ ~lambda), ylab = expression(beta)
)
title("Lasso \n\n")
dev.off()
```
![_Coefficient paths of a Lasso Cox model. The verticle gray line indicates the optimal $\lambda$ and its correspondingly selected features are marked as green (positive coefficient) and red (negative coefficient) colors. Note that the demographic variables age and ethnicity were not penalized, so that their coefficient paths did not start from zero in the figure._](fig/TCGA_lasso.png){width=60%}
<br>
Elastic Net Cox model includes the $\lambda$ and an additional penalty parameter $\alpha \in [0,1]$.
The parameter $\alpha$ can be fixed as $0$ (Ridge), $1$ (Lasso) or any value between $0$ and $1$ for making a compromise between Ridge and Lasso, which can also be optimized by cross-validation manually, see the example below.
```{r}
## Elastic Net Cox model
# set penalty parameter alpha which comprises between Lasso and ridge regressions
alpha <- seq(0.1, 1, length = 10)
fitEN <- list()
set.seed(123)
for (i in 1:length(alpha)) {
fitEN[[i]] <- cv.glmnet(x, y, family = "cox", alpha = alpha[i], nfolds = 5, penalty.factor = pf)
}
idx <- which.min(sapply(fitEN, function(xx) {
xx$cvm[xx$lambda == xx$lambda.min]
}))
cvfit <- fitEN[[idx]]
# the following code is the same as Lasso previously
mod <- cvfit$glmnet.fit
lambda_optimal <- cvfit$lambda.min # optimal lambda
betas <- as.vector(coef(mod, s = lambda_optimal))
beta.positive <- colnames(x)[betas > 0]
beta.negative <- colnames(x)[betas < 0]
allnames <- names(coef(mod)[, ncol(coef(mod))]
[order(coef(mod)[, ncol(coef(mod))], decreasing = TRUE)])
cols <- rep("gray80", length(allnames))
cols[allnames %in% beta.positive] <- "seagreen3"
cols[allnames %in% beta.negative] <- "hotpink"
plotmo::plot_glmnet(mod,
label = TRUE, s = lambda_optimal, col = cols,
xlab = expression(log ~ ~lambda), ylab = expression(beta)
)
title("Elastic Net \n\n")
```
```{r, echo=FALSE}
pdf("TCGA_elastic.pdf", width = 6, height = 5)
plotmo::plot_glmnet(mod,
label = TRUE, s = lambda_optimal, col = cols,
xlab = expression(log ~ ~lambda), ylab = expression(beta)
)
title("Elastic Net \n\n")
dev.off()
```
![_Coefficient paths of an Elastic Net Cox model. The verticle gray line indicates the optimal $\lambda$ and its correspondingly selected features are marked as green (positive coefficient) and red (negative coefficient) colors. Note that the demographic variables age and ethnicity were not penalized, so that their coefficient paths did not start from zero in the figure._](fig/TCGA_elastic.png){width=60%}
<br>
Adaptive Lasso Cox model needs to pre-estimate all coefficients which will be used as weights via the argument `penalty.factor` in the `glmnet()` and `cv.glmnet()` functions to fit a Lasso Cox model.
The pre-estimation can be done by a Ridge Cox model, see an example below.
```{r}
## Adaptive Lasso Cox model
set.seed(123)
fit <- cv.glmnet(x, y, family = "cox", alpha = 0, nfolds = 5)
weights <- abs(1 / as.vector(coef(fit, s = "lambda.min")))
weights[c(1,2)] = 0 # don't penalize age and ethnicity
# adaptive Lasso Cox by using cv.glmnet to obtain the 5-fold CV optimal lambda.min or lambda.1se
cvfit <- cv.glmnet(x, y, family = "cox", nfolds = 5, penalty.factor = weights)
mod <- cvfit$glmnet.fit
lambda_optimal <- cvfit$lambda.min # optimal lambda
betas <- as.vector(coef(mod, s = lambda_optimal))
beta.positive <- colnames(x)[betas > 0]
beta.negative <- colnames(x)[betas < 0]
# get ordered list of variables as they appear at smallest lambda
allnames <- names(coef(mod)[, ncol(coef(mod))]
[order(coef(mod)[, ncol(coef(mod))], decreasing = TRUE)])
# assign colors
cols <- rep("gray80", length(allnames))
cols[allnames %in% beta.positive] <- "seagreen3"
cols[allnames %in% beta.negative] <- "hotpink"
plot_glmnet(mod,
label = TRUE, s = lambda_optimal, col = cols,
xlab = expression(log ~ lambda), ylab = expression(beta)
)
title("Adative Lasso \n\n")
```
```{r, echo=FALSE}
pdf("TCGA_adaptiveLasso.pdf", width = 6, height = 5)
plot_glmnet(mod,
label = TRUE, s = lambda_optimal, col = cols,
xlab = expression(log ~ lambda), ylab = expression(beta)
)
title("Adative Lasso \n\n")
dev.off()
```
![_Coefficient paths of an adaptive Lasso Cox model. The verticle gray line indicates the optimal $\lambda$ and its correspondingly selected features are marked as green (positive coefficient) and red (negative coefficient) colors. Note that the demographic variables age and ethnicity were not penalized, so that their coefficient paths did not start from zero in the figure._](fig/TCGA_adaptiveLasso.png){width=60%}
<br>
Group Lasso Cox model can be implemented through the `R` package [**grpreg**](https://CRAN.R-project.org/package=grpreg) [@Breheny2015].
For an illustration, we specify the two demographic variables as the first group, the first $10$ PAM50 genes as the second group, the last $40$ PAM50 genes as the third group.
A $k$-fold cross-validation (CV) for the group Lasso Cox model is performed through function `cv.grpsurv()`.
The returned object `cvfit$lambda.min` is the value of CV-optimized $\lambda$.
The following results show that
- when choosing the CV-optimized $\lambda = 0.0143$ (output matrix has lambda values as column names), the estimated coefficients of the first two groups are nonzero (i.e. selecting first and second groups);
- when choosing the $10$-th lambda $\lambda = 0.0217$, only the first group of covariates has nonzero coefficients (i.e. selecting first group);
- when choosing the $15$-th lambda $\lambda = 0.0108$, the estimated coefficients of all the three groups are nonzero (i.e. selecting all groups).
Note that the `R` package [**grpreg**](https://CRAN.R-project.org/package=grpreg) [@Breheny2015] also implements group smoothly clipped absolute deviation (SCAD) model and some others, see @Breheny2021 for details.
```{r}
# group Lasso Cox model
group <- c(rep("demographic", 2), rep("PAM50_1", 10), rep("PAM50_2", 40))
group <- factor(group)
set.seed(123)
cvfit <- grpreg::cv.grpsurv(X = x, y = y, group = group, penalty = "grLasso", returnY = TRUE)
round(cvfit$fit$beta[, c(which.min(cvfit$cve), 10, 20)], digits = 4)
```
```{.border}
0.0143 0.0217 0.0108
age 0.0218 0.0154 0.0247
ethnicity -0.0542 -0.0425 -0.0570
ANLN 0.0193 0.0000 0.0713
FOXC1 -0.0032 0.0000 -0.0104
CDH3 -0.0028 0.0000 -0.0090
UBE2T 0.0154 0.0000 0.0571
NDC80 -0.0239 0.0000 -0.0862
PGR -0.0027 0.0000 -0.0086
BIRC5 -0.0133 0.0000 -0.0497
ORC6 0.0140 0.0000 0.0489
ESR1 -0.0002 0.0000 -0.0008
PHGDH 0.0008 0.0000 0.0024
CDC6 0.0000 0.0000 -0.0094
MMP11 0.0000 0.0000 0.0074
MYBL2 0.0000 0.0000 0.0018
SFRP1 0.0000 0.0000 0.0049
CCNE1 0.0000 0.0000 0.0000
BLVRA 0.0000 0.0000 -0.0436
BAG1 0.0000 0.0000 -0.0163
MLPH 0.0000 0.0000 -0.0155
CDC20 0.0000 0.0000 -0.0129
CENPF 0.0000 0.0000 -0.0245
KRT17 0.0000 0.0000 -0.0125
FOXA1 0.0000 0.0000 0.0040
ACTR3B 0.0000 0.0000 -0.0112
CCNB1 0.0000 0.0000 0.0302
MDM2 0.0000 0.0000 -0.0077
MYC 0.0000 0.0000 0.0002
CEP55 0.0000 0.0000 -0.0242
SLC39A6 0.0000 0.0000 0.0053
ERBB2 0.0000 0.0000 -0.0089
GRB7 0.0000 0.0000 0.0099
KIF2C 0.0000 0.0000 0.0219
NUF2 0.0000 0.0000 0.0210
EGFR 0.0000 0.0000 -0.0150
MKI67 0.0000 0.0000 0.0266
TMEM45B 0.0000 0.0000 0.0100
FGFR4 0.0000 0.0000 0.0023
PTTG1 0.0000 0.0000 0.0095
MELK 0.0000 0.0000 -0.0188
NAT1 0.0000 0.0000 -0.0052
CXXC5 0.0000 0.0000 0.0131
BCL2 0.0000 0.0000 -0.0082
RRM2 0.0000 0.0000 -0.0003
GPR160 0.0000 0.0000 -0.0043
EXO1 0.0000 0.0000 0.0041
UBE2C 0.0000 0.0000 -0.0052
TYMS 0.0000 0.0000 -0.0298
KRT5 0.0000 0.0000 -0.0025
KRT14 0.0000 0.0000 0.0085
MAPT 0.0000 0.0000 -0.0071
MIA 0.0000 0.0000 -0.0180
```
Sparse group Lasso Cox model is implemented in the `R` package [**SGL**](https://CRAN.R-project.org/package=SGL) [@Simon2019].
The function `cvSGL()` uses cross validation to optimize the penalty parameter $\lambda$.
The following example shows that it induces sparsity in each group of covariates.
```{r}
# sparse group Lasso Cox model
group <- c(rep("demographic", 2), rep("PAM50_1", 10), rep("PAM50_2", 40))
group <- factor(group)
dat_tmp <- list(x = x, time = clin$time, status = clin$status)
set.seed(123)
cvfit <- SGL::cvSGL(dat_tmp, index = group, type = "cox", nfold = 5)
beta.hat <- cvfit$fit$beta[, which.min(cvfit$lldiff)]
names(beta.hat) <- paste0("group", as.numeric(group), ".", c(1:2, 1:10, 1:40))
beta.hat
```
```{.border}
group1.1 group1.2 group2.1 group2.2 group2.3 group2.4
5.6584838488 0.0000000000 0.4812006103 0.0000000000 0.0000000000 0.2481830177
group2.5 group2.6 group2.7 group2.8 group2.9 group2.10
0.0000000000 -0.0003042126 0.0000000000 0.3317385412 0.0000000000 0.0000000000
group3.1 group3.2 group3.3 group3.4 group3.5 group3.6
0.0000000000 0.3037631224 0.0000000000 -0.3782338997 0.0000000000 -2.6805881347
group3.7 group3.8 group3.9 group3.10 group3.11 group3.12
-1.8418523757 0.0000000000 0.0000000000 0.0000000000 -1.7849923007 0.0000000000
group3.13 group3.14 group3.15 group3.16 group3.17 group3.18
0.0000000000 1.0290918041 0.0000000000 0.0000000000 0.0000000000 0.0000000000
group3.19 group3.20 group3.21 group3.22 group3.23 group3.24
0.0000000000 0.0000000000 0.0000000000 0.0000000000 -0.3679980817 0.0000000000
group3.25 group3.26 group3.27 group3.28 group3.29 group3.30
0.9925901529 0.0088469957 0.0000000000 0.0000000000 0.0000000000 0.0000000000
group3.31 group3.32 group3.33 group3.34 group3.35 group3.36
-2.1975942364 0.0000000000 0.0000000000 0.0000000000 0.0000000000 -0.8407228093
group3.37 group3.38 group3.39 group3.40
-1.8217490477 0.0000000000 -0.7323739107 -2.0111900380
```
#### Sparse Bayesian Cox models
The `R` package [**psbcGroup**](https://CRAN.R-project.org/package=psbcGroup) [@Lee2021] integrates a large set of sparse Bayesian Cox models.
The function `psbcGL()` implements Bayesian Cox models with Lasso and group Lasso priors for feature selection and group selection respectively.
For the Lasso prior, set the hyperparameter `priorPara$groupInd = 1:p` where $p$ is the total number of covariates.
For the group Lasso prior, set the hyperparameter `priorPara$groupInd` as a vector of size $p$, where each element denotes which group each covariate corresponds to.
```{r}
# Bayesian Cox model with Lasso prior
set.seed(123)
survObj <- list(t = clin$time, di = clin$status, x = x)
p <- ncol(x)
# set hyperparameters.
# For Lasso prior (i.e. 'groupInd'= 1:p), larger ratio r/delta tends to force the posterior betas to be more concentrated at 0
# For group Lasso prior (i.e. 'groupInd' as group indicator for covariates), larger ratio r/delta tends to force stronger grouping effect of covariates
s <- c(sort(survObj$t[survObj$di == 1]), 2 * max(survObj$t) - max(survObj$t[-which(survObj$t == max(survObj$t))]))
priorPara <- list(
"eta0" = 1, "kappa0" = 1, "c0" = 2, "r" = 0.5,
"delta" = 0.0001, "s" = s, "J" = length(s), "groupInd" = 1:p
)
# set MCMC parameters
mcmcPara <- list("numBeta" = p, "beta.prop.var" = 1)
# set initial values of hyperparameters
lambdaSq <- 1
initial <- list(
"beta.ini" = rep(0, p), "lambdaSq" = 1, "sigmaSq" = runif(1, 0.1, 10),
"tauSq" = rexp(length(unique(priorPara$groupInd)), "rate" = lambdaSq / 2),
"h" = rgamma(priorPara$J, 1, 1)
)
# in real applications, 'num.reps' should be large enough (e.g. 20000, 40000) and 'chain' to be > 1
# argument 'rw' should be FALSE for high-dimensional covariates
BayesLassofit <- psbcGroup::psbcGL(survObj, priorPara, initial, rw = TRUE, mcmcPara, num.reps = 100, thin = 1, chain = 1)
# burn-in the first half MCMC iterations
beta_p <- BayesLassofit$beta.p[-(1:51), ]
colnames(beta_p) <- colnames(x)
psbcSpeedUp:::plot.psbcSpeedUp(beta_p)
```
```{r, echo=FALSE}
pdf("TCGA_bayesLasso.pdf", width = 4, height = 6)
psbcSpeedUp:::plot.psbcSpeedUp(beta_p)
dev.off()
```
![_Estimates of regression coefficients by a penalized semiparametric Bayesian Cox model with Lasso prior. Solid dots indicate the posterior mean over MCMC iterations (excluding burn-in period), and horizontal lines show the corresponding 95% credibility intervals._](fig/TCGA_bayeslasso.png){width=50%}
<br>
Note that **psbcGroup** cannot distinguish mandatory (unpenalized) covariates with omics features, see @Zucknick2015 for an extended Bayesian Lasso Cox model. []{#psbcSpeedUp}
The following code implements the Bayesian Lasso Cox model with mandatory covariates through the `R` package [**psbcSpeedUp**](https://CRAN.R-project.org/package=psbcSpeedUp) [@Zhao2023b].
```{r}
# Bayesian Cox model with Lasso prior and mandatory covariates
set.seed(123)
survObjM <- list(t = clin$time, di = clin$status, x = x[, c(3:52, 1:2)])
priorPara <- list("eta0" = 1, "kappa0" = 1, "c0" = 2, "r" = 0.5, "delta" = 0.0001)
BayesLassoMfit <- psbcSpeedUp::psbcSpeedUp(survObjM,
p = 50, q = 2, hyperpar = priorPara,
nIter = 100, burnin = 50, thin = 1, rw = FALSE, outFilePath = "tmp"
)
plot(BayesLassoMfit)
```
```{.border}
Running MCMC iterations ...
[##################################################] 100%
DONE, exiting!
```
```{r, echo=FALSE}
pdf("TCGA_bayesLassoM.pdf", width = 4, height = 6)
plot(BayesLassoMfit)
dev.off()
```
![_Estimates of regression coefficients by a penalized semiparametric Bayesian Cox model with Lasso prior and unpenalized covariates. Solid dots indicate the posterior mean over MCMC iterations (excluding burn-in period), and horizontal lines show the corresponding 95% credibility intervals._](fig/TCGA_bayesLassoM.png){width=50%}
<br>
In the `R` package [**psbcGroup**](https://CRAN.R-project.org/package=psbcGroup) [@Lee2021], function `psbcEN()` implements Bayesian Cox models with Elastic Net prior for feature selection with grouping effect of correlated features.
Function `psbcFL()` implements Bayesian Cox models with fused Lasso prior.
```{r}
# Bayesian Cox model with Elastic Net prior
set.seed(123)
# set hyperparameters
# Larger ratio r1/delta1 forces the posterior betas to be more concentrated at 0
# Larger ratio r2/delta2 forces stronger grouping effect of covariates
priorPara <- list(
"eta0" = 1, "kappa0" = 1, "c0" = 2, "r1" = 0.1, "r2" = 1,
"delta1" = 0.1, "delta2" = 1, "s" = s, "J" = length(s)
)
# set MCMC parameters
mcmcPara <- list("numBeta" = p, "beta.prop.var" = 1)
# set initial values of hyperparameters
initial <- list(
"beta.ini" = rep(0, p), "lambda1Sq" = 1, "lambda2" = 1, "sigmaSq" = runif(1, 0.1, 10),
"tauSq" = rexp(p, rate = 1 / 2), "h" = rgamma(priorPara$J, 1, 1)
)
# in real application, 'num.reps' should be large enough (e.g. 20000, 40000) and 'chain' to be > 1
BayesENfit <- psbcEN(survObj, priorPara, initial, rw = FALSE, mcmcPara,
num.reps = 100, thin = 1, chain = 1)
# burn-in the first half MCMC iterations
EN_beta_p <- BayesENfit$beta.p[52:101, ]
colnames(EN_beta_p) <- colnames(x)
psbcSpeedUp:::plot.psbcSpeedUp(EN_beta_p)
```
```{r, echo=FALSE}
pdf("TCGA_bayesEN.pdf", width = 4, height = 6)
psbcSpeedUp:::plot.psbcSpeedUp(EN_beta_p)
dev.off()
```
![_Estimates of regression coefficients by a penalized semiparametric Bayesian Cox model with Elastic Net prior. Solid dots indicate the posterior mean over MCMC iterations (excluding burn-in period), and horizontal lines show the corresponding 95% credibility intervals._](fig/TCGA_bayesEN.png){width=50%}
<br>
A penalized semiparametric Bayesian Cox model with double exponential spike-and-slab prior is implemented in the `R` package [**BhGLM**](https://github.com/nyiuab/BhGLM.git) [@Yi2019]. Note that **BhGLM** provides frequentist confidence intervals of the posterior mode of the coefficients.
```{r}
# penalized semiparametric Bayesian Cox model with (double exponential) spike-and-slab prior
y_surv <- Surv(clin$time, clin$status)
x_dataframe <- as.data.frame(x)
set.seed(123)
Bayesfit <- BhGLM::bcoxph(y_surv ~ ., x_dataframe, prior = mde(0, 0.01, 0.8), control = coxph.control(iter.max = 200))
BhGLM::plot.bh(Bayesfit, col.pts = c("red", "blue"), main = "Cox with mixture double exponential\n")
```
```{r, echo=FALSE}
pdf("TCGA_bayesSpikeSlab.pdf", width = 6, height = 5)
par(mar = c(3, 8, 4, 4))
BhGLM::plot.bh(Bayesfit, col.pts = c("red", "blue"), main = "Cox with mixture double exponential\n")
dev.off()
```
![_Coefficient estimates of a penalized semiparametric Bayesian Cox model with (double exponential) spike-and-slab prior. Solid dots denote the posterior mode of the coefficients and lines denote the 95% confidence intervals. Red colored text on the right side mark the significant features with $p < 0.05$._](fig/TCGA_bayesSpikeSlab.png){width=60%}
## Survival model validation {-}
The ideal evaluation of a prognostic model is based on completely independent validation data, since high-dimensional survival models built on the training data can be overfitted.
If there are no independent validation data, it is recommended to use resampling-based methods for estimating the **uncertainty** of the model’s prediction performance.
This can be done for example by repeatedly splitting the dataset to training/validation sets and evaluating a model’s performance on the different validation sets using various evaluation metrics.
:::{.callout-tip}
## Model validation
To validate a prediction model systematically, the predictive performance of the model is commonly addressed by
- **Discrimination**: the ability of the model to distinguish between low and high risk patients
- **Calibration**: the agreement between the observed and predicted survival probabilities
- **Overall performance**: the distance between the observed and predicted survival probabilities
:::
The performance metrics can be *time-dependent* or *time-independent*, with the time-dependent metrics being more informative in general compared to integrated measures (i.e. evaluated across many time points).
For survival data, we can assess the **discriminatory power** of a model (i.e. how well does it ranks patients) or how well a model is **calibrated** (i.e. how closely the predicted survival probabilities agree numerically with the actual survival outcomes).
For example, measures such as the receiver operating characteristic (ROC) curve, the (integrated) area under time-specific ROC curves (**AUC**, @Heagerty2005) and the concordance index (**C-index**, @Harrell1982) are measures of discrimination, while the right-censored logarithmic loss (**RCLL**, @Avati2020) and the well-known **Brier score** [@Graf1999] are used to evaluate both discrimination and calibration performance.
### Model evaluation (classic) {-}
:::{.callout-note}
'Classic' here refers to the use of manual `R` code in combination with many separate `R` packages which have been routinely used in academia the latest 10+ years for evaluating survival models.
:::
To evaluate the performance of a statistical model, we first split the data into training and validation data sets.
For example, we can randomly split the 1047 BRCA patients from TCGA into $80\%$ as training set and $20\%$ as validation set.
```{r}
set.seed(123)
n <- nrow(x)
idx <- sample(1:n, n * 0.8, replace = FALSE)
x_train <- x[idx, ]
y_train <- y[idx, ]
x_validate <- x[-idx, ]
y_validate <- y[-idx, ]
```
:::{.callout-important}
The $20\%$ split of a dataset is often not considered an **independent** dataset and **resampling-based methods** should be used in such cases to provide an unbiased estimate of the predictive accuracy of a prognostic model.
:::
#### Discrimination metrics {-}
<font size="4"> **Goodness-of-fit** </font>
The simplest way to demonstrate the prognostic power of a survival model is to dichotomize the prognostic scores (i.e., linear predictor $lp$ in the Cox model) by median value, and then to use a log-rank test to compare the survival curves of the patients in the two groups.
We use the built model to predict the prognostic scores based on the $20\%$ validation data.
The following code shows the **goodness-of-fit** of a Lasso Cox model with the BRCA patients survival and PAM50 mRNA-Seq data from TCGA.
```{r}
# train a Lasso Cox model, similarly for other Cox-type models
set.seed(123)
cvfit <- cv.glmnet(x_train, y_train, family = "cox", nfolds = 5, penalty.factor = pf)
pred_lp <- predict(cvfit, newx = x_validate, s = cvfit$lambda.min, type = "link")
# dichotomize by prognostic scores (linear predictor) by median to divide the validation patients into two groups
group_dichotomize <- as.numeric(pred_lp > median(pred_lp))
# draw two survival curves based on KM estimation and compare them by a log-rank test
dat_tmp <- data.frame(time = y_validate[, 1], status = y_validate[, 2], group = group_dichotomize)
sfit <- survfit(Surv(time, status) ~ group, data = dat_tmp)
ggsurv <- ggsurvplot(sfit,
conf.int = TRUE, risk.table = TRUE,
xlab = "Time since diagnosis (year)", legend = c(.2, .3),
legend.labs = c("Low risk", "High risk"), legend.title = "Dichotomized groups",
risk.table.y.text.col = TRUE, risk.table.y.text = FALSE
)
ggsurv$plot <- ggsurv$plot +
annotate("text", x = 2.6, y = .03, label = paste0("Log-rank test:\n", surv_pvalue(sfit)$pval.txt))
ggsurv$table <- ggsurv$table + labs(y = "Dichotomized\n groups")
ggsurv
```
```{r, echo=FALSE}
pdf("TCGA_surv_km_lasso.pdf", width = 5, height = 5)
ggsurv
dev.off()
```
![_Kaplan-Meier curves of the BRCA patients data dichotomized by the median of prognostic scores (calculated from the Lasso Cox model with patients' survival and mRNA-Seq data) into two groups. The log-rank test is to compare the two survival distributions corresponding to the two groups of patients._](fig/TCGA_surv_km_lasso.png){width=50%}
<br>
The prognostic scores can also be divided into three or more groups based on quantiles and the log-rank test can be used to compare the difference of multiple survival curves.
```{r}
group <- pred_lp
group[pred_lp >= quantile(pred_lp, 2 / 3)] <- 3