/
LearnerSurvCoxPH.R
74 lines (63 loc) · 2.52 KB
/
LearnerSurvCoxPH.R
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
#' @templateVar title Cox Proportional Hazards
#' @templateVar fullname LearnerSurvCoxPH
#' @templateVar caller [survival::coxph()]
#' @templateVar distr by [survival::survfit.coxph()]
#' @templateVar lp by [survival::predict.coxph()]
#' @templateVar id surv.coxph
#' @template surv_learner
#'
#' @references
#' `r format_bib("cox_1972")`
#'
#' @export
LearnerSurvCoxPH = R6Class("LearnerSurvCoxPH",
inherit = LearnerSurv,
public = list(
#' @description
#' Creates a new instance of this [R6][R6::R6Class] class.
initialize = function() {
super$initialize(
id = "surv.coxph",
param_set = ps(
ties = p_fct(default = "efron", levels = c("efron", "breslow", "exact"), tags = "train"),
singular.ok = p_lgl(default = TRUE, tags = "train"),
type = p_fct(default = "efron", levels = c("efron", "aalen", "kalbfleisch-prentice"), tags = "predict"),
stype = p_int(default = 2L, lower = 1L, upper = 2L, tags = "predict")
),
predict_types = c("crank", "distr", "lp"),
feature_types = c("logical", "integer", "numeric", "factor"),
properties = "weights",
packages = c("survival", "distr6"),
label = "Cox Proportional Hazards",
man = "mlr3proba::mlr_learners_surv.coxph"
)
}
),
private = list(
.train = function(task) {
pv = self$param_set$get_values(tags = "train")
if ("weights" %in% task$properties) {
pv$weights = task$weights$weight
}
invoke(survival::coxph, formula = task$formula(), data = task$data(), .args = pv, x = TRUE)
},
.predict = function(task) {
newdata = task$data(cols = task$feature_names)
# We move the missingness checks here manually as if any NAs are made in predictions then the
# distribution object cannot be create (initialization of distr6 objects does not handle NAs)
if (anyMissing(newdata)) {
stop(sprintf(
"Learner %s on task %s failed to predict: Missing values in new data (line(s) %s)\n",
self$id, task$id,
paste0(which(!complete.cases(newdata)), collapse = ", ")))
}
pv = self$param_set$get_values(tags = "predict")
# Get predicted values
fit = mlr3misc::invoke(survival::survfit, formula = self$model, newdata = newdata,
se.fit = FALSE, .args = pv)
lp = predict(self$model, type = "lp", newdata = newdata)
.surv_return(times = fit$time, surv = t(fit$surv), lp = lp)
}
)
)
register_learner("surv.coxph", LearnerSurvCoxPH)