XGBoost is designed to be an extensible library. One way to extend it is by providing our
own objective function for training and corresponding metric for performance monitoring.
This document introduces implementing a customized elementwise evaluation metric and
objective for XGBoost. Although the introduction uses Python for demonstration, the
concepts should be readily applicable to other language bindings.
See also the advanced usage example for more information about limitations and
workarounds for more complex objetives: Advanced Usage of Custom Objectives
In the following two sections, we will provide a step by step walk through of implementing
the SquaredLogError(SLE) objective function:
21[log(pred+1)−log(label+1)]2
and its default metric RootMeanSquaredLogError(RMSLE):
N1[log(pred+1)−log(label+1)]2
Although XGBoost has native support for said functions, using it for demonstration
provides us the opportunity of comparing the result from our own implementation and the
one from XGBoost internal for learning purposes. After finishing this tutorial, we should
be able to provide our own functions for rapid experiments. And at the end, we will
provide some notes on non-identity link function along with examples of using custom metric
and objective with the scikit-learn interface.
If we compute the gradient of said objective function:
During model training, the objective function plays an important role: provide gradient
information, both first and second order gradient, based on model predictions and observed
data labels (or targets). Therefore, a valid objective function should accept two inputs,
namely prediction and labels. For implementing SLE, we define:
importnumpyasnpimportxgboostasxgbfromtypingimportTupledefgradient(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)defhessian(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))defsquared_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-6grad=gradient(predt,dtrain)hess=hessian(predt,dtrain)returngrad,hess
In the above code snippet, squared_log is the objective function we want. It accepts a
numpy array predt as model prediction, and the training DMatrix for obtaining required
information, including labels and weights (not used here). This objective is then used as
a callback function for XGBoost during training by passing it as an argument to
xgb.train:
xgb.train({'tree_method':'hist','seed':1994},# any other tree method is fine.dtrain=dtrain,num_boost_round=10,obj=squared_log)
Notice that in our definition of the objective, whether we subtract the labels from the
prediction or the other way around is important. If you find the training error goes up
instead of down, this might be the reason.
Customized Metric Function
So after having a customized objective, we might also need a corresponding metric to
monitor our model’s performance. As mentioned above, the default metric for SLE is
RMSLE. Similarly we define another callback like function as the new metric:
defrmsle(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)))
Since we are demonstrating in Python, the metric or objective need not be a function, any
callable object should suffice. Similar to the objective function, our metric also
accepts predt and dtrain as inputs, but returns the name of the metric itself and
a floating point value as the result. After passing it into XGBoost as argument of
custom_metric parameter:
When using builtin objective, the raw prediction is transformed according to the objective
function. When a custom objective is provided XGBoost doesn’t know its link function so the
user is responsible for making the transformation for both objective and custom evaluation
metric. For objective with identity link like squarederror this is trivial, but for
other link functions like log link or inverse link the difference is significant.
For the Python package, the behaviour of prediction can be controlled by the
output_margin parameter in predict function. When using the custom_metric
parameter without a custom objective, the metric function will receive transformed
prediction since the objective is defined by XGBoost. However, when the custom objective is
also provided along with that metric, then both the objective and custom metric will
receive raw prediction. The following example provides a comparison between two different
behavior with a multi-class classification model. Firstly we define 2 different Python
metric functions implementing the same underlying metric for comparison,
merror_with_transform is used when custom objective is also used, otherwise the simpler
merror is preferred since XGBoost can perform the transformation itself.
importxgboostasxgbimportnumpyasnpdefmerror_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.assertpredt.shape==(d_train.num_row(),n_classes)out=np.zeros(dtrain.num_row())forrinrange(predt.shape[0]):i=np.argmax(predt[r])out[r]=iasserty.shape==out.shapeerrors=np.zeros(dtrain.num_row())errors[y!=out]=1.0return'PyMError',np.sum(errors)/dtrain.num_row()
The above function is only needed when we want to use custom objective and XGBoost doesn’t
know how to transform the prediction. The normal implementation for multi-class error
function is:
defmerror(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',
Next we need the custom softprob objective:
defsoftprob_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...returngrad,hess
Lastly we can train the model using obj and custom_metric parameters:
Or if you don’t need the custom objective and just want to supply a metric that’s not
available in 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=[(
We use multi:softmax to illustrate the differences of transformed prediction. With
softprob the output prediction array has shape (n_samples,n_classes) while for
softmax it’s (n_samples,). A demo for multi-class objective function is also
available at Demo for creating customized multi-class objective function. Also, see
Intercept for some more explanation.
Scikit-Learn Interface
The scikit-learn interface of XGBoost has some utilities to improve the integration with
standard scikit-learn functions. For instance, after XGBoost 1.6.0 users can use the cost
function (not scoring functions) from scikit-learn out of the box: