如何使用XGboost为不同的“eval”度量优化sklearn管道?

2024-04-25 17:52:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用XGBoost,并将eval_metric优化为auc(如所述here)。

当直接使用分类器时,这很好,但当我试图将其用作pipeline时失败。

向sklearn管道传递.fit参数的正确方法是什么?

示例:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from xgboost import XGBClassifier
import xgboost
import sklearn

print('sklearn version: %s' % sklearn.__version__)
print('xgboost version: %s' % xgboost.__version__)

X, y = load_iris(return_X_y=True)

# Without using the pipeline: 
xgb = XGBClassifier()
xgb.fit(X, y, eval_metric='auc')  # works fine

# Making a pipeline with this classifier and a scaler:
pipe = Pipeline([('scaler', StandardScaler()), ('classifier', XGBClassifier())])

# using the pipeline, but not optimizing for 'auc': 
pipe.fit(X, y)  # works fine

# however this does not work (even after correcting the underscores): 
pipe.fit(X, y, classifier__eval_metric='auc')  # fails

错误:
TypeError: before_fit() got an unexpected keyword argument 'classifier__eval_metric'

关于xgboost的版本:
xgboost.__version__显示0.6
pip3 freeze | grep xgboost显示xgboost==0.6a2


Tags: thefromimportpipelineversionevalsklearnmetric
2条回答

错误是因为在管道中使用时,估计器名称与其参数之间使用了一个下划线。应该是两个下划线。

documentation of Pipeline.fit()中,我们可以看到提供合适参数的正确方法:

Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.

因此,在您的情况下,正确的用法是:

pipe.fit(X_train, y_train, classifier__eval_metric='auc')

(注意name和param之间有两个下划线)

当目标是优化时,我建议使用sklearn包装器和GridSearchCV

from xgboost.sklearn import XGBClassifier
from sklearn.grid_search import GridSearchCV

看起来像

pipe = Pipeline([('scaler', StandardScaler()), ('classifier', XGBClassifier())])

score = 'roc_auc'
pipe.fit(X, y) 

param = {
 'classifier_max_depth':[1,2,3,4,5,6,7,8,9,10] # just as example
}

gsearch = GridSearchCV(estimator =pipe, param_grid =param , scoring= score)

也可以使用交叉验证技术

gsearch.fit(X, y)

你得到了最好的参数和最好的分数

gsearch.best_params_, gsearch.best_score_

相关问题 更多 >