gpt4 book ai didi

python - 如何获取或查看xgboost的梯度统计值?

转载 作者:行者123 更新时间:2023-11-30 08:54:05 25 4
gpt4 key购买 nike

我正在研究xgboost,新手进行梯度 boost 。在梯度树 boost 中,损失函数是通过二阶近似计算gi、hi来导出的。您可以在https://xgboost.readthedocs.io/en/latest/model.html#the-structure-score上看到它。给定一个数据集,我如何查看值 gi, hi 例如 g1, h1, g2, h2,..?

我在training.py和sklean.py中看到了_train_internal和几个函数。但我没有找到。通过了解它是如何有效计算和获得的,可以应用 xgboost 中使用的进一步算法,例如分位数百分位数草图。

谢谢。

最佳答案

为了跟踪每次迭代中的梯度更新,您需要在 python 中公开训练循环(而不是让它在 C++ 实现中内部执行),并提供自定义梯度和 hessian 实现。对于许多标准损失函数,例如平方损失、逻辑损失,这非常简单,并且在标准引用文献中并不难找到。下面的示例展示了如何公开逻辑回归的训练循环。

import numpy as np
import xgboost as xgb
from sklearn.datasets import make_classification
from sklearn.metrics import confusion_matrix


def sigmoid(x):
return 1 / (1 + np.exp(-x))


def logregobj(preds, dtrain):
"""log likelihood loss"""
labels = dtrain.get_label()
preds = sigmoid(preds)
grad = preds - labels
hess = preds * (1.0-preds)
return grad, hess


# Build a toy dataset.
X, Y = make_classification(n_samples=1000, n_features=5, n_redundant=0, n_informative=3,
random_state=1, n_clusters_per_class=1)

# Instantiate a Booster object to do the heavy lifting
dtrain = xgb.DMatrix(X, label=Y)
params = {'max_depth': 2, 'eta': 1, 'silent': 1}
num_round = 2
model = xgb.Booster(params, [dtrain])

# Run 10 boosting iterations
# g and h can be monitored for gradient statistics
for _ in range(10):
pred = model.predict(dtrain)
g, h = logregobj(pred, dtrain)
model.boost(dtrain, g, h)

# Evaluate predictions
yhat = model.predict(dtrain)
yhat = 1.0 / (1.0 + np.exp(-yhat))
yhat_labels = np.round(yhat)
confusion_matrix(Y, yhat_labels)

关于python - 如何获取或查看xgboost的梯度统计值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44916391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com