caret: combine createResample and groupKFold

主宰稳场 提交于 2019-12-06 04:20:44

I trust this will solve your problem

library(caret)
x <- rep(1:12, each = 30)
folds <- groupKFold(x, k = 12)

provide 10 bootstrap replicates in a nested list for each of the groups in folds - this solves the lost indexes problem.

folds2 <- lapply(folds, function(x) lapply(1:10, function(i) sample(x, size = length(x), replace = TRUE)))

convert nested list to a one dimensional list - this solves the nested list problem.

folds2 <- unlist(folds2 , recursive = FALSE, use.names = TRUE)

does it work?

df <- data.frame(y = rnorm(360), x = rnorm(360))

lm_formula <- train(
  y ~ ., df,
  method = "lm",
  trControl = trainControl(method = "boot" , index = folds2)
)

looks like it does.

The only issue is perhaps in the intended indexOut for each resample, in the example all indexes not present in the fold were used as test. If I understood you would like to test on the held out months and not on all the held out samples. To solve this:

folds_out <- lapply(folds, function(x) setdiff(1:360, x))
folds_out <- rep(folds_out, each = 10)
names(folds_out) <- names(folds2)

lm_formula <- train(
  y ~ ., df,
  method = "lm",
  trControl = trainControl(method = "boot" , index = folds2, indexOut = folds_out)
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!