r - 将 XGBoost eval_metric 交叉验证计算与权重匹配
问题描述
我正在尝试从 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 的计算,我怀疑任何损失指标。如何更改我的计算以匹配输出?
解决方案
部分解决:
使用加权对数损失函数会产生几乎相同的结果。
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 包在现实中是如何使用权重的。
推荐阅读
- react-native - 为什么 Youtube 视频没有在反应原生移动应用程序的 Webview 中显示?
- java - 使用 QueryDSL 和 PostgreSQL 数据库与 GroupBy 汇总
- odoo - 如何根据 Odoo 11 中的状态隐藏编辑按钮
- variables - 如何在 Informix 中检索活动 SAVEPOINT 的名称
- reactjs - 错误:在使用 react-redux 时,Provider 的钩子调用无效
- tensorflow - 对象检测:锚框的纵横比和比例
- c# - 命名空间“Microsoft”中不存在类型或命名空间名称“ServiceBus”?
- python - 我将 python 从 3.5 更新到 3.7,现在找不到 manage.py
- python - Pyinstaller 依赖项的许可证
- mysql - 具有事务正确语法和 in 参数的 MySQL SP