gpt4 book ai didi

r - rpart 的混淆矩阵

转载 作者:行者123 更新时间:2023-11-30 08:27:18 26 4
gpt4 key购买 nike

我一生都无法弄清楚如何计算 rpart 上的混淆矩阵。

这是我所做的:

set.seed(12345)
UBANK_rand <- UBank[order(runif(1000)), ]
UBank_train <- UBank_rand[1:900, ]
UBank_test <- UBank_rand[901:1000, ]


dim(UBank_train)
dim(UBank_test)

#Build the formula for the Decision Tree
UB_tree <- Personal.Loan ~ Experience + Age+ Income +ZIP.Code + Family + CCAvg + Education

#Building the Decision Tree from Test Data
UB_rpart <- rpart(UB_tree, data=UBank_train)

现在,我想我会做类似的事情

table(predict(UB_rpart, UBank_test, UBank_Test$Default))

但这并没有给我一个混淆矩阵。

最佳答案

您没有提供可重现的示例,因此我将创建一个合成数据集:

set.seed(144)
df = data.frame(outcome = as.factor(sample(c(0, 1), 100, replace=T)),
x = rnorm(100))

具有 type="class"rpart 模型的 predict 函数将返回每个观测值的预测类别。

library(rpart)
mod = rpart(outcome ~ x, data=df)
pred = predict(mod, type="class")
table(pred)
# pred
# 0 1
# 51 49

最后,您可以通过在预测和真实结果之间运行table来构建混淆矩阵:

table(pred, df$outcome)
# pred 0 1
# 0 36 15
# 1 14 35

关于r - rpart 的混淆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21273934/

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