12

我正在尝试使用 http://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/上提供的数据为几种分类方法/超参数制作 k 折 CV声纳.所有数据

该集合由 208 行组成,每行有 60 个属性。我正在使用 read.table 函数将它读入 data.frame 中。

下一步是将我的数据分成 k 折,假设 k = 5。我的第一次尝试是使用

test <- createFolds(t, k=5)

我有两个问题。第一个是褶皱的长度不相邻:

       Length Class  Mode   
Fold1 29     -none- numeric <br />
Fold2 14     -none- numeric <br />
Fold3  7     -none- numeric <br />
Fold4  5     -none- numeric <br />
Fold5  5     -none- numeric

另一个是这显然根据属性索引拆分了我的数据,但我想拆分数据本身。我认为通过转置我的data.frame,使用:

test <- t(myDataNumericValues)

但是当我调用 createFolds 函数时,它给了我这样的信息:

       Length Class  Mode   
Fold1 2496   -none- numeric <br />
Fold2 2496   -none- numeric <br />
Fold3 2495   -none- numeric <br />
Fold4 2496   -none- numeric <br />
Fold5 2497   -none- numeric

长度问题已解决,但它仍然没有相应地拆分我的 208 数据。

我可以做什么?插入符号包可能不是最合适的吗?

4

2 回答 2

33

请阅读?createFolds以了解该功能的作用。它创建了定义哪些数据被保存在单独折叠中的索引(请参阅返回相反的选项):

  > library(caret)
  > library(mlbench)
  > data(Sonar)
  > 
  > folds <- createFolds(Sonar$Class)
  > str(folds)
  List of 10
   $ Fold01: int [1:21] 25 39 58 63 69 73 80 85 90 95 ...
   $ Fold02: int [1:21] 19 21 42 48 52 66 72 81 88 89 ...
   $ Fold03: int [1:21] 4 5 17 34 35 47 54 68 86 100 ...
   $ Fold04: int [1:21] 2 6 22 29 32 40 60 65 67 92 ...
   $ Fold05: int [1:20] 3 14 36 41 45 75 78 84 94 104 ...
   $ Fold06: int [1:21] 10 11 24 33 43 46 50 55 56 97 ...
   $ Fold07: int [1:21] 1 7 8 20 23 28 31 44 71 76 ...
   $ Fold08: int [1:20] 16 18 26 27 38 57 77 79 91 99 ...
   $ Fold09: int [1:21] 13 15 30 37 49 53 74 83 93 96 ...
   $ Fold10: int [1:21] 9 12 51 59 61 62 64 70 82 87 ...

要使用这些来拆分数据:

   > split_up <- lapply(folds, function(ind, dat) dat[ind,], dat = Sonar)
   > dim(Sonar)
   [1] 208  61
   > unlist(lapply(split_up, nrow))
   Fold01 Fold02 Fold03 Fold04 Fold05 Fold06 Fold07 Fold08 Fold09 Fold10 
       21     21     21     21     20     21     21     20     21     21 

此包中使用该函数train进行实际建模(您通常不需要自己进行拆分。请参阅此页面)。

于 2014-04-07T13:33:27.667 回答
0

我对caret包不熟悉,但我曾经写过一个基于包中的决策树计算 CV 的函数rpart。当然,该功能需要主题化以适合您的目的。

CV <- function(form, x, fold = 10, cp = 0.01) {
  # x is the data
  n <- nrow(x)
  prop <- n%/%fold
  set.seed(7)
  newseq <- rank(runif(n))
  k <- as.factor((newseq - 1)%/%prop + 1)

  y <- unlist(strsplit(as.character(form), " "))[2]
  vec.accuracy <- vector(length = fold)
  for (i in seq(fold)) {
    # It depends on which classification method you use
    fit <- rpart(form, data = x[k != i, ], method = "class")
    fit.prune <- prune(fit, cp = cp)
    fcast <- predict(fit.prune, newdata = x[k == i, ], type = "class")
    cm <- table(x[k == i, y], fcast)
    accuracy <- (cm[1, 1] + cm[2, 2])/sum(cm)
    vec.accuracy[i] <- accuracy
  }
avg.accuracy <- mean(vec.accuracy)
avg.error <- 1 - avg.accuracy
cv <- data.frame(Accuracy = avg.accuracy, Error = avg.error)
return(cv)

}

于 2014-04-07T06:01:46.993 回答