gpt4 book ai didi

r - 为决策树的概率结果设置阈值

转载 作者:行者123 更新时间:2023-12-05 05:19:31 24 4
gpt4 key购买 nike

我在进行决策树模型后尝试计算混淆矩阵

# tree model
tree <- rpart(LoanStatus_B ~.,data=train, method='class')
# confusion matrix
pdata <- predict(tree, newdata = test, type = "class")
confusionMatrix(data = pdata, reference = test$LoanStatus_B, positive = "1")

我如何为我的混淆矩阵设置阈值,比如我希望默认概率高于 0.2,这是二元结果。

最佳答案

这里有几点需要注意。首先,确保在进行预测时获得类别概率。使用预测类型 ="class" 你只是得到离散的类,所以你想要的是不可能的。所以你要让它像下面我的那样 "p"

library(rpart)
data(iris)

iris$Y <- ifelse(iris$Species=="setosa",1,0)

# tree model
tree <- rpart(Y ~Sepal.Width,data=iris, method='class')

# predictions
pdata <- as.data.frame(predict(tree, newdata = iris, type = "p"))
head(pdata)

# confusion matrix
table(iris$Y, pdata$`1` > .5)

接下来请注意,这里的 .5 只是一个任意值——您可以将其更改为任何您想要的值。

我看不出有什么理由使用 confusionMatrix 函数,因为可以通过这种方式简单地创建混淆矩阵并允许您实现轻松更改截止值的目标。

话虽如此,如果您确实想为您的混淆矩阵使用 confusionMatrix 函数,那么只需首先根据您的自定义截止值创建一个离散类预测,如下所示:

pdata$my_custom_predicted_class <- ifelse(pdata$`1` > .5, 1, 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

关于r - 为决策树的概率结果设置阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com