【问题标题】:Regarding K fold cross validation in R关于 R 中的 K 折交叉验证
【发布时间】:2019-12-18 04:02:21
【问题描述】:

我创建了这个代码的函数来执行逻辑回归的 5 折交叉验证。

  require(ISLR)
    folds <- cut(seq(1,nrow(Smarket)),breaks=5,labels=FALSE)



    log_cv=sapply(1:5,function(x)
    {
      set.seed(123)           

      testIndexes <- which(folds==x,arr.ind=TRUE)
      testData <- Smarket[testIndexes, ]
      trainData <- Smarket[-testIndexes, ]
      glm_log=glm(Direction ~ Lag1 + Lag2 + Lag3 + 
Lag4 + Lag5 + Volume ,family = "binomial",  data = trainData)
      glm.prob <- predict(glm_log, testData, "response")
      glm.pred <- ifelse(glm.prob >= 0.5, 1, 0)
      return(glm.pred)

    }
    )

上述函数的输出给出了每一折的预测值。

> head(log_cv)
  [,1] [,2] [,3] [,4] [,5]
1    1    1    0    1    1
2    0    1    1    1    1
3    0    1    1    1    0
4    1    1    0    1    1
5    1    1    1    1    1
6    1    1    1    0    1
> 

有没有什么方法可以结合以上结果使用5折交叉验证得到混淆矩阵?

【问题讨论】:

    标签: r cross-validation confusion-matrix


    【解决方案1】:

    混淆矩阵由真阳性、假阳性、真阴性、假阴性的数量组成。从交叉验证中,您需要每个折叠的平均值。您有一个预测矩阵 log_cv 需要与您的 testData 进行比较。

    虽然我相信这里的其他人会推荐 tidyverse,但一种方法是将您的测试数据转换为矩阵:

    truth <- matrix(testData$response, ncol = 5, nrow = nrow(testData))
    

    然后使用逻辑运算符来查找真阳性等:

    真正的肯定:

    mean(apply(truth & testData, 2, sum))
    

    真阴性:

    mean(apply(!truth & !testData, 2, sum))
    

    误报:

    mean(apply(truth & !testData, 2, sum))
    

    假阴性:

    mean(apply(!truth & testData, 2, sum))
    

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 2016-11-15
      • 2016-02-17
      • 2019-12-17
      • 2016-01-15
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多