38

I've been exploring the xgboost package in R and went through several demos as well as tutorials but this still confuses me: after using xgb.cv to do cross validation, how does the optimal parameters get passed to xgb.train? Or should I calculate the ideal parameters (such as nround, max.depth) based on the output of xgb.cv?

param <- list("objective" = "multi:softprob",
              "eval_metric" = "mlogloss",
              "num_class" = 12)
cv.nround <- 11
cv.nfold <- 5
mdcv <-xgb.cv(data=dtrain,params = param,nthread=6,nfold = cv.nfold,nrounds = cv.nround,verbose = T)

md <-xgb.train(data=dtrain,params = param,nround = 80,watchlist = list(train=dtrain,test=dtest),nthread=6)
4

3 回答 3

87

看来你误会xgb.cv了,它不是参数搜索功能。它只进行 k 折交叉验证,仅此而已。

在您的代码中,它不会更改param.

要在 R 的 XGBoost 中找到最佳参数,有一些方法。这是2种方法,

(1) 使用mlr包, http: //mlr-org.github.io/mlr-tutorial/release/html/

在 Kaggle 的 Prudential 挑战中有一个 XGBoost + mlr示例代码,

但该代码用于回归,而不是分类。据我所知,包中还没有mlogloss度量标准mlr,因此您必须自己从头开始编写 mlogloss 测量代码。CMIIW。

(2) 第二种方法,通过手动设置参数然后重复,例如,

param <- list(objective = "multi:softprob",
      eval_metric = "mlogloss",
      num_class = 12,
      max_depth = 8,
      eta = 0.05,
      gamma = 0.01, 
      subsample = 0.9,
      colsample_bytree = 0.8, 
      min_child_weight = 4,
      max_delta_step = 1
      )
cv.nround = 1000
cv.nfold = 5
mdcv <- xgb.cv(data=dtrain, params = param, nthread=6, 
                nfold=cv.nfold, nrounds=cv.nround,
                verbose = T)

然后,你会找到最好的(最小的)mlogloss,

min_logloss = min(mdcv[, test.mlogloss.mean])
min_logloss_index = which.min(mdcv[, test.mlogloss.mean])

min_logloss是 mlogloss 的最小值,而min_logloss_index是索引(round)。

您必须多次重复上述过程,每次手动更改参数(mlr为您重复)。直到最后你得到最好的全局最小值min_logloss

注意:您可以在 100 或 200 次迭代的循环中执行此操作,其中每次迭代您随机设置参数值。这样,您必须将最好的保存[parameters_list, min_logloss, min_logloss_index]在变量或文件中。

注意:最好设置随机种子以set.seed()获得可重复的结果。不同的随机种子产生不同的结果。因此,您必须保存[parameters_list, min_logloss, min_logloss_index, seednumber]在变量或文件中。

说最后你在 3 次迭代/重复中得到 3 个结果:

min_logloss = 2.1457, min_logloss_index = 840
min_logloss = 2.2293, min_logloss_index = 920
min_logloss = 1.9745, min_logloss_index = 780

然后您必须使用第三个参数(它的全局最小值min_logloss1.9745)。你最好的指数(nrounds)是780

获得最佳参数后,在训练中使用它,

# best_param is global best param with minimum min_logloss
# best_min_logloss_index is the global minimum logloss index
nround = 780
md <- xgb.train(data=dtrain, params=best_param, nrounds=nround, nthread=6)

我认为您不需要watchlist进行培训,因为您已经完成了交叉验证。但如果你还想用watchlist,也没关系。

更好的是,您可以使用提前停止xgb.cv

mdcv <- xgb.cv(data=dtrain, params=param, nthread=6, 
                nfold=cv.nfold, nrounds=cv.nround,
                verbose = T, early.stop.round=8, maximize=FALSE)

使用此代码,当mlogloss值没有在 8 步内减少时,xgb.cv将停止。您可以节省时间。您必须设置maximizeFALSE,因为您期望最小 mlogloss。

