【问题标题】:k-fold nested repeated cross validation in RR中的k-fold嵌套重复交叉验证
【发布时间】:2020-08-17 19:55:51
【问题描述】:

我需要进行四重嵌套重复交叉验证来训练模型。 我编写了以下代码,它具有内部交叉验证,但现在我正在努力创建外部。

fitControl <- trainControl(## 10-fold CV
                           method = "repeatedcv",
                           number = 10,
                           ## repeated five times
                           repeats = 5,
                           savePredictions = TRUE,
                           classProbs = TRUE,
                           summaryFunction = twoClassSummary)

model_SVM_P <- train(Group ~ ., data = training_set, 
                 method = "svmPoly", 
                 trControl = fitControl,
                 verbose = FALSE,
                 tuneLength = 5)

我尝试解决这个问题:

ntrain=length(training_set)    
train.ext=createFolds(training_set,k=4,returnTrain=TRUE)
test.ext=lapply(train.ext,function(x) (1:ntrain)[-x])

for (i in 1:4){
    model_SVM_P <- train(Group ~ ., data = training_set[train.ext[[i]]], 
                 method = "svmRadial", 
                 trControl = fitControl,
                 verbose = FALSE,
                 tuneLength = 5) 

    }

但它没有奏效。 我该如何做这个外循环?

【问题讨论】:

  • 这个答案可能会很有帮助stackoverflow.com/questions/62183291/…。您的代码中的问题是您为每个i 创建了四次model_SVM_P,而不是将四次迭代的结果保存在一个列表中。
  • 我尝试将结果添加到列表中,但它不起作用。如何创建对象列表? model_SVM_P 类是“train”和“train.function”,我找不到创建这些元素列表的方法
  • 您可以在链接的帖子中使用lapply 方法。要了解如何在 R 中使用 for 循环,请阅读:r4ds.had.co.nz/iteration.html

标签: r machine-learning r-caret


【解决方案1】:

rsample 包在nested_cv() 函数中实现了外循环,参见documentation

要评估由nested_cv 训练的模型,请查看vignette,它显示了“繁重”的完成位置:

# `object` is an `rsplit` object in `results$inner_resamples` 
summarize_tune_results <- function(object) {
  # Return row-bound tibble that has the 25 bootstrap results
  map_df(object$splits, tune_over_cost) %>%
    # For each value of the tuning parameter, compute the 
    # average RMSE which is the inner bootstrap estimate. 
    group_by(cost) %>%
    summarize(mean_RMSE = mean(RMSE, na.rm = TRUE),
              n = length(RMSE),
              .groups = "drop")
}

tuning_results <- map(results$inner_resamples, summarize_tune_results)

此代码将tune_over_cost 函数应用于每个超参数并拆分(或折叠)训练数据,此处称为“评估数据”。

请查看小插图以获取更多有用的代码,包括并行化。

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 2016-10-21
    • 2019-02-19
    • 2011-10-01
    • 2020-10-25
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    相关资源
    最近更新 更多