【问题标题】:confusion matrix from rpart来自 rpart 的混淆矩阵
【发布时间】:2014-02-11 23:31:11
【问题描述】:

我终其一生都无法弄清楚如何在 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))

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

【问题讨论】:

    标签: r machine-learning classification decision-tree confusion-matrix


    【解决方案1】:

    你可以试试

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

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 2018-04-26
        • 2018-09-07
        • 2021-03-13
        • 2014-07-09
        • 2015-12-17
        • 2020-10-01
        • 2012-01-20
        • 2019-11-23
        • 1970-01-01
        相关资源
        最近更新 更多