【问题标题】:R list containing training set and test set objects包含训练集和测试集对象的 R 列表
【发布时间】:2020-12-10 21:14:45
【问题描述】:

我正在尝试创建 10 折数据。我想要的是一个长度为 10(折叠数)的数据结构,并且该数据结构的每个元素都包含一个具有两个属性/元素的对象/数据结构;那个折叠的训练集和测试集。这是我的 R 代码。 例如,我想访问 View(data_pairs[[8]]$training_set) 的第 8 折训练集。但它没有用。任何帮助将不胜感激:)

k <- 10    # number of folds

i <- 1:k  


folds <- sample(i, nrow(data), replace = TRUE)

data_pairs <- list()

for (j in i) {
  
  test_ind <- which(folds==j,arr.ind=TRUE)
  
  test <- data[test_ind,]
  train <- data[-test_ind,]
  
  data_pair <- list(training_set = list(train), test_set = list(test))
  
  data_pairs <- append(x = data_pairs, values = data_pair)
  
}

【问题讨论】:

    标签: r machine-learning


    【解决方案1】:

    您非常接近,您只需将values 包装在list 调用中。

    k <- 10    # number of folds
    
    i <- 1:k  
    folds <- sample(i, nrow(mtcars), replace = TRUE)
    
    data_pairs <- list()
    
    for (j in i) {
      
      test_ind <- which(folds==j,arr.ind=TRUE)
      
      test <- mtcars[test_ind,]
      train <- mtcars[-test_ind,]
      data_pair <- list(training_set = train, test_set = test)
      data_pairs <- append(x = data_pairs, values = list(data_pair))
      #data_pairs <- c(data_pairs, list(data_pair))
    }
    

    如果您的数据很大,我建议您阅读这两篇文章,了解如何更有效地增加列表。

    1. Append an object to a list in R in amortized constant time, O(1)?
    2. Here we go again: append an element to a list in R

    我还想指出,您并没有创建数据的“折叠”。在您的情况下,您正在尝试 10 倍交叉验证,这意味着您的数据应该分成 10 个“相等”大小的块。然后创建 10 个训练/测试数据集,将每个折叠用作测试数据,其余用于训练。

    【讨论】:

      【解决方案2】:

      似乎modelr 包可以在这里为您提供帮助。 我会特别指出:

      https://modelr.tidyverse.org/reference/resample_partition.html

      library(modelr)
      ex <- resample_partition(mtcars, c(test = 0.3, train = 0.7))
      
      mod <- lm(mpg ~ wt, data = ex$train)
      
      rmse(mod, ex$test)
      #> [1] 3.229756
      rmse(mod, ex$train)
      #> [1] 2.88216
      

      或者,可以通过以下方式生成这些分区的数据集: crossv_mc(data, n, test = 0.2, id = ".id")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-01
        • 2013-06-18
        • 2015-01-17
        • 2019-08-15
        • 2015-04-21
        • 2018-04-22
        • 2012-12-04
        • 1970-01-01
        相关资源
        最近更新 更多