mpg*_*mpg 4 r classification machine-learning decision-tree confusion-matrix
我不能为我的生活弄清楚如何计算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)
Run Code Online (Sandbox Code Playgroud)
现在,我想我会做类似的事情
table(predict(UB_rpart, UBank_test, UBank_Test$Default))
Run Code Online (Sandbox Code Playgroud)
但这并没有给我一个混乱的矩阵.
jos*_*ber 12
您没有提供可重现的示例,因此我将创建一个合成数据集:
set.seed(144)
df = data.frame(outcome = as.factor(sample(c(0, 1), 100, replace=T)),
x = rnorm(100))
Run Code Online (Sandbox Code Playgroud)
predict
具有rpart
模型的函数type="class"
将返回每个观察的预测类.
library(rpart)
mod = rpart(outcome ~ x, data=df)
pred = predict(mod, type="class")
table(pred)
# pred
# 0 1
# 51 49
Run Code Online (Sandbox Code Playgroud)
最后,您可以通过table
在预测和真实结果之间运行来构建混淆矩阵:
table(pred, df$outcome)
# pred 0 1
# 0 36 15
# 1 14 35
Run Code Online (Sandbox Code Playgroud)