首页 > 解决方案 > R中的模型评估与混淆矩阵

问题描述

嗨,我已经使用 ROCR 包来检查模型的性能,我想做更多的评估,比如带有 kappa 值或 k 折叠的混淆矩阵。以下是模型和预测,任何帮助都会很棒。

   model <- cv.glmnet(sparesemx[train.set,],
            first.round[train.set],
            alpha = 0.05,
            family = 'binomial')

 training$sparse.fr.hat <- predict(model, newx = sparesemx, type = 
 'response')[,1]

predictions <- prediction(training$sparse.fr.hat[test.set], 
first.round[test.set])
perform <- performance(predictions, 'tpr', 'fpr')
plot(perform)
performance(predictions, 'auc')

我正在尝试将插入符号库与confusionMatrix() 函数一起使用,但我无法生成矩阵。我已经为这两个 agruments 尝试了几个输入,但我不确定需要什么

标签: rmachine-learning

解决方案


工作示例,逐步详细说明。

library(OptimalCutpoints)
library(caret)
library(glmnet)
library(e1071)

data(elas) #predicting for variable "status"

将数据拆分elas为训练 (dev) 和测试 (val)

sample.ind <- sample(2, 
                     nrow(elas),
                     replace = T,
                     prob = c(0.6,0.4))
elas.dev <- elas[sample.ind==1,]
elas.val <- elas[sample.ind==2,]

此示例使用逻辑模型,因此这是指定公式的方式,类似于您的sparesemx矩阵。

formula.glm<-glm(status ~ gender + elas, data = elas, family = binomial)
xfactors<-model.matrix(formula.glm)[,-1]

glmnet.x<-as.matrix(xfactors)
glmmod<-glmnet(x=glmnet.x[sample.ind==1,],y=elas.dev$status,alpha=1,
               family='binomial')


#if you care; the lasso model includes both predictors
#cv.glmmod <- cv.glmnet(x=glmnet.x[sample.ind==1,], y=elas.dev$status, alpha=1, family='binomial')
#plot(cv.glmmod)
#cv.glmmod$lambda.min
#coef(cv.glmmod, s="lambda.min")

现在,您必须使用从 glmnet 中选择的两个预测变量来获得状态变量的预测值,您已经这样做了。

bestglm<-glm(status ~ gender + elas, data = elas.dev, family = binomial)

你已经到了这里。 我正在使用fitted.values来自我的对象并且您正在使用prediction,但您应该得到一列实际值和拟合值。这并没有告诉你切点在哪里。你在哪里划清什么是“正面”和什么是“负面”?

我建议使用OptimalCutpoints这个。

设置为optimal.cutpoints; 接下来的容器只是data.frame两个变量具有相同长度的地方。它包含来自 glm 的实际与预测。

container.for.OC<-data.frame(fit=bestglm$fitted.values, truth=elas.dev$status)

我在这里使用约登标准,但标准有很多选择。

optimal.cutpoint.Youden<-optimal.cutpoints(X = fit  ~ truth , tag.healthy = 0, 
        methods = "Youden", pop.prev = NULL,  data=container.for.OC,
        control = control.cutpoints(), ci.fit = FALSE, conf.level = 0.95, trace = FALSE)


summary(optimal.cutpoint.Youden)

这是我得到的:

Area under the ROC curve (AUC):  0.818 (0.731, 0.905) 

CRITERION: Youden
Number of optimal cutoffs: 1

                    Estimate
cutoff             0.4863188
Se                 0.9180328
Sp                 0.5882353
PPV                0.8000000
NPV                0.8000000
DLR.Positive       2.2295082
DLR.Negative       0.1393443
FP                14.0000000
FN                 5.0000000
Optimal criterion  0.5062681

#not run
#plot(optimal.cutpoint.Youden)

现在将您从 Youden 截止值中学到的知识应用到您的验证集,elas.val.

这应该与上表中的截止值相匹配。

MaxYoudenCutoff <- optimal.cutpoint.Youden$Youden$Global$optimal.cutoff$cutoff

这将为您提供约登切点的预测水平。它们必须是您的confusionMatrix功能的因素对象。

val.predicted<-predict(object=bestglm, newdata=elas.val, type="response")
val.factor.level<-factor(ifelse(val.predicted >=MaxYoudenCutoff,"1","0"))

confusionMatrix像以前一样,为函数制作一个小容器。

container.for.CM <- data.frame(truth=factor(elas.val$status), fit=val.factor.level)
confusionMatrix(data=container.for.CM$fit, reference=container.for.CM$truth)

Confusion Matrix and Statistics

          Reference
Prediction  0  1
         0  7  8
         1  6 37

               Accuracy : 0.7586          
                 95% CI : (0.6283, 0.8613)
    No Information Rate : 0.7759          
    P-Value [Acc > NIR] : 0.6895          

                  Kappa : 0.342           
 Mcnemar's Test P-Value : 0.7893          

            Sensitivity : 0.5385          
            Specificity : 0.8222          
         Pos Pred Value : 0.4667          
         Neg Pred Value : 0.8605          
             Prevalence : 0.2241          
         Detection Rate : 0.1207          
   Detection Prevalence : 0.2586          
      Balanced Accuracy : 0.6803          

       'Positive' Class : 0  

推荐阅读