2016-11-11 213 views
1

我在R中使用createFolds函數來創建返回成功結果的摺疊。但是,當我使用循環來執行一些計算每個摺疊我得到錯誤以下。 代碼是:下標越界-R錯誤

set.seed(1000) 
k <- 10 
folds <- createFolds(train_data,k=k,list = TRUE, returnTrain = FALSE) 
str(folds) 

這是給輸出:

List of 10 
$ Fold01: int [1:18687] 1 8 10 21 22 25 26 29 34 35 ... 
$ Fold02: int [1:18685] 5 11 14 32 40 46 50 52 56 58 ... 
$ Fold03: int [1:18685] 16 20 39 47 49 77 78 83 84 86 ... 
$ Fold04: int [1:18685] 3 15 30 38 41 44 51 53 54 55 ... 
$ Fold05: int [1:18685] 7 9 17 18 23 37 42 67 75 79 ... 
$ Fold06: int [1:18686] 6 31 36 48 72 74 90 113 114 121 ... 
$ Fold07: int [1:18686] 2 33 59 61 100 103 109 123 137 161 ... 
$ Fold08: int [1:18685] 24 64 68 87 88 101 110 130 141 152 ... 
$ Fold09: int [1:18684] 4 27 28 66 70 85 97 105 112 148 ... 
$ Fold10: int [1:18684] 12 13 19 43 65 91 94 108 134 138 ... 

但是下面的代碼是給我的錯誤

for(i in 1:k){ 
    testData <- train_data[folds[[i]], ] 
    trainData <- train_data[(-folds[[i]]), ] 
} 

錯誤是:

> for(i in 1:k){ 
+ testData <- train_data[folds[[i]], ] 
+ trainData <- train_data[(-folds[[i]]), ] 
+ } 
Error in train_data[folds[[i]], ] : subscript out of bounds 

我試着與不同的種子值,但我得到同樣的錯誤。 任何幫助表示讚賞。 謝謝!

回答

0

根據我的理解,您的問題正在出現,因爲您正在使用整個數據幀train_data來創建摺疊。可以爲樣本生成K-fold,即數據集的行。

例如:

data(spam) # from package kernlab 
dim(spam) #has 4601 rows/samples 
folds <- createFolds(y=spam$type, k=10, list=T, returnTrain = T) 
# Here, only one column , spam$type, is used 
# and indeed 
max(unlist(folds)) #4601 
#and these can be used as row indices 
head(spam[folds[[4]], ]) 

使用整個數據框非常相似,使用矩陣。這樣的矩陣將首先轉換爲矢量。因此一個5x10矩陣實際上將被轉換爲50個元素向量,並且摺疊中的值將對應於該向量的索引。如果您嘗試將這些值用作數據幀的行索引,則它們將會過沖

r <- 8 
c <- 10 
m0 <- matrix(rnorm(r*c), r, c) 
features<-apply(m0, c(1,2), function(x) sample(c(0,1),1)) 
features 
folds<-createFolds(features,4)  
folds 
max(unlist(folds)) 

m0[folds[[2]],] # Error in m0[folds[[2]], ] : subscript out of bounds