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

时间:2018-02-02 20:07:52

标签: r machine-learning r-caret training-data

我有一个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

要做到这一点,我需要告诉Caret,在优化之前,它应该对数据进行子集化,但是为了最终拟合,请使用所有数据。

我可以通过以下方式实现:(1)对数据进行子集化; (2)做通常的火车阶段; (3)停止最终适合(不需要); (4)建立“最佳”组合(这是在火车的输出中); (5)在没有参数优化的情况下运行完整的500k列车。

这有点凌乱,我不知道如何停止对最终模型进行插入训练,这是我永远不会使用的。

1 个答案:

答案 0 :(得分:2)

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

以下是使用mlbench库中的Sonar数据集的示例:

library(caret)
library(mlbench)
data(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