【问题标题】:Matching XGBoost eval_metric cross-validation calculations with weights将 XGBoost eval_metric 交叉验证计算与权重匹配
【发布时间】:2019-01-09 05:38:17
【问题描述】:

我正在尝试从 xgb.cv 重新创建评估指标的平均值和标准差的计算。我可以用一些代码来演示这个问题。

library(xgboost)
library(ModelMetrics)
library(rBayesianOptimization)

首先没有权重。

data(agaricus.train, package='xgboost')
dt <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
dt.folds <- KFold(as.matrix(agaricus.train$label), 
                              nfolds = 5, 
                              stratified = TRUE, 
                              seed = 23)
cv <- xgb.cv(data = dt, nrounds = 3, nthread = 2, folds = dt.folds, metrics = list("logloss","auc"),
             max_depth = 3, eta = 1, objective = "binary:logistic", prediction = TRUE)
test <- sapply(cv$folds, function(x){
  testSet <- unlist(cv$pred[x])
  test_ll <- logLoss(agaricus.train$label[x], testSet)
  test_ll
})

> cv$evaluation_log$test_logloss_mean
[1] 0.1615132 0.0655742 0.0262498

> mean(test)
[1] 0.02624984

正如预期的那样,来自 cv 对象的最后一个平均 logloss 与我的计算相符。

但是,添加权重。仅更改 dt 声明行。

dt <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label, weight = 1:length(agaricus.train$label))

> cv$evaluation_log$test_logloss_mean
[1] 0.1372536 0.0509958 0.0219024
> mean(test)
[1] 0.02066699

现在它们不匹配了。 xgb.cv 函数在计算损失指标方面有何不同?添加权重也会改变 auc 的计算,我怀疑任何损失指标。如何更改我的计算以匹配输出?

【问题讨论】:

    标签: r cross-validation xgboost loss-function


    【解决方案1】:

    部分解决:

    使用加权对数损失函数得到几乎相同的结果。

    wLogLoss=function(actual, predicted, weights)
    {
      result=-1/sum(weights)*(sum(weights*(actual*log(predicted)+(1-actual)*log(1-predicted))))
      return(result)
    }
    
    calc <- sapply(cv$folds, function(x){
      testSet <- unlist(cv$pred[x])
      test_ll <- wLogLoss(agaricus.train$label[x], testSet, ww[x])
      test_ll
    })
    
    > mean(calc)
    [1] 0.02190241
    > cv$evaluation_log$test_logloss_mean[3]
    [1] 0.0219024
    > var(calc)*4/5
    [1] 0.00001508648
    > cv$evaluation_log$test_logloss_std[3]^2
    [1] 0.00001508551
    

    方差的微小差异仍然存在。我仍然想知道 xgboost 包在现实中是如何使用权重的。

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 2019-11-16
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      • 2016-03-29
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多