Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为K折叠交叉验证手动创建折叠R_R_Cross Validation - Fatal编程技术网

为K折叠交叉验证手动创建折叠R

为K折叠交叉验证手动创建折叠R,r,cross-validation,R,Cross Validation,我试图用K=5建立一个K倍CV回归模型。我尝试使用“boot”package cv.glm函数,但我的电脑内存不足,因为启动包总是计算旁边的LOOCV MSE。所以我决定手动操作,但遇到了以下问题。我试图将数据帧划分为5个长度相等的向量,其中包含df行数的1/5样本,但我从第三次折叠中得到了无法解释的长度 a <- sample((d<-1:1000), size = 100, replace = FALSE) b <- sample((d<-1:1000), size

我试图用K=5建立一个K倍CV回归模型。我尝试使用“boot”package cv.glm函数,但我的电脑内存不足,因为启动包总是计算旁边的LOOCV MSE。所以我决定手动操作,但遇到了以下问题。我试图将数据帧划分为5个长度相等的向量,其中包含df行数的1/5样本,但我从第三次折叠中得到了无法解释的长度

a <- sample((d<-1:1000), size = 100, replace = FALSE)
b <- sample((d<-1:1000), size = 100, replace = FALSE)
c <- sample((d<-1:1000), size = 100, replace = FALSE)
df <- data.frame(a,b,c)
head(df)

# create first fold (correct: n=20)
set.seed(5)
K1row <- sample(x = nrow(df), size = (nrow(df)/5), replace = FALSE, prob = NULL)
str(K1row) # int [1:20] 21 68 90 28 11 67 50 76 88 96 ...

# create second fold (still going strong: n=20)
set.seed(5)
K2row <- sample(x = nrow(df[-K1row,]), size = ((nrow(df[-K1row,]))/4), replace = FALSE, prob = NULL)
str(K2row) # int [1:20] 17 55 72 22 8 53 40 59 69 76 ...

# create third fold (this is where it goes wrong: n=21)
set.seed(5)
K3row <- sample(x = nrow(df[-c(K1row,K2row),]), size = ((nrow(df[-c(K1row,K2row),]))/3), replace = FALSE, prob = NULL)
str(K3row) # int [1:21] 13 44 57 18 7 42 31 47 54 60 ...

# create fourth fold (and it gets worse: n=26)
set.seed(5)
K4row <- sample(x = nrow(df[-c(K1row,K2row,K3row),]), size = ((nrow(df[-c(K1row,K2row,K3row),]))/2), replace = FALSE, prob = NULL)
str(K4row) # int [1:26] 11 35 46 14 6 33 25 37 43 5 ...

a这是因为K1row和K2row有一些共同的元素。你是有效的抽样替换。下面的方法使用模来均匀地分割行

set.seed(5)
rand <- sample(nrow(df))

K1row <- rand[rand %% 5 + 1 == 1]
K2row <- rand[rand %% 5 + 1 == 2]
K3row <- rand[rand %% 5 + 1 == 3]
K4row <- rand[rand %% 5 + 1 == 4]
K5row <- rand[rand %% 5 + 1 == 5]
set.seed(5)

因为K1row和K2row有一些共同的元素。您正在使用替换有效地进行采样。感谢您的快速评论ddunn801!它工作得很好!你能再解释一下模分裂吗?我对此不熟悉。那么,如何创建替换零件呢?除以后,模返回余数。例:17模5意味着将17除以5(即3,余数2),然后返回2。这是一种将任何数量分成大致相等的桶的方法,因为您使用的模(例如,5)是剩余的数量(0,1,2,3,4,重复)。您的原始方法不知道之前选择了哪些行,因此它会多次拾取相同的行号。您请求的非替换适用于该样本,但不适用于每个样本。如果您对答案满意,请单击复选标记以将此问题标记为完成。