这里有几点需要注意。首先,确保在进行预测时获取类别概率。如果使用预测类型="class"
,则只会得到离散的类别,因此您想要的是不可能的。所以您需要将其设置为"p"
,像下面我的代码一样。
library(rpart)
data(iris)
iris$Y <- ifelse(iris$Species=="setosa",1,0)
tree <- rpart(Y ~Sepal.Width,data=iris, method='class')
pdata <- as.data.frame(predict(tree, newdata = iris, type = "p"))
head(pdata)
table(iris$Y, pdata$`1` > .5)
请注意,这里的0.5只是任意值,您可以将其更改为任何您想要的值。
我认为没有必要使用“confusionMatrix”函数,因为可以通过以下方式简单地创建混淆矩阵,并允许您轻松更改截止值以实现目标。
话虽如此,如果您确实想要使用“confusionMatrix”函数来创建混淆矩阵,则可以首先根据您的自定义截止值创建一个离散类预测,如下所示:
pdata$my_custom_predicted_class <- ifelse(pdata$`1` > .5, 1, 0)
再次提醒,0.5是您自定义的阈值,可以根据您的需要设置。
caret::confusionMatrix(data = pdata$my_custom_predicted_class,
reference = iris$Y, positive = "1")
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 94 19
1 6 31
Accuracy : 0.8333
95% CI : (0.7639, 0.8891)
No Information Rate : 0.6667
P-Value [Acc > NIR] : 3.661e-06
Kappa : 0.5989
Mcnemar's Test P-Value : 0.0164
Sensitivity : 0.6200
Specificity : 0.9400
Pos Pred Value : 0.8378
Neg Pred Value : 0.8319
Prevalence : 0.3333
Detection Rate : 0.2067
Detection Prevalence : 0.2467
Balanced Accuracy : 0.7800
'Positive' Class : 1
?predict.rpart
以了解您可以为type
指定的其他内容。 - coffeinjunky