首页 > 解决方案 > 分类任务的 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

标签: pythonxgboostloss-function

解决方案


推荐阅读