[英]Confusion matrix for random forest in R Caret
我有二進制YES / NO Class響應的數據。 使用以下代碼運行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
如果你們能幫助我得到混淆矩陣結果,我感激不盡。
據我所知,您希望獲得插入符號中交叉驗證的混淆矩陣。
為此,您需要在savePredictions
中指定trainControl
。 如果設置為"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的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時獲得的。 這應該謹慎使用,因為它可能導致過度配合。
您可以嘗試這樣來創建混淆矩陣並檢查准確性
m <- table(class_log, testing[["Class"]])
m #confusion table
#Accuracy
(sum(diag(m)))/nrow(testing)
代碼片段class_log <- ifelse(model_rf[,1] > 0.50, "YES", "NO")
是執行以下測試的if-else語句:
在
model_rf
的第一列中,如果數字大於0.50,則返回“YES”,否則返回“NO”,並將結果保存在對象class_log
。
因此,代碼基本上根據數字向量創建類標簽的字符向量,“YES”和“NO”。
您需要將模型應用於測試集。
prediction.rf <- predict(model_rf, testing, type = "prob")
然后執行class_log <- ifelse(prediction.rf > 0.50, "YES", "NO")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.