【问题标题】:R: Why doesn't the negative index work to create the complement set?R:为什么负索引不能创建补集?
【发布时间】:2021-11-05 20:15:34
【问题描述】:

我正在尝试创建训练、验证和测试数据集。 (在将数据框过滤到适当的数据集之前,我正在尝试使用每个数据集将包含的行列表创建向量。
有 654 个观察值,我打算将 354 个用于训练,200 个验证,100 个测试。 这是我使用的代码:

x <- 1:654
train_ind <- sample(x, 354)
rest <- x[-train_ind]
length(rest)
[1] 300
valid <- sample(rest, 200)
length(valid)
[1] 200
test <- rest[-valid]
length(test)
[1] 210

我不明白为什么 test 对象是 210!
我会认为,由于valid 的长度只有 200,如果我采用rest (300) 和负索引valid,那么我将只剩下 100。
感谢您对我做错的任何意见。
谢谢

【问题讨论】:

  • 在这种情况下,我强烈建议您在一个更小的示例上尝试您的流程。如果您使 x
  • 您从rest 采样,该向量不代表索引,而是x 的子集。如果您想对索引进行采样,您应该像这样sample(seq_along(rest), 200) 进行采样。
  • x &lt;- 1:654; i &lt;- sample(x); split(i, rep(1:3, c(354, 200, 100)))
  • 作为一个仅供参考,乔治梅森大学有一个关于使用 tidymodels 构建回归工作流的非常好的教程:gmudatamining.com/lesson-10-r-tutorial.html 您可以通过将代码复制并粘贴到 RStudio 中来跟随。 tidymodels 工作流程包括拆分数据集的功能。非常好。
  • @det rawr (Dason SteveM) 谢谢大家的精彩回答/cmets!

标签: r indexing subset


【解决方案1】:

您可以只打乱索引(无需替换的采样),然后获取前几个用于测试和其他用于训练。

indices <- sample(seq(20))
test <- indices[1:10]
train <- indices[11:20]

train
#>  [1] 10  8 12  1  7 20 13 18  4 11
test
#>  [1] 19  3 15  2  6  9 16 14 17  5

reprex package (v2.0.0) 于 2021-09-09 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2013-08-30
    相关资源
    最近更新 更多