【问题标题】:How to obtain confusion matrix using caret package?如何使用 caret 包获取混淆矩阵?
【发布时间】:2021-04-12 16:50:15
【问题描述】:

我试图分析 caret 包提供的示例,用于混淆矩阵,即

lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
                levels = rev(lvs))
pred <- factor(
  c(
    rep(lvs, times = c(54, 32)),
    rep(lvs, times = c(27, 231))),
  levels = rev(lvs))

xtab <- table(pred, truth)

confusionMatrix(xtab)

但可以肯定的是,我不太了解它。让我们以这个非常简单的模型为例:

set.seed(42)
x <- sample(0:1, 100, T)
y <- rnorm(100)
glm(x ~ y, family = binomial('logit'))

而且我不知道如何为这个 glm 模型类似地执行混淆矩阵。你知道怎么做吗?

编辑

我尝试运行 cmets 中提供的示例:

train <- data.frame(LoanStatus_B = as.numeric(rnorm(100)>0.5), b= rnorm(100), c = rnorm(100), d = rnorm(100))
logitMod <- glm(LoanStatus_B ~ ., data=train, family=binomial(link="logit"))
library(caret)
# Use your model to make predictions, in this example newdata = training set, but replace with your test set    
pdata <- predict(logitMod, newdata = train, type = "response")

confusionMatrix(data = as.numeric(pdata>0.5), reference = train$LoanStatus_B)

但我得到错误:dataandreference`应该是具有相同水平的因素

我做错了吗?

【问题讨论】:

  • 可能是this帮助

标签: r regression glm confusion-matrix


【解决方案1】:

你只需要把它们变成因子:

confusionMatrix(data = as.factor(as.numeric(pdata>0.5)), 
                reference = as.factor(train$LoanStatus_B))
# Confusion Matrix and Statistics
# 
# Reference
# Prediction  0  1
#          0 61 31
#          1  2  6
# 
# Accuracy : 0.67            
# 95% CI : (0.5688, 0.7608)
# No Information Rate : 0.63            
# P-Value [Acc > NIR] : 0.2357          
# 
# Kappa : 0.1556          
# 
# Mcnemar's Test P-Value : 1.093e-06       
#                                           
#             Sensitivity : 0.9683          
#             Specificity : 0.1622          
#          Pos Pred Value : 0.6630          
#          Neg Pred Value : 0.7500          
#              Prevalence : 0.6300          
#          Detection Rate : 0.6100          
#    Detection Prevalence : 0.9200          
#       Balanced Accuracy : 0.5652          
#                                           
#        'Positive' Class : 0               
                              

【讨论】:

    猜你喜欢
    • 2017-12-19
    • 2018-06-03
    • 1970-01-01
    • 2018-03-30
    • 2021-12-03
    • 2018-10-02
    • 2016-05-07
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多