XGB-16:自定义目标和评估指标

概述

XGBoost被设计为一个可扩展的库。通过提供自定义的训练目标函数和相应的性能监控指标,可以扩展它。本文介绍了如何为XGBoost实现自定义的逐元评估指标和目标。

注意:

排序不能自定义

在接下来的两个部分中,将逐步介绍如何实现平方对数误差(Squared Log Error,SLE)目标函数

1 2 [ log ⁡ ( p r e d + 1 ) − log ⁡ ( l a b e l + 1 ) ] 2 \frac{1}{2}[\log(pred + 1) - \log(label + 1)]^2 21[log(pred+1)log(label+1)]2

以及它的默认评估指标均方根对数误差(Root Mean Squared Log Error,RMSLE

1 N [ log ⁡ ( p r e d + 1 ) − log ⁡ ( l a b e l + 1 ) ] 2 \sqrt{\frac{1}{N}[\log(pred + 1) - \log(label + 1)]^2} N1[log(pred+1)log(label+1)]2

定制目标函数

尽管XGBoost本身已经原生支持这些功能,但为了演示的目的,使用它来比较自己实现的结果和XGBoost内部实现的结果。完成本教程后,应该能够为快速实验提供自己的函数。最后,将提供一些关于非恒等链接函数的注释,以及在scikit-learn接口中使用自定义度量和目标的示例。

如果计算所述目标函数的梯度:

g = ∂ o b j e c t i v e ∂ p r e d = log ⁡ ( p r e d + 1 ) − log ⁡ ( l a b e l + 1 ) p r e d + 1 g = \frac{\partial{objective}}{\partial{pred}} = \frac{\log(pred + 1) - \log(label + 1)}{pred + 1} g=predobjective=pred+1log(pred+1)log(label+1)

以及 hessian(目标的二阶导数):

h = ∂ 2 o b j e c t i v e ∂ p r e d = − log ⁡ ( p r e d + 1 ) + log ⁡ ( l a b e l + 1 ) + 1 ( p r e d + 1 ) 2 h = \frac{\partial^2{objective}}{\partial{pred}} = \frac{ - \log(pred + 1) + \log(label + 1) + 1}{(pred + 1)^2} h=pred2objective=(pred+1)2log(pred+1)+log(label+1)+1

在模型训练过程中,目标函数起着重要的作用:基于模型预测和观察到的数据标签(或目标),提供梯度信息,包括一阶和二阶梯度。因此,有效的目标函数应接受两个输入,即预测值和标签。对于实现SLE,定义:

import numpy as np
import xgboost as xgb
from typing import Tuple


def gradient(predt: np.ndarray, dtrain: xgb.DMatrix) -> np.ndarray:
    '''Compute the gradient squared log error.'''
    y = dtrain.get_label()
    return (np.log1p(predt)-np.log1p(y)) / (predt+1)

def hessian(predt: np.ndarray, dtrain: xgb.DMatrix) -> np.ndarray:
    '''Compute the hessian for squared log error.'''
    y = dtrain.get_label()
    return ((-np.log1p(predt)+np.log1p(y)+1) /
            np.power(predt+1, 2))

def squared_log(predt: np.ndarray,
                dtrain: xgb.DMatrix) -> Tuple[np.ndarray, np.ndarray]:
    '''Squared Log Error objective. A simplified version for RMSLE used as
    objective function.
    '''
    predt[predt < -1] = -1 + 1e-6
    grad = gradient(predt, dtrain)
    hess = hessian(predt, dtrain)
    return grad, hess

在上面的代码片段中,squared_log是想要的目标函数。它接受一个numpy数组predt作为模型预测值,以及用于获取所需信息的训练DMatrix,包括标签和权重(此处未使用)。然后,在训练过程中,通过将其作为参数传递给xgb.train,将此目标函数用作XGBoost的回调函数:

xgb.train({'tree_method': 'hist', 'seed': 1994},   # any other tree method is fine.
           dtrain=dtrain,
           num_boost_round=10,
           obj=squared_log)

注意,在定义目标函数时,从预测值中减去标签或从标签中减去预测值,这是很重要的。如果发现训练错误上升而不是下降,这可能是原因。

定制度量函数

因此,在拥有自定义目标函数之后,还需要一个相应的度量标准来监控模型的性能。如上所述,SLE 的默认度量标准是 RMSLE。同样,定义另一个类似的回调函数作为新的度量标准:

def rmsle(predt: np.ndarray, dtrain: xgb.DMatrix) -> Tuple[str, float]:
    ''' Root mean squared log error metric.'''
    y = dtrain.get_label()
    predt[predt < -1] = -1 + 1e-6
    elements = np.power(np.log1p(y) - np.log1p(predt), 2)
    return 'PyRMSLE', float(np.sqrt(np.sum(elements) / len(y)))

与目标函数类似,度量也接受 predtdtrain 作为输入,但返回度量本身的名称和一个浮点值作为结果。将其作为 custom_metric 参数传递给 XGBoost:

xgb.train({'tree_method': 'hist', 'seed': 1994,
           'disable_default_eval_metric': 1},
          dtrain=dtrain,
          num_boost_round=10,
          obj=squared_log,
          custom_metric=rmsle,
          evals=[(dtrain, 'dtrain'), (dtest, 'dtest')],
          evals_result=results)

能够看到 XGBoost 打印如下内容:

[0] dtrain-PyRMSLE:1.37153  dtest-PyRMSLE:1.31487
[1] dtrain-PyRMSLE:1.26619  dtest-PyRMSLE:1.20899
[2] dtrain-PyRMSLE:1.17508  dtest-PyRMSLE:1.11629
[3] dtrain-PyRMSLE:1.09836  dtest-PyRMSLE:1.03871
[4] dtrain-PyRMSLE:1.03557  dtest-PyRMSLE:0.977186
[5] dtrain-PyRMSLE:0.985783 dtest-PyRMSLE:0.93057
...

注意,参数 disable_default_eval_metric 用于禁用 XGBoost 中的默认度量。

完整可复制的源代码参阅定义自定义回归目标和度量的演示

转换链接函数

在使用内置目标函数时,原始预测值会根据目标函数进行转换。当提供自定义目标函数时,XGBoost 不知道其链接函数,因此用户需要对目标和自定义评估度量进行转换。对于具有身份链接的目标,如平方误差squared error,这很简单,但对于其他链接函数,如对数链接或反链接,差异很大。

在 Python 包中,可以通过 predict 函数中的 output_margin 参数来控制预测的行为。当使用 custom_metric 参数而没有自定义目标函数时,度量函数将接收经过转换的预测,因为目标是由 XGBoost 定义的。然而,当同时提供自定义目标和度量时,目标和自定义度量都将接收原始预测。以下示例比较了多类分类模型中两种不同的行为。首先,我们定义了两个不同的 Python 度量函数,实现了相同的底层度量以进行比较。其中 merror_with_transform 在同时使用自定义目标时使用,否则会使用更简单的 merror,因为 XGBoost 可以自行执行转换。

import xgboost as xgb
import numpy as np


def merror_with_transform(predt: np.ndarray, dtrain: xgb.DMatrix):
    """Used when custom objective is supplied."""
    y = dtrain.get_label()
    n_classes = predt.size // y.shape[0]
    # Like custom objective, the predt is untransformed leaf weight when custom objective
    # is provided.

    # With the use of `custom_metric` parameter in train function, custom metric receives
    # raw input only when custom objective is also being used.  Otherwise custom metric
    # will receive transformed prediction.
    assert predt.shape == (d_train.num_row(), n_classes)
    out = np.zeros(dtrain.num_row())
    for r in range(predt.shape[0]):
        i = np.argmax(predt[r])
        out[r] = i

    assert y.shape == out.shape

    errors = np.zeros(dtrain.num_row())
    errors[y != out] = 1.0
    return 'PyMError', np.sum(errors) / dtrain.num_row()

仅当想要使用自定义目标并且 XGBoost 不知道如何转换预测时才需要上述函数。多类误差函数的正常实现是:

def merror(predt: np.ndarray, dtrain: xgb.DMatrix):
    """Used when there's no custom objective."""
    # No need to do transform, XGBoost handles it internally.
    errors = np.zeros(dtrain.num_row())
    errors[y != out] = 1.0
    return 'PyMError', np.sum(errors) / dtrain.num_row()

接下来需要自定义 softprob 目标:

def softprob_obj(predt: np.ndarray, data: xgb.DMatrix):
    """Loss function.  Computing the gradient and approximated hessian (diagonal).
    Reimplements the `multi:softprob` inside XGBoost.
    """

    # Full implementation is available in the Python demo script linked below
    ...

    return grad, hess

最后可以使用 objcustom_metric 参数训练模型:

Xy = xgb.DMatrix(X, y)
booster = xgb.train(
    {"num_class": kClasses, "disable_default_eval_metric": True},
    m,
    num_boost_round=kRounds,
    obj=softprob_obj,
    custom_metric=merror_with_transform,
    evals_result=custom_results,
    evals=[(m, "train")],
)

如果不需要自定义目标,只是想提供一个XGBoost中不可用的指标:

booster = xgb.train(
    {
        "num_class": kClasses,
        "disable_default_eval_metric": True,
        "objective": "multi:softmax",
    },
    m,
    num_boost_round=kRounds,
    # Use a simpler metric implementation.
    custom_metric=merror,
    evals_result=custom_results,
    evals=[(m, "train")],
)

使用multi:softmax来说明转换后预测的差异。使用softprob时,输出预测数组的形状是(n_samples, n_classes),而对于softmax,它是(n_samples, )。关于多类目标函数的示例也可以在创建自定义多类目标函数的示例中找到。此外,更多解释请参见Intercept

Scikit-Learn 接口

XGBoost的scikit-learn接口提供了一些工具,以改善与标准的scikit-learn函数的集成,用户可以直接使用scikit-learn的成本函数(而不是评分函数):

from sklearn.datasets import load_diabetes
from sklearn.metrics import mean_absolute_error


X, y = load_diabetes(return_X_y=True)
reg = xgb.XGBRegressor(
    tree_method="hist",
    eval_metric=mean_absolute_error,
)
reg.fit(X, y, eval_set=[(X, y)])

对于自定义目标函数,用户可以在不访问DMatrix的情况下定义目标函数:

def softprob_obj(labels: np.ndarray, predt: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    rows = labels.shape[0]
    classes = predt.shape[1]
    grad = np.zeros((rows, classes), dtype=float)
    hess = np.zeros((rows, classes), dtype=float)
    eps = 1e-6
    for r in range(predt.shape[0]):
        target = labels[r]
        p = softmax(predt[r, :])
        for c in range(predt.shape[1]):
            g = p[c] - 1.0 if c == target else p[c]
            h = max((2.0 * p[c] * (1.0 - p[c])).item(), eps)
            grad[r, c] = g
            hess[r, c] = h

    grad = grad.reshape((rows * classes, 1))
    hess = hess.reshape((rows * classes, 1))
    return grad, hess

clf = xgb.XGBClassifier(tree_method="hist", objective=softprob_obj)

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uncle_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值