在Python中为XGBoost指定tree\u方法参数

2024-04-20 14:51:00 发布

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

我正在使用Python中的XGBoost(PyPl:0.6的最新版本)开发一个预测模型,并在我的大约一半数据上进行了it培训。现在我有了我的最终模型,我用我所有的数据对它进行了训练,但是得到了一个我从未见过的信息:

Tree method is automatically selected to be 'approx' for faster speed. to use old behavior(exact greedy algorithm on single machine), set tree_method to 'exact'"

作为一个可复制的示例,以下代码也会在我的计算机上生成该消息:

import numpy as np
import xgboost as xgb

rows = 10**7
cols = 20
X = np.random.randint(0, 100, (rows, cols))    
y = np.random.randint(0,2, size=rows)

clf = xgb.XGBClassifier(max_depth=5)
clf.fit(X,y)    

在我的模型的初始化和fit()步骤中,我尝试将tree_方法设置为“精确”,但每个步骤都会抛出错误:

^{pr2}$

如何在Python中使用XGBoost指定tree_method='exact'?在


Tags: to数据模型importtreeasnprandom
3条回答

根据XGBoostparameter documentation,这是因为tree_method的默认值是“auto”。“自动”设置取决于数据:对于“中小型”数据,它将使用“精确”方法;对于“非常大”数据集,它将使用“近似”。当您开始使用整个训练集(而不是50%)时,您必须已超过训练大小阈值,该阈值会更改tree_method的自动值。从文档中还不清楚要达到这个阈值需要多少个观察值,但它似乎在500万到1000万行之间(因为您有rows = 10**7)。在

我不知道tree_method参数是否在XGBoost Python模块中公开(听起来好像不是,所以可能要提交一个bug报告?),但tree_method在R API中公开。在

文档描述了您看到警告消息的原因:

enter image description here

您可以在xGBoost中使用sklearnapi中的GPU。你可以这样使用它:

import xgboost

xgb = xgboost.XGBClassifier(n_estimators=200, tree_method='gpu_hist', predictor='gpu_predictor')
xgb.fit(X_train, y_train)

可以使用不同的树方法。请参考documentation选择最适合您需要的方法。在

它仍然没有在用于xgboost的scikit learn API中实现。 因此,我引用了下面来自here的代码示例。在

import xgboost as xgb
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

digits = load_digits(2)
X = digits['data']
y = digits['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
dtrain = xgb.DMatrix(X_train, y_train)
dtest = xgb.DMatrix(X_test, y_test)

param = {'objective': 'binary:logistic',
         'tree_method':'hist',
         'grow_policy':"lossguide",
         'eval_metric': 'auc'}
res = {}
bst = xgb.train(param, dtrain, 10, [(dtrain, 'train'), (dtest, 'test')], evals_result=res)

相关问题 更多 >