这是一个示例代码,具有 100 次迭代循环和随机选择的参数。

best_param = list()
best_seednumber = 1234
best_logloss = Inf
best_logloss_index = 0

for (iter in 1:100) {
    param <- list(objective = "multi:softprob",
          eval_metric = "mlogloss",
          num_class = 12,
          max_depth = sample(6:10, 1),
          eta = runif(1, .01, .3),
          gamma = runif(1, 0.0, 0.2), 
          subsample = runif(1, .6, .9),
          colsample_bytree = runif(1, .5, .8), 
          min_child_weight = sample(1:40, 1),
          max_delta_step = sample(1:10, 1)
          )
    cv.nround = 1000
    cv.nfold = 5
    seed.number = sample.int(10000, 1)[[1]]
    set.seed(seed.number)
    mdcv <- xgb.cv(data=dtrain, params = param, nthread=6, 
                    nfold=cv.nfold, nrounds=cv.nround,
                    verbose = T, early.stop.round=8, maximize=FALSE)

    min_logloss = min(mdcv[, test.mlogloss.mean])
    min_logloss_index = which.min(mdcv[, test.mlogloss.mean])

    if (min_logloss < best_logloss) {
        best_logloss = min_logloss
        best_logloss_index = min_logloss_index
        best_seednumber = seed.number
        best_param = param
    }
}

nround = best_logloss_index
set.seed(best_seednumber)
md <- xgb.train(data=dtrain, params=best_param, nrounds=nround, nthread=6)

使用此代码,您可以运行 100 次交叉验证,每次都使用随机参数。然后你得到最好的参数集,即在迭代中具有 minimum min_logloss

增加 的值,early.stop.round以防您发现它太小(过早停止)。您还需要根据您的数据特征更改随机参数值的限制。

而且,对于 100 或 200 次迭代,我认为您想更改verbose为 FALSE。

旁注:这是随机方法的示例,您可以通过贝叶斯优化对其进行调整以获得更好的方法。如果你有 XGBoost 的 Python 版本,有一个很好的 XGBoost 超参数脚本,https://github.com/mpearmain/BayesBoost可以使用贝叶斯优化搜索最佳参数集。

编辑:我想添加第三种手动方法,由 Kaggle 大师“Davut Polat”在Kaggle 论坛中发布。

编辑:如果您了解 Python 和 sklearn,您还可以将GridSearchCV与 xgboost.XGBClassifier 或 xgboost.XGBRegressor 一起使用

于 2016-01-30T11:48:47.317 回答
8

这是一个很好的问题,来自筒仓的很好的回复,有很多细节!xgboost我发现这对喜欢我的新人很有帮助。谢谢你。随机化并与边界进行比较的方法非常鼓舞人心。好用,好知道。现在在 2018 年需要进行一些细微的修改,例如early.stop.round应该是early_stopping_rounds. 输出mdcv的组织方式略有不同:

  min_rmse_index  <-  mdcv$best_iteration
  min_rmse <-  mdcv$evaluation_log[min_rmse_index]$test_rmse_mean

并且取决于应用程序(线性、逻辑等),objectiveeval_metric相应调整 和 参数。

为了方便运行回归的任何人,这里是稍微调整的代码版本(大部分与上面相同)。

library(xgboost)
# Matrix for xgb: dtrain and dtest, "label" is the dependent variable
dtrain <- xgb.DMatrix(X_train, label = Y_train)
dtest <- xgb.DMatrix(X_test, label = Y_test)

best_param <- list()
best_seednumber <- 1234
best_rmse <- Inf
best_rmse_index <- 0

