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

时间:2017-07-05 02:59:36

标签: python boost machine-learning xgboost gradient-descent

我正在研究xgboost和渐变增强的新手。 在梯度树提升中,通过二阶近似计算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中使用的更多算法,例如分位数百分位草图。

感谢。

1 个答案:

答案 0 :(得分:3)

要跟踪每次迭代中的渐变更新,您需要在python中公开训练循环(而不是让它在C ++实现中内部执行),并提供自定义渐变和粗体实现。对于许多标准损失函数,例如平方损失,逻辑损失,这很简单并且在标准参考文献中不难发现。这是一个示例,展示了如何公开逻辑回归的训练循环。

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)
相关问题