我正在尝试从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对象的最后平均对数损失与我的计算结果相符。
但是,增加权重。仅更改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的计算,我怀疑会有任何损失指标。如何更改计算结果以匹配输出?
答案 0 :(得分:0)
部分解决:
使用加权对数损失函数得到的结果几乎相同。
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软件包在实际中如何正确使用权重感兴趣。