【问题标题】:How to partition train/test data set based on the centers?如何根据中心划分训练/测试数据集?
【发布时间】:2018-12-19 19:06:42
【问题描述】:

我有一个数据集,其中包含 3 个预测变量 (P1-P3) 和 1 个响应变量作为结果 (Response)。数据来自 5 个中心(200 个 ID)。我将整个数据分为训练(70%)和测试(30%)。

样本数据:

ID  Centers   P1    P2  P3  Response
ID1 Center1   12    1   1   Class1
ID2 Center2   73    1   3   Class2
ID3 Center3   56    2   1   Class1
ID4 Center1   44    1   3   Class2
ID5 Center4   33    1   1   Class1
ID6 Center5   26    1   1   Class2
ID7 Center2   61    1   1   Class1
ID8 Center3   44    1   3   Class2
ID9 Center5   45    1   1   Class1

我想要一个考虑结果变量中心和类别的训练和测试数据集的分区,我可以写的是

library(caret)
set.seed(123)
train.index <- createDataPartition(data$Response, p = .7, list = FALSE)
train <- data[ train.index,]
test  <- data[-train.index,]

如何编写代码以使分区从所有中心选择数据?

【问题讨论】:

  • 请务必明确提及相关库——这里,createDataPartition 不是base R,而是来自caret,应该在您的问题中明确提及。

标签: r machine-learning partitioning r-caret


【解决方案1】:

也许这不是完美的答案,但我遇到了类似的问题,我使用dplyr::group_bydplyr::sanple_n 管理它。我需要按组进行平衡训练和测试,以及一个 test 数据集,它是我的数据的子集,包含不在 train 数据集中的个人。

例如,使用著名的mtcars 数据集:

library(dplyr)
mtcars %>%              # in your case your data
    group_by(cyl) %>%   # in your case Centers
    sample_n(2)         # here the numbers of the sample for each group

这样就变成了:

train <- data %>% group_by(Centers) %>% sample_n(28)

这意味着如果您有 200 行和 5 个中心,并且每个中心的个体数量相同(我们称之为平衡),那么每个组都有 200/5 = 40,所以 sample_n 没有重复次数最多为 40。

在每组平衡数据的情况下,如果我的数学没有错,您可以设置为 28 (200/100*70/5),以获得 70% 的覆盖率,为每组平衡。

如果组不平衡,无需重复,您可以将参数放到最小的组。

另一方面,您必须设置重复。

要设置测试,如果你想让那些不在训练中的人,你可以这样做:

test <- data %>% filter(!ID %in% train%ID)

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 2020-08-11
    • 2015-03-23
    • 2019-05-01
    • 2017-02-20
    • 2019-12-09
    • 2020-09-12
    • 2019-10-15
    相关资源
    最近更新 更多