随机森林中的折叠性能

问题描述 投票:0回答:1

[当我使用caret训练随机森林时,尤其是如果我更改阈值时,我试图在所有倍数上获得灵敏度,特异性,ppv和npv(或混淆矩阵也可以工作)。我通常知道使用默认阈值时,您可以使用model$resample为您提供所有倍数的指标,但是如何在新阈值下做到这一点?

这是我的模特:

ctrl <- trainControl(method = "cv",
                 number = 5,
                 savePredictions = TRUE,
                 summaryFunction = TwoClassSummary,
                 classProbs = TRUE)

model <- train(outcome ~ ., data=df, 
  trControl = ctrl, method= "rf", preProc=c("center","scale"), metric="ROC",importance=TRUE)

这里是如何以新的阈值生成混淆矩阵:

 label <- ifelse(model$pred$affirmatory > 0.75, 'affirmatory', 'negatory')
 confusionMatrix(label, model$pred$obs, positive = 'affirmatory')

但是这只给了我所有褶皱的平均值。我如何查看所有折页的指标?

r machine-learning random-forest r-caret roc
1个回答
0
投票

我想出了我问题的答案,并希望将其发布,以防将来对任何人都有好处。

这是使用iris的可复制示例。假设您对threshold=0.2的每一折的表现感兴趣。

set.seed(3949)
attach(iris)
#create a binary outcome on Sepal.Length
iris <- iris %>% mutate(Sepal.Length=ifelse(Sepal.Length>5.0,"aff","neg")) 


practice <- train(Sepal.Length ~ ., data = iris, trControl = ctrl, method= 
"rf", preProc=c("center","scale"), metric="ROC",importance=TRUE, tuneGrid = 
data.frame(mtry = 2)) #must specify a single mtry

#examine outcome at every fold
print(practice$pred) 

您可以看到默认阈值为0.5。如果为threshold>0.5,则pred将为aff,反之亦然。如果我想要threshold=0.2,那么当aff时我会得到threshold>0.2。因此,现在您只需要根据该阈值创建一个具有新预测的新列,然后可以从中生成一个混淆矩阵。

f1 <- practice$pred %>% filter(Resample=="Fold1")
f1 <- f1 %>% mutate(new_pred=ifelse(aff>0.2,"positive","negative"))
f1 %>% group_by(obs, new_pred) %>% summarize(n=n())

对每个折叠重复以上步骤。最后一行给您一个细分的混淆矩阵。使用它,您可以手动找出sen / spec / ppv / npv。如果要确认此方法是否确实有效,可以使用以下方法为在新阈值下评估的整个模型生成混淆矩阵:

label <- ifelse(practice$pred$aff > 0.2, 'aff', 'neg')
confusionMatrix(label, practice$pred$obs, positive = 'aff')

计算每个折叠中的单个组合,它将合计成上述混淆矩阵中的总数。同样,如果您在每一折中采用任何性能指标(例如特异性)并将其平均,您还将从上一行获得特异性。如果需要确认,只需再次检查确保您做的一切正确。

© www.soinside.com 2019 - 2024. All rights reserved.