我创建了一个函数,它将Cox回归模型应用于测试数据,基于协变量创建生存函数,然后预测每个测试观察的当前时间30天的生存概率。
以下示例使用肺数据集并且运行良好。但是,应用于我自己的数据处理时间很繁琐。对于n = 60000,我只是在一小时后停止它,因为它不适合我打算使用该程序。
看一下代码结构,有一种明显的方法可以加快速度吗?
require(dplyr, survival, pec)
cox_model <- coxph(Surv(time, status) ~ sex, data = lung)
surv_preds <- function(model, query) {
prediction <- vector(mode = "numeric", length = nrow(query))
time <- 30
for(i in 1:nrow(query)) {
prediction[i] <- predictSurvProb(model, newdata = query[i, ], times = query[i, "time"] + time)
}
prediction
}
surv_preds(cox_model, lung)
另一条路线是by_row
的purrrlyr
函数以及问题中的包。
library(purrrlyr)
prediction <- lung %>%
mutate(time = time + 30) %>%
by_row(~predictSurvProb(cox_model, newdata = ., times = .$time)) %>%
.$.out %>%
unlist
在产生相同结果时更加整洁,然而,microbenchmark
的早期运行并未显示处理时间的改善。
# Unit: seconds
# expr min lq mean median uq max neval
# surv_preds(cox_model, lung) 1.531631 1.561518 1.59431 1.574664 1.591117 2.157002 100
# (purrrlyr) 1.841713 1.887438 1.921371 1.90474 1.92649 2.170205 100
这将使我在使用的硬件上运行超过24小时的两种解决方案。鉴于这个答案似乎不再解决你的问题,我不熟悉并行处理选项我很乐意删除它,除非有人发现保持这里的价值。
解决了!!如果感兴趣,我想发布我使用的解决方案。我设法完全取消了for循环的需要。
predictSurvProb(cox_model,
newdata = lung,
times = lung[ , "time"] + 30)[1, ]
这给了我需要的输出。关键是我从结果矩阵索引第一行及其所有列。该代码使用每个观察的唯一生存函数估计来预测距观察曲线上当前位置30天的生存概率。
@thc的回答实际上指出了我最终的正确方向。
您不需要一次预测一行。你可以一次完成所有工作。例如。:
cox_model <- coxph(Surv(time, status) ~ sex, data = lung)
surv_preds <- function(model, query) {
prediction <- vector(mode = "numeric", length = nrow(query))
time <- 30
for(i in 1:nrow(query)) {
prediction[i] <- predictSurvProb(model, newdata = query[i, ], times = query[i, "time"] + time)
}
prediction
}
surv_preds2 <- function(model, query) {
time <- 30
prediction <- predictSurvProb(model, newdata = query, times = query[, "time"] + time)
prediction
}
microbenchmark(surv_preds(cox_model, lung), surv_preds2(cox_model, lung), times=5)
结果:
Unit: milliseconds
expr min lq mean median uq max neval cld
surv_preds(cox_model, lung) 1017.5587 1031.58422 1056.7026 1062.30476 1072.33865 1099.72672 5 b
surv_preds2(cox_model, lung) 30.3567 30.78582 35.7851 31.81206 33.00534 52.96559 5 a