如何对数据集进行分层抽样,使用 Caret 进行统计分析并在 r 中重复?

How to stratify sample a data set, conduct statistical analysis with Caret and repeat in r?

我有一个数据集,我想对样本进行分层,使用 caret 包创建统计模型,然后生成预测。

我发现的问题是,在分层数据集的不同迭代中,我得到明显不同的结果(这可能部分是由于数据样本相对较小 M=1000)。

我希望能够做到的是:

  1. 生成分层数据样本
  2. 创建机器学习模型
  3. 重复 1000 次并取平均模型输出

我希望通过对分层数据集的变化重复这些步骤,我能够避免由于较小的数据样本而产生的预测的细微变化。

例如,在 r 中可能看起来像这样;

Original.Dataset = data.frame(A)

Stratified.Dataset = stratified(Original.Dataset, group = x)

Model = train(Stratified.Dataset.....other model inputs)

Repeat process with new stratified data set based on the original data and average out.

提前感谢您提供的任何帮助或可能有用的打包建议。是否可以在插入符号中对样本进行分层或在插入符号中进行模拟?

首先,欢迎来到 SO。

很难理解你到底想知道什么,你的问题太宽泛了。

如果您需要统计信息,我建议您在 Cross Validated. 中提出更明确的问题 面向对统计、机器学习、数据分析、数据挖掘和数据可视化感兴趣的人的问答。

The problem I am finding is that in different iterations of the stratified data set I get significantly different results (this may be in part due to the relatively small data sample M=1000).

我假设您指的是模型的不同迭代。这取决于您的不同群体的规模。例如。如果您尝试将由 1000 个样本组成的数据集分成 10 个样本的组,您的模型很可能不稳定,因此在每次迭代中给出不同的结果。这也可能是由于您的模型取决于一些随机性,并且 较小 您的数据(以及更多组)将 较大 变化。 See here or here 有关交叉验证、稳定性和 bootstrap 聚合的更多信息。

  1. Generate the stratified data sample

如何生成它:dplyr 包在根据不同变量对数据进行分组方面非常出色。您可能还想使用 base 包中的 split 函数。 See here for more information. You could also use the in-built methods found in the caret package, found here.

如何知道如何拆分它:这在很大程度上取决于您想要回答的问题,很可能您想平衡一些变量,例如性别和年龄来创建预测疾病的模型。 See here for more info.

例如有重复的观察,并且您想创建具有不同重复组合的唯一子集及其独特的测量值,您将不得不使用其他方法。如果重复有一个共同的标识符,这里 sample_names。您可以对 select 所有样本执行类似的操作,但使用不同的重复组合:

tg <- data.frame(sample_names = rep(1:5,each=2))
set.seed(10)
tg$values<-rnorm(10)

partition <- lapply(1:100, function(z) {
  set.seed(z)
  sapply(unique(tg$sample_names), function(x) {
    which(x == tg$sample_names)[sample(1:2, 1)]
  })
})

#the first partition of your data to train a model.
tg[partition[[1]],]
  1. Create the machine learning model

如果你想用caret,你可以去caret webpage. And see all the available models. Depending on your research question and/or data you would like to use different types of models. Therefore, I would recommend you to take some online machine learning courses, for instance the Stanford University course given by Andrew Ng(我自己拿过),更熟悉你熟悉的不同专业algorithms.If使用算法,只需搜索可用的模型。

  1. Repeat 1000 times & take the average model output

您可以使用不同的种子(参见 set.seed)和不同的训练方法重复您的模型 1000 次,例如交叉验证或 bootstrap 聚合。 caret包中有很多不同的训练参数:

The function trainControl generates parameters that further control how models are created, with possible values:

method: The resampling method: "boot", "cv", "LOOCV", "LGOCV", "repeatedcv", "timeslice", "none" and "oob"

有关方法的更多信息,see here