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

2024-03-05 05:28

本文主要是介绍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 Tupledef 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 asobjective function.'''predt[predt < -1] = -1 + 1e-6grad = 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-6elements = 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 npdef 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] = iassert y.shape == out.shapeerrors = np.zeros(dtrain.num_row())errors[y != out] = 1.0return '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.0return '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_errorX, 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-6for 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] = ghess[r, c] = hgrad = grad.reshape((rows * classes, 1))hess = hess.reshape((rows * classes, 1))return grad, hessclf = xgb.XGBClassifier(tree_method="hist", objective=softprob_obj)

参考

  • https://xgboost.readthedocs.io/en/latest/tutorials/custom_metric_obj.html
  • https://xgboost.readthedocs.io/en/latest/python/examples/custom_rmsle.html#sphx-glr-python-examples-custom-rmsle-py

这篇关于XGB-16:自定义目标和评估指标的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/775445

相关文章

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

MySQL8 密码强度评估与配置详解

《MySQL8密码强度评估与配置详解》MySQL8默认启用密码强度插件,实施MEDIUM策略(长度8、含数字/字母/特殊字符),支持动态调整与配置文件设置,推荐使用STRONG策略并定期更新密码以提... 目录一、mysql 8 密码强度评估机制1.核心插件:validate_password2.密码策略级

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

Linux中的自定义协议+序列反序列化用法

《Linux中的自定义协议+序列反序列化用法》文章探讨网络程序在应用层的实现,涉及TCP协议的数据传输机制、结构化数据的序列化与反序列化方法,以及通过JSON和自定义协议构建网络计算器的思路,强调分层... 目录一,再次理解协议二,序列化和反序列化三,实现网络计算器3.1 日志文件3.2Socket.hpp

C语言自定义类型之联合和枚举解读

《C语言自定义类型之联合和枚举解读》联合体共享内存,大小由最大成员决定,遵循对齐规则;枚举类型列举可能值,提升可读性和类型安全性,两者在C语言中用于优化内存和程序效率... 目录一、联合体1.1 联合体类型的声明1.2 联合体的特点1.2.1 特点11.2.2 特点21.2.3 特点31.3 联合体的大小1

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

解读GC日志中的各项指标用法

《解读GC日志中的各项指标用法》:本文主要介绍GC日志中的各项指标用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、基础 GC 日志格式(以 G1 为例)1. Minor GC 日志2. Full GC 日志二、关键指标解析1. GC 类型与触发原因2. 堆