Rpart mixing matrix

I can’t understand for life how to calculate the confusion matrix on rpart.

Here is what I did:

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)

Now I would think that I would do something like

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

But that does not give me confusion.

+4
source share
2 answers

You did not provide a reproducible example, so I will create a synthetic dataset:

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

The function predictfor model rpartc type="class"will return the predicted class for each observation.

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

Finally, you can build a matrix of confusion by running tablebetween the prediction and the true result:

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

You may try

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

-1
source

All Articles