簡體   English   中英

來自rpart的混淆矩陣

[英]confusion matrix from rpart

我一生都無法弄清楚如何在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

你可以試試

pred <- predict(UB_rpart, UB_test) confusionMatrix(pred, UB_test$Personal.Loan)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM