r - R Caret中随机森林的混淆矩阵

标签 r random-forest r-caret confusion-matrix

我有二进制 YES/NO 类响应的数据。使用以下代码运行 RF 模型。我在获取混淆矩阵结果时遇到问题。

 dataR <- read_excel("*:/*.xlsx")
 Train    <- createDataPartition(dataR$Class, p=0.7, list=FALSE)  
 training <- dataR[ Train, ]
 testing  <- dataR[ -Train, ]

model_rf  <- train(  Class~.,  tuneLength=3,  data = training, method = 
"rf",  importance=TRUE,  trControl = trainControl (method = "cv", number = 
5))

结果:
Random Forest 

3006 samples
82 predictor
2 classes: 'NO', 'YES' 

No pre-processing
Resampling: Cross-Validated (5 fold) 
Summary of sample sizes: 2405, 2406, 2405, 2404, 2404 
Addtional sampling using SMOTE

Resampling results across tuning parameters:

 mtry  Accuracy   Kappa    
  2    0.7870921  0.2750655
  44    0.7787721  0.2419762
 87    0.7767760  0.2524898

Accuracy was used to select the optimal model using  the largest value.
The final value used for the model was mtry = 2.

到目前为止还好,但是当我运行此代码时:
# Apply threshold of 0.50: p_class
class_log <- ifelse(model_rf[,1] > 0.50, "YES", "NO")

# Create confusion matrix
p <-confusionMatrix(class_log, testing[["Class"]])

##gives the accuracy
p$overall[1]

我收到此错误:
 Error in model_rf[, 1] : incorrect number of dimensions

如果你们能帮助我获得混淆矩阵结果,我将不胜感激。

最佳答案

据我了解,您想获得插入符号中交叉验证的混淆矩阵。

为此,您需要指定 savePredictionstrainControl .如果设置为 "final"保存最佳模型的预测。通过指定 classProbs = T每个类的概率也将被保存。

data(iris)
iris_2 <- iris[iris$Species != "setosa",] #make a two class problem
iris_2$Species <- factor(iris_2$Species) #drop levels

library(caret)
model_rf  <- train(Species~., tuneLength = 3, data = iris_2, method = 
                       "rf", importance = TRUE,
                   trControl = trainControl(method = "cv",
                                            number = 5,
                                            savePredictions = "final",
                                            classProbs = T))

预测在:
model_rf$pred

按 CV fols 排序,按原始数据框排序:
model_rf$pred[order(model_rf$pred$rowIndex),2]

获得混淆矩阵:
confusionMatrix(model_rf$pred[order(model_rf$pred$rowIndex),2], iris_2$Species)
#output
Confusion Matrix and Statistics

            Reference
Prediction   versicolor virginica
  versicolor         46         6
  virginica           4        44

               Accuracy : 0.9            
                 95% CI : (0.8238, 0.951)
    No Information Rate : 0.5            
    P-Value [Acc > NIR] : <2e-16         

                  Kappa : 0.8            
 Mcnemar's Test P-Value : 0.7518         

            Sensitivity : 0.9200         
            Specificity : 0.8800         
         Pos Pred Value : 0.8846         
         Neg Pred Value : 0.9167         
             Prevalence : 0.5000         
         Detection Rate : 0.4600         
   Detection Prevalence : 0.5200         
      Balanced Accuracy : 0.9000         

       'Positive' Class : versicolor 

在两个类别的设置中,通常将 0.5 指定为阈值概率是次优的。通过优化 Kappa 或 Youden's J 统计(或任何其他首选)作为概率的函数,可以在训练后找到最佳阈值。下面是一个例子:
sapply(1:40/40, function(x){
  versicolor <- model_rf$pred[order(model_rf$pred$rowIndex),4]
  class <- ifelse(versicolor >=x, "versicolor", "virginica")
  mat <- confusionMatrix(class, iris_2$Species)
  kappa <- mat$overall[2]
  res <- data.frame(prob = x, kappa = kappa)
  return(res)
})

这里的最高 kappa 不是在 threshold == 0.5 处获得的但在 0.1。这应该谨慎使用,因为它可能导致过度拟合。

关于r - R Caret中随机森林的混淆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46816174/

相关文章:

r - 根据变量在新数据框中设置列名称

r - 较长的物体长度不是较短的物体长度的倍数吗?

python - 随机森林在 opencv python (cv2) 中不起作用

python - 从随机森林导出特征重要性到 csv

R - plotly - 结合气泡图和等值线图

r - 将不同长度的长格式数据帧组合并转换为宽格式

r - 如何安装旧的 R 包?

r - 插入符号的 rfe 函数中的下标越界错误

r - 对象 'pkgInfo' 未找到,r

r - 用于summaryFunction插入符号分类的自定义指标(hmeasure)