2

我正在使用 XGBoost 0.90。我希望使用 Python 训练 XGBoost 回归模型,使用内置的学习目标,并在内置评估指标上提前停止。简单的。就我而言,目标是“reg:tweedie”,评估指标是“tweedie-nloglik”。但是在每次迭代中,我希望计算一个信息丰富的自定义指标,它不应该用于提前停止。但它是错误的。

最终我希望使用 scikit-learn GridSearchCV,用内置的目标和指标训练一组模型以提前停止,但最后选择最适合折叠自定义指标的模型。

在此示例代码中,我使用了另一个内置目标和内置指标,但问题是相同的。

import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split

def mymetric(pred, dmat):
    y = dmat.get_label()
    res = np.sqrt(np.sum((y - pred)**4)/len(y))
    return 'mymetric', float(res)

np.random.seed(seed=2500)
x, y, weight = np.random.randn(4096, 16), np.random.randn(4096), np.random.random(4096)

train_x, test_x, train_y, test_y, train_weight, test_weight = train_test_split(x, y, weight, 
                                                                               train_size=0.7, random_state=32)

dtrain = xgb.DMatrix(train_x, label=train_y, weight=train_weight)
dtest = xgb.DMatrix(test_x, label=test_y, weight=test_weight)

results_learning = {}
bst = xgb.train(params={'objective': 'reg:squarederror', 
                        'eval_metric': 'rmse', 
                        'disable_default_eval_metric': 0},
    num_boost_round=20, dtrain=dtrain, evals=[(dtrain, 'dtrain'), (dtest, 'dtest')],
    evals_result=results_learning,
    feval=mymetric,
    early_stopping_rounds=3)

输出是(如果我没有使用feval 它将在迭代 3 处停止):

[0] dtrain-rmse:1.02988 dtest-rmse:1.11216  dtrain-mymetric:1.85777 dtest-mymetric:2.15138
Multiple eval metrics have been passed: 'dtest-mymetric' will be used for early stopping.
Will train until dtest-mymetric hasn't improved in 3 rounds.
...
Stopping. Best iteration:
[4] dtrain-rmse:0.919674    dtest-rmse:1.08358  dtrain-mymetric:1.56446 dtest-mymetric:1.9885

我怎么能得到这样的输出?

[0] dtrain-rmse:1.02988 dtest-rmse:1.11216  dtrain-mymetric:1.85777 dtest-mymetric:2.15138
Multiple eval metrics have been passed: 'dtest-rmse' will be used for early stopping.
Will train until dtest-rmse hasn't improved in 3 rounds.
...
Stopping. Best iteration:
[3] dtrain-rmse:0.941712    dtest-rmse:1.0821   dtrain-mymetric:1.61367 dtest-mymetric:1.99428

我可以通过返回元组列表的自定义评估函数来解决这个问题(https://github.com/dmlc/xgboost/issues/1125)。但是,当我希望使用“rmse”或“tweedie-nloglik”等内置评估指标时,可以这样做吗?我可以在自定义评估函数中调用它们吗?

4

1 回答 1

1

XGBoost 中有一个内置的提前停止回调函数,可以在其中指定用于提前停止的数据集和指标。在您的情况下,您必须像这样创建一个新的提前停止回调:

early_stop = xgb.callback.EarlyStopping(rounds=3,
                                    metric_name='rmse',
                                    data_name='dtest')

然后在调用 train 时将其添加到回调列表中:

bst = xgb.train(params={'objective': 'reg:squarederror', 
                    'eval_metric': 'rmse', 
                    'disable_default_eval_metric': 0},
num_boost_round=20, dtrain=dtrain, evals=[(dtrain, 'dtrain'), (dtest, 'dtest')],
evals_result=results_learning,
feval=mymetric,
callbacks=[early_stop])

有关更多信息,请参阅文档的此页面:https ://xgboost.readthedocs.io/en/latest/python/callbacks.html

于 2021-01-26T21:50:58.740 回答