r - 如何将插入符号训练的随机森林模型输入到 predict() 和 performance() 函数中?
问题描述
我想使用创建精确召回曲线,performance()
但我不知道如何输入我的数据。我按照这个例子。
attach(ROCR.simple)
pred <- prediction(ROCR.simple$predictions, ROCR.simple$labels)
perf <- performance(pred,"prec","rec")
plot(perf)
我正在尝试为我caret
训练有素的 RF 模型专门模拟训练数据(我知道有各种关于如何使用predict
的示例newdata
)。我试过这个:
pred <- prediction(rf_train_model$pred$case, rf_train_model$pred$pred)
perf <- performance(pred,"prec","rec")
plot(perf)
我的模型如下。我尝试了上述方法,因为这似乎与ROCR.simple
数据匹配。
#create model
ctrl <- trainControl(method = "cv",
number = 5,
savePredictions = TRUE,
summaryFunction = twoClassSummary,
classProbs = TRUE)
set.seed(3949)
rf_train_model <- train(outcome ~ ., data=df_train,
method= "rf",
ntree = 1500,
tuneGrid = data.frame(mtry = 33),
trControl = ctrl,
preProc=c("center","scale"),
metric="ROC",
importance=TRUE)
> head(rf_train_model$pred)
pred obs case control rowIndex mtry Resample
1 control control 0.3173333 0.6826667 4 33 Fold1
2 control control 0.3666667 0.6333333 7 33 Fold1
3 control control 0.2653333 0.7346667 16 33 Fold1
4 control control 0.1606667 0.8393333 18 33 Fold1
5 control control 0.2840000 0.7160000 20 33 Fold1
6 case case 0.6206667 0.3793333 25 33 Fold1
这是错误的,因为我的精确召回曲线走错了路。我感兴趣的不仅仅是 PRAUC 曲线,尽管这是一个很好的来源,它展示了如何制作它,所以我想修复这个错误。我犯了什么错误?
解决方案
如果您阅读性能的小插曲:
必须声明哪个类标签表示负类,哪个类标签表示正类。理想情况下,标签应作为有序因子提供,较低级别对应于负类,上层对应于正类。如果标签是因子(无序)、数字、逻辑或字符,标签的顺序是从 R 的内置 < 关系推断出来的(例如 0 < 1, -1 < 1, 'a' < 'b', FALSE < TRUE )。
在您的情况下,当您提供 rf_train_model$pred$pred 时,上层仍然是“控制”,因此最好的方法是使其为 TRUE / FALSE。此外,您应该提供实际标签,而不是预测标签rf_train_model$obs
。请参阅下面的示例:
library(caret)
library(ROCR)
set.seed(100)
df = data.frame(matrix(runif(100*100),ncol=100))
df$outcome = ifelse(runif(100)>0.5,"case","control")
df_train = df[1:80,]
df_test = df[81:100,]
rf_train_model <- train(outcome ~ ., data=df_train,
method= "rf",
ntree = 1500,
tuneGrid = data.frame(mtry = 33),
trControl = ctrl,
preProc=c("center","scale"),
metric="ROC",
importance=TRUE)
levels(rf_train_model$pred$pred)
[1] "case" "control"
plotCurve = function(label,positive_class,prob){
pred = prediction(prob,label==positive_class)
perf <- performance(pred,"prec","rec")
plot(perf)
}
plotCurve(rf_train_model$pred$obs,"case",rf_train_model$pred$case)
plotCurve(rf_test$outcome,"case",predict(rf_train,df_test,type="prob")[,2])
推荐阅读
- r - dcast() - 添加 R 中不存在的列
- microsoft-graph-sdks - Microsoft.Graph:如何设置大型嵌入式嵌入式附件/图像的 ContentId
- visual-studio - 如何组织 Visual Studio 发布文件夹?
- ios - react-native-firebase:onNotificationOpenedApp 和 getInitialNotification 在 iOS 上不起作用
- javascript - 调用从 React 到 SailsJs 的 GET 路由时出现 401 Forbidden
- elasticsearch - Elasticsearch 术语聚合和小写值
- css - 如何使用 CSS 变换比例使对象居中
- amazon-s3 - 尝试通过 Logstash 传递二进制文件
- google-sheets - 将多个电子表格文件合并到一个主概览中(只读)
- java - 如何在整个硬盘驱动器中搜索特定文件(Java Eclipse)?