R 插入符号估计子集上的参数拟合到完整数据



我有一个包含 550k 项的数据集,我将其拆分为 500k 用于训练,50k 用于测试。在训练阶段,有必要建立每种算法参数值的"最佳"组合。与其为此使用整个 500k,我很乐意使用一个子集,但是在训练最终模型时,使用"最佳"组合,我想使用完整的 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

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

我可以通过以下方式做到这一点:(1(子集数据;(2(做通常的火车阶段;(3(停止最终配合(不需要(;(4(建立"最佳"组合(这是在火车的输出中(;(5(在全500K上运行列车,没有参数优化。

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

这可以通过指定 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)

如果您对不同的抽样方法感兴趣,请发布详细信息。这仅供说明之用。

对于测试,我们将使用不在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

最新更新