objectif
Définir une métrique d’évaluation custom pour xgb.train.
code minimal
import numpy as np
import xgboost as xgb
X = np.random.RandomState(0).randn(100, 2)
y = (X[:,0]*2 + X[:,1] > 0).astype(float)
dtrain = xgb.DMatrix(X, label=y)
def feval_mape(preds, dtrain):
y_true = dtrain.get_label()
denom = np.maximum(np.abs(y_true), 1e-8)
mape = np.mean(np.abs((y_true - preds)/denom))
return ("mape", float(mape), False) # False => plus petit est meilleur
params = {"objective":"reg:squarederror", "seed":0, "tree_method":"hist"}
bst = xgb.train(params, dtrain, num_boost_round=50, feval=feval_mape)
print(isinstance(bst, xgb.Booster))
utilisation
# Avec jeu de validation + early stopping basé sur la métrique custom
dval = xgb.DMatrix(X, label=y)
bst = xgb.train(
params, dtrain,
num_boost_round=200,
feval=feval_mape,
evals=[(dval, "val")],
early_stopping_rounds=10,
)
print(bst.best_iteration >= 0)
variante(s) utile(s)
# Récupérer l'historique
hist = bst.eval_history()
print("val" in hist)
notes
- Pour scikit-learn API, feval n’est pas directement supporté; utilisez xgb.train si vous avez besoin d’une métrique custom.