在使用XGBoost包时,我们可以在param字典中设置’objective’(例如:’objective’: ‘binary:logistic’),并将该字典传递给train函数。同时,train函数中还有一个obj参数。据我所知,这两者都是目标函数。那么,它们有什么区别呢?如果两者都被设置,哪一个会生效呢?
param = {'max_depth': 3, 'eta': 1, 'silent': 1, 'objective': 'binary:logistic'} bst = xgb.train(param, data_train, num_boost_round=n_round, obj=g_h, feval=error_rate)
其中,g_h是一个自定义的目标函数。
奇怪的是,我发现如果同时设置了’objective’: ‘binary:logistic’和obj,y_hat的值是
y_hat: [6.0993789e-06 9.8472750e-01 6.0993789e-06 ... 9.9993265e-01 4.4560062e-07 9.9993265e-01]
如果我跳过’objective’: ‘binary:logistic’,只在train中设置obj,y_hat的值是
y_hat: [-5.6174016 5.2989674 -5.6174016 ... 7.6525593 -6.4794073 6.7979865]
因此,train函数中的obj并没有覆盖’objective’: ‘binary:logistic’!
这是代码:
import xgboost as xgbdef g_h(y_hat, y): p = 1.0 / (1.0 + np.exp(-y_hat)) g = p - y.get_label() h = p * (1.0-p) return g, h# read in datadtrain = xgb.DMatrix('demo/data/agaricus.txt.train')dtest = xgb.DMatrix('demo/data/agaricus.txt.test')# specify parameters via mapparam = {'max_depth':3, 'eta':1, 'silent':1, 'objective':'binary:logistic' }num_round = 7bst = xgb.train(param, dtrain, num_round)# make predictiony_hat = bst.predict(dtest)print(y_hat)
回答:
最初,objective
构造函数参数仅支持定义已知目标函数的string
值,例如您示例中的那种。另一方面,obj
参数期望一个具有签名objective(y_true, y_pred) -> grad, hess
的可调用对象。
然而,如今(至少在v0.7版本中),两者都可以是自定义的可调用对象。对于用户来说,这意味着您可以使用任一种方式来定义目标函数,传递给train的将覆盖构造函数中定义的。对于这种双重定义方式的存在,我的最佳猜测是出于向后兼容性的考虑。