r 插入符估计适合完整数据的子集的参数

r caret estimate parameters on a subset fit to full data

我有一个包含 550k 个项目的数据集,我将其中 500k 用于训练,50k 用于测试。在训练阶段,需要建立每个算法参数值的 'best' 组合。与其为此使用整个 500k,我很乐意使用一个子集,但是在训练最终模型时,使用 'best' 组合,我想使用完整的 500k。在伪代码中,任务如下所示:

subset the 500k training data to 50k
for each combination of model parameters (3, 6, or 9)
  for each repeat (3)
    for each fold (10)
       fit the model on 50k training data using the 9 folds
       evaluate performance on the remaining fold
establish the best combination of parameters
fit to all 500k using best combination of parameters

为此,我需要告诉 caret 在优化之前它应该对数据进行子集化,但为了最终拟合,使用所有数据。

我可以通过以下方式做到这一点:(1)对数据进行子集化; (2) 做通常的火车阶段; (3) 停止最终拟合(不需要); (4) 建立'best'组合(这在train的输出中); (5) 运行 在没有参数优化的情况下进行完整的 500k 训练。

这有点不整洁,我不知道如何停止插入符号训练最终模型,我永远不会使用它。

这可以通过为 trainControl 指定 index、indexOut 和 indexFinal 参数来实现。

下面是一个使用来自 mlbench 库的 Sonar 数据集的示例:

library(caret)
library(mlbench)
data(Sonar)

假设我们每次要绘制一半的 Sonar 数据集进行训练,并重复 10 次:

train_inds <- replicate(10, sample(1:nrow(Sonar), size = nrow(Sonar)/2), simplify = FALSE)

如果您对不同的采样方法感兴趣,请 post 详细信息。这仅供参考。

为了测试,我们将使用不在 train_inds:

中的随机 10 行
test_inds <- lapply(train_inds, function(x){
  inds <- setdiff(1:nrow(Sonar), x)
  return(sample(inds, size = 10))
}
)

现在只需在 trainControl 中指定 test_inds 和 train_inds:

ctrl <-  trainControl(
    method = "boot",
    number = 10,
    classProbs = T,
    savePredictions = "final",
    index = train_inds,
    indexOut = test_inds,
    indexFinal = 1:nrow(Sonar),
    summaryFunction = twoClassSummary
  )

如果您不希望在所有行上拟合最终模型,您也可以指定 indexFinal。

适合:

model <- train(
    Class ~ .,
    data = Sonar,
    method = "rf",
    trControl = ctrl,
    metric = "ROC"
  )
model
#output
Random Forest 

208 samples, 208 used for final model
 60 predictor
  2 classes: 'M', 'R' 

No pre-processing
Resampling: Bootstrapped (10 reps) 
Summary of sample sizes: 104, 104, 104, 104, 104, 104, ... 
Resampling results across tuning parameters:

  mtry  ROC        Sens    Spec     
   2    0.9104167  0.7750  0.8250000
  31    0.9125000  0.7875  0.7916667
  60    0.9083333  0.7875  0.8166667