【问题标题】:How to create a precision recall curve from a random forest model?如何从随机森林模型创建精确召回曲线?
【发布时间】:2020-08-03 05:25:32
【问题描述】:

我正在尝试根据仅基于训练数据的随机森林模型创建精确召回曲线。它类似于this question,但我不知道创建PR曲线的代码。请参阅下面的可重现示例(已修改以匹配我的个人数据集):

#Load beaver2
View(beaver2)

#convert outcome into factor
beaver2 <- beaver2 %>% mutate(activ = ifelse(activ==0, "no","yes"))

#convert outcome to factor
beaver2$activ <- as.factor(beaver2$activ)

#create trControl
data_ctrl_null <- trainControl(method="cv", number = 5, classProbs = TRUE, summaryFunction=twoClassSummary, savePredictions=T, sampling=NULL)

#create rf model
rf_model <- train(activ ~ ., data=beaver2, trControl = data_ctrl_null, method= "rf", preProc=c("center","scale"),metric="ROC", importance=TRUE)

#create precision recall curve
library("PRROC")

我想使用PRROC 包。如何从随机森林模型中获取预测并创建 PR 曲线?笔记;我想对我的训练数据进行预测;所以想象一下没有用于预测的测试数据。非常感谢所有的帮助!

【问题讨论】:

标签: r random-forest precision-recall


【解决方案1】:
#Load beaver2
View(beaver2)
library(dplyr)
library(caret)

#convert outcome into factor
beaver2 <- beaver2 %>% mutate(activ = ifelse(activ==0, "no","yes"))

#convert outcome to factor
beaver2$activ <- as.factor(beaver2$activ)

#create trControl
data_ctrl_null <- trainControl(method="cv", number = 5, classProbs = TRUE, summaryFunction=twoClassSummary, savePredictions=T, sampling=NULL)

#create rf model
rf_model <- train(activ ~ ., data=beaver2, trControl = data_ctrl_null, method= "rf", preProc=c("center","scale"),metric="ROC", importance=TRUE)

# predict using train data
predictions <- predict.train(rf_model)
test_data <- beaver2 %>% select(-activ) #instead of train data, use unseen test data here.
predictions <- predict(object = rf_model, newdata = test_data)
#add some artificial wrong predictions, otherwise perfect prediction, since we use train data as test
predictions[1] <- 'yes'
predictions[18] <- 'yes'
predictions[60] <- 'no'
predictions[61] <- 'no'
predictions[100] <- 'no'
confusion_Matrix <- table(Predictions = predictions, Reference = beaver2$activ)

#create precision recall curve
library("PRROC")

fg <- predictions[beaver2$activ == 'yes']
bg <- predictions[beaver2$activ == 'no']

pr <- pr.curve(scores.class0 = fg, scores.class1 = bg, curve = T)
plot(pr)

也可以在这里查看回复:https://stats.stackexchange.com/questions/10501/calculating-aupr-in-r

【讨论】:

  • 几天后回过头来看,为什么在训练数据和测试数据上都可以轻松计算ROC时,为什么还要从测试数据中进行精确召回呢?运行“predictions
【解决方案2】:

如果您没有固定在 PROC 包上,我可以向您强烈推荐 MLeval 包中的 evalm 函数。使用插入符号,它工作得非常好且简单。

在你的情况下,你需要做的就是

x <- evalm(rf_model )
x$roc #roc curve
x$stdres #model specs
x$cc #calibration plot

为您的火车数据集。此代码适用于您的测试数据集:

test <- evalm(data.frame(pred, test.data$outcome))
test$roc
test$stdres
test$cc

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2018-10-29
    • 2016-07-12
    • 2020-03-08
    • 2020-04-18
    • 2021-09-13
    • 2017-09-21
    • 2016-11-07
    • 2012-09-04
    相关资源
    最近更新 更多