来自插入符号的交叉验证预测分配给不同的折叠

Cross-validation predictions from caret in assigned to different folds

我想知道为什么 'Fold1' 的预测实际上是我预定义折叠中第二个折叠的预测。我附上我的意思的例子。

# load the library
library(caret)
# load the cars dataset
data(cars)
# define folds
cv_folds <- createFolds(cars$Price, k = 5, list = TRUE, returnTrain = TRUE)
# define training control
train_control <- trainControl(method="cv", index = cv_folds, savePredictions = 'final')
# fix the parameters of the algorithm
# train the model
model <- caret::train(Price~., data=cars, trControl=train_control, method="gbm", verbose = F)

model$pred$rowIndex[model$pred$Resample == 'Fold1'] %in% cv_folds[[2]]

'Fold1'的Resample数据是cv_folds[[1]]中没有的记录。这些记录包含在 cv_folds 2-5 中。这是正确的,因为您是 运行 5 折交叉验证。对 Resample Fold 1 进行测试,以在折叠 2-5 上训练模型。针对折叠 1、3-5 等的训练对 Resample fold 2 进行测试。

总结:Fold1 中的预测是在 cv_folds 2-5 上训练模型的测试预测。

编辑:根据评论

所有需要的信息都在 model$pred table 中。我添加了一些代码来说明:

model$pred %>% 
  select(rowIndex, pred, Resample) %>%
  rename(predection = pred, holdout = Resample) %>% 
  mutate(trained_on = case_when(holdout == "Fold1" ~ "Folds 2, 3, 4, 5",
                                holdout == "Fold2" ~ "Folds 1, 3, 4, 5", 
                                holdout == "Fold3" ~ "Folds 1, 2, 4, 5", 
                                holdout == "Fold4" ~ "Folds 1, 2, 3, 5", 
                                holdout == "Fold5" ~ "Folds 1, 2, 3, 4"))

  rowIndex predection holdout       trained_on
1      610   13922.60   Fold2 Folds 1, 3, 4, 5
2      623   38418.83   Fold2 Folds 1, 3, 4, 5
3      604   12383.55   Fold2 Folds 1, 3, 4, 5
4      607   15040.07   Fold2 Folds 1, 3, 4, 5
5       95   33549.40   Fold2 Folds 1, 3, 4, 5
6      624   40357.35   Fold2 Folds 1, 3, 4, 5

基本上,您需要进一步叠加预测的是模型 $pred table 中的 predrowIndex 列。

rowIndex 指的是原始数据中的行。所以 rowIndex 610 指的是汽车数据集中的记录 610。你可以对比一下obs中的数据,也就是cars数据集中Price列的值。