在 R 中使用 Xgboost 进行训练和预测

Training and predicting with Xgboost in R

我有一个问题与使用包 and the function xgb.cv in 时模型的交叉验证、调整、训练和预测有关。

特别是,我重新使用并改编了来自互联网的代码,以便在 class 中使用 xgb.cv 搜索参数 space(调整)中的最佳参数]化问题。

在这里您可以找到用于执行此任务的代码:

# *****************************
# *******  TUNING  ************
# *****************************
start_time <- Sys.time()

best_param <- list()
best_seednumber <- 1234
best_acc <- 0
best_acc_index <- 0

set.seed(1234)
# In reality, might need 100 or 200 iters
for (iter in 1:200) {
  param <- list(objective = "binary:logistic",
                eval_metric = c("error"),      # rmse is used for regression
                max_depth = sample(6:10, 1),
                eta = runif(1, .01, .1),   # Learning rate, default: 0.3
                subsample = runif(1, .6, .9),
                colsample_bytree = runif(1, .5, .8), 
                min_child_weight = sample(5:10, 1), # These two are important
                max_delta_step = sample(5:10, 1) # Can help to focus error
                # into a small range.
  )
  cv.nround <-  1000
  cv.nfold <-  10 # 10-fold cross-validation
  seed.number  <-  sample.int(10000, 1) # set seed for the cv
  set.seed(seed.number)
  mdcv <- xgb.cv(data = dtrain, params = param,  
                 nfold = cv.nfold, nrounds = cv.nround,
                 verbose = F, early_stopping_rounds = 20, maximize = FALSE,
                 stratified = T)

  max_acc_index  <-  mdcv$best_iteration
  max_acc <- 1 - mdcv$evaluation_log[mdcv$best_iteration]$test_error_mean
  print(i)
  print(max_acc)
  print(mdcv$evaluation_log[mdcv$best_iteration])

  if (max_acc > best_acc) {
    best_acc <- max_acc
    best_acc_index <- max_acc_index
    best_seednumber <- seed.number
    best_param <- param
  }
}

end_time <- Sys.time()

print(end_time - start_time)    # Duration -> 1.54796 hours

大约 1.5 小时后,此代码返回交叉验证设置中性能最佳的参数。我还能够重现循环中获得的精度和最佳参数。

# Reproduce what found in loop
set.seed(best_seednumber)
best_model_cv <- xgb.cv(data=dtrain, params=best_param, nfold=cv.nfold, nrounds=cv.nround,
                     verbose = T, early_stopping_rounds = 20, maximize = F, stratified = T,
                     prediction=TRUE)
print(best_model_cv)
best_model_cv$params

现在我想使用这个 "best parameters" 来使用 xgboostxgb.train 训练我的完整训练集,并在测试数据集上制作

best_model <- xgboost(params = best_param, data=dtrain,
                      seed=best_seednumber, nrounds=10)

在这一点上,我不确定这个训练代码是否正确以及我应该在 xgboost 中使用哪些参数。问题是,当我 运行 这次训练并在测试数据集中做出预测时,我的 classifier 基本上 class 在一个 class 中将几乎所有新实例化](这是不可能的,因为我还使用了其他模型,这些模型原则上可以提供准确的 class化率)。

所以,总而言之,我的问题是:

  1. 如何在包的训练函数中使用交叉验证阶段得到的训练参数?

  2. 由于我是这个领域的新手,您能否确认我应该预处理我的测试数据集,因为我已经预处理了我的训练数据集(转换、特征工程等) )?

我知道我的代码不可重现,但我对函数的使用更感兴趣,所以我想在这个阶段这并不重要。

谢谢。

最后是我的测试数据集定义错误导致了这个问题。我定义训练模型参数的方式没有错