set.seed(123)
for (iter in 1:100) {
  param <- list(objective = "reg:linear",
                eval_metric = "rmse",
                max_depth = sample(6:10, 1),
                eta = runif(1, .01, .3), # Learning rate, default: 0.3
                subsample = runif(1, .6, .9),
                colsample_bytree = runif(1, .5, .8), 
                min_child_weight = sample(1:40, 1),
                max_delta_step = sample(1:10, 1)
  )
  cv.nround <-  1000
  cv.nfold <-  5 # 5-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 = 8, maximize = FALSE)

  min_rmse_index  <-  mdcv$best_iteration
  min_rmse <-  mdcv$evaluation_log[min_rmse_index]$test_rmse_mean

  if (min_rmse < best_rmse) {
    best_rmse <- min_rmse
    best_rmse_index <- min_rmse_index
    best_seednumber <- seed.number
    best_param <- param
  }
}

# The best index (min_rmse_index) is the best "nround" in the model
nround = best_rmse_index
set.seed(best_seednumber)
xg_mod <- xgboost(data = dtest, params = best_param, nround = nround, verbose = F)

# Check error in testing data
yhat_xg <- predict(xg_mod, dtest)
(MSE_xgb <- mean((yhat_xg - Y_test)^2))
于 2018-07-08T10:10:13.163 回答
4

我发现 silo 的回答很有帮助。除了他的随机研究方法外,您可能还想使用贝叶斯优化来促进超参数搜索的过程,例如rBayesianOptimization 库。以下是我使用 rbayesianoptimization 库的代码。

cv_folds <- KFold(dataFTR$isPreIctalTrain, nfolds = 5, stratified = FALSE, seed = seedNum)
xgb_cv_bayes <- function(nround,max.depth, min_child_weight, subsample,eta,gamma,colsample_bytree,max_delta_step) {
param<-list(booster = "gbtree",
            max_depth = max.depth,
            min_child_weight = min_child_weight,
            eta=eta,gamma=gamma,
            subsample = subsample, colsample_bytree = colsample_bytree,
            max_delta_step=max_delta_step,
            lambda = 1, alpha = 0,
            objective = "binary:logistic",
            eval_metric = "auc")
cv <- xgb.cv(params = param, data = dtrain, folds = cv_folds,nrounds = 1000,early_stopping_rounds = 10, maximize = TRUE, verbose = verbose)

list(Score = cv$evaluation_log$test_auc_mean[cv$best_iteration],
     Pred=cv$best_iteration)
# we don't need cross-validation prediction and we need the number of rounds.
# a workaround is to pass the number of rounds(best_iteration) to the Pred, which is a default parameter in the rbayesianoptimization library.
}
OPT_Res <- BayesianOptimization(xgb_cv_bayes,
                              bounds = list(max.depth =c(3L, 10L),min_child_weight = c(1L, 40L),
                                            subsample = c(0.6, 0.9),
                                            eta=c(0.01,0.3),gamma = c(0.0, 0.2),
                                            colsample_bytree=c(0.5,0.8),max_delta_step=c(1L,10L)),
                              init_grid_dt = NULL, init_points = 10, n_iter = 10,
                              acq = "ucb", kappa = 2.576, eps = 0.0,
                              verbose = verbose)
best_param <- list(
booster = "gbtree",
eval.metric = "auc",
objective = "binary:logistic",
max_depth = OPT_Res$Best_Par["max.depth"],
eta = OPT_Res$Best_Par["eta"],
gamma = OPT_Res$Best_Par["gamma"],
subsample = OPT_Res$Best_Par["subsample"],
colsample_bytree = OPT_Res$Best_Par["colsample_bytree"],
min_child_weight = OPT_Res$Best_Par["min_child_weight"],
max_delta_step = OPT_Res$Best_Par["max_delta_step"])
# number of rounds should be tuned using CV
#https://www.hackerearth.com/practice/machine-learning/machine-learning-algorithms/beginners-tutorial-on-xgboost-parameter-tuning-r/tutorial/
# However, nrounds can not be directly derivied from the bayesianoptimization function
# Here, OPT_Res$Pred, which was supposed to be used for cross-validation, is used to record the number of rounds
nrounds=OPT_Res$Pred[[which.max(OPT_Res$History$Value)]]
xgb_model <- xgb.train (params = best_param, data = dtrain, nrounds = nrounds)
于 2019-02-16T18:48:59.797 回答