python - 分类任务的 Xgboost 自定义损失函数
问题描述
我是使用 XGBoost 的新手。现在我需要为 XGBoost 使用自定义损失函数。我找到了很多例子,但我不明白它们是如何从内部工作的。我需要一个分类任务的自定义损失。你能解释一下自定义损失在 XGBoost 中是如何工作的吗?
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
解决方案
推荐阅读
- c# - Linq to Entities Group By 有一些没有元素的组
- javascript - 将按钮添加到 Javascript 倒计时
- java - 如果您想要接近其尾部的元素,LinkedList 是否从末尾开始搜索?
- dart - (Flutter) 如何在不按“完成”的情况下自动监听 TextField 中的变化?
- javascript - HTA - 提交表单后如何关闭 HTA
- android - 微调器未出现在菜单栏中
- text - 与 tf idf 和 chi square 合作后我必须做什么
- angular - 根据 Angular 中的场景执行 Typescript 函数
- android - 从文件选择器获取正确的路径
- mongodb - 比较 MongoDb 中的两个字段