【发布时间】:2020-12-02 05:54:27
【问题描述】:
我在 R 中编写了一些代码。该代码获取一些数据并将其拆分为训练集和测试集。然后,我在训练集上拟合了一个“生存随机森林”模型。之后,我使用该模型来预测测试集中的观察结果。
由于我正在处理的问题类型(“生存分析”),必须为每个“唯一时间”(在文件“unique.death.time”中)制作一个混淆矩阵。对于为每个唯一时间制作的每个混淆矩阵,我对相应的“敏感度”值(例如敏感度_1001、敏感度_2005 等)感兴趣。我正在尝试获取所有这些敏感度值:我想用它们绘制一个图(相对于唯一的死亡时间)并确定平均敏感度值。
为了做到这一点,我需要重复计算“unique.death.times”中每个时间点的灵敏度。我尝试手动执行此操作,但需要很长时间。
有人可以告诉我如何使用“循环”来做到这一点吗?
我在下面发布了我的代码:
#load libraries
library(survival)
library(data.table)
library(pec)
library(ranger)
library(caret)
#load data
data(cost)
#split data into train and test
ind <- sample(1:nrow(cost),round(nrow(cost) * 0.7,0))
cost_train <- cost[ind,]
cost_test <- cost[-ind,]
#fit survival random forest model
ranger_fit <- ranger(Surv(time, status) ~ .,
data = cost_train,
mtry = 3,
verbose = TRUE,
write.forest=TRUE,
num.trees= 1000,
importance = 'permutation')
#optional: plot training results
plot(ranger_fit$unique.death.times, ranger_fit$survival[1,], type = 'l', col = 'red') # for first observation
lines(ranger_fit$unique.death.times, ranger_fit$survival[21,], type = 'l', col = 'blue') # for twenty first observation
#predict observations test set using the survival random forest model
ranger_preds <- predict(ranger_fit, cost_test, type = 'response')$survival
ranger_preds <- data.table(ranger_preds)
colnames(ranger_preds) <- as.character(ranger_fit$unique.death.times)
#here is my question:
#get results for some time (time >1001)
prediction <- ranger_preds$'1001' > 0.5 # time has to be in "unique.death.times."
real <- cost_test$time >= 1001
#get confusion matrix and sensitivity for this same time
confusion = confusionMatrix(as.factor(prediction), as.factor(real), positive = 'TRUE')
sensitivity_1001 = confusion$byclass[1]
#now, get the results for a second time
prediction <- ranger_preds$'2005' > 0.5 # for any time in unique.death.times. "2005"
real <- cost_test$time >= 2005
#get confusion matirx and sensitivity for the second time
confusion = confusionMatrix(as.factor(prediction), as.factor(real), positive = 'TRUE')
sensitivity_2005 = confusion$byclass[1]
#question: how do I get the "sensitivity" for all the times in "unique.death.times", the average sensitivity and "plot sensitivity vs unique death times"?
有人可以帮我吗?
谢谢
编辑:用户“Justin Singh”提供的答案。好像思路对了,但是产生了如下错误:
sensitivity <- list()
for (time in names(ranger_preds)) {
prediction <- ranger_preds[which(names(ranger_preds) == time)] > 0.5
real <- cost_test$time >= as.numeric(time)
confusion <- confusionMatrix(as.factor(prediction), as.factor(real), positive = 'TRUE')
sensitivity[as.character(i)] <- confusion$byclass[1]
}
Error in confusionMatrix.default(as.factor(prediction), as.factor(real), :
The data must contain some levels that overlap the reference.
【问题讨论】:
标签: r function loops for-loop repeat