我正在 RStudio 中执行随机森林分析,我可以使用下面的代码提取混淆矩阵。我可以看到有多少样本被错误分类,但是我可以使用什么代码来识别哪些特定样本被错误分类?
library(randomForest)
library(rfPermute)
rfmetrics <- randomForest(x, y, ntree=ntree, importance=T)
print(rfmetrics)
Call:
randomForest(x = x, y = y, ntree = ntree, importance = T)
Type of random forest: classification
Number of trees: 1999
No. of variables tried at each split: 25
OOB estimate of error rate: 56.88%
Confusion matrix:
1 2 3 4 class.error
1 8 7 7 4 0.6923077
2 4 19 2 4 0.3448276
3 3 3 15 6 0.4444444
4 3 9 10 5 0.8148148
如果您分享一个最小的可重现示例,我们可以更好地帮助您。无论如何,这段代码可能很有用:
library(dplyr)
data.frame(y, y_hat = myrf$predicted) %>%
mutate(id = row_number()) %>%
filter(y != y_hat)
其中
y
是您观察到的响应向量,y_hat
是基于您的估计的预测值,id
内的 mutate
是指示第 i 个观察值的位置的新列,y != y_hat
filter
唯一的观察被错误分类。您可以使用 id
来查找这些值。