我使用BayesSearchCV
来自scikit-optimize
来优化一个XGBoost
模型以适应我的一些数据。虽然模型适应得很好,但我对诊断信息中提供的分数感到困惑,并且无法复制这些分数。
这里有一个使用波士顿房价数据集的示例脚本来说明我的观点:
from sklearn.datasets import load_bostonimport numpy as npimport pandas as pdfrom xgboost.sklearn import XGBRegressorfrom skopt import BayesSearchCVfrom skopt.space import Real, Categorical, Integerfrom sklearn.model_selection import KFold, train_test_split boston = load_boston()# 数据集信息:print(boston.keys())print(boston.data.shape)print(boston.feature_names)print(boston.DESCR)# 将数据放入数据框并标记列标题:data = pd.DataFrame(boston.data)data.columns = boston.feature_names# 将目标变量添加到数据框data['PRICE'] = boston.target# 分割成X和yX, y = data.iloc[:, :-1],data.iloc[:,-1]# 将数据分割成训练和验证集 X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42, shuffle = True) # 对于交叉验证,将训练数据分成5个折叠xgb_kfold = KFold(n_splits = 5,random_state = 42)# 运行拟合xgb_params = {'n_estimators': Integer(10, 3000, 'uniform'), 'max_depth': Integer(2, 100, 'uniform'), 'subsample': Real(0.25, 1.0, 'uniform'), 'learning_rate': Real(0.0001, 0.5, 'uniform'), 'gamma': Real(0.0001, 1.0, 'uniform'), 'colsample_bytree': Real(0.0001, 1.0, 'uniform'), 'colsample_bylevel': Real(0.0001, 1.0, 'uniform'), 'colsample_bynode': Real(0.0001, 1.0, 'uniform'), 'min_child_weight': Real(1, 6, 'uniform')}xgb_fit_params = {'early_stopping_rounds': 15, 'eval_metric': 'mae', 'eval_set': [[X_val, y_val]]}xgb_pipe = XGBRegressor(random_state = 42, objective='reg:squarederror', n_jobs = 10)xgb_cv = BayesSearchCV(xgb_pipe, xgb_params, cv = xgb_kfold, n_iter = 5, n_jobs = 1, random_state = 42, verbose = 4, scoring = None, fit_params = xgb_fit_params)xgb_cv.fit(X_train, y_train)
运行后,xgb_cv.best_score_
是0.816,xgb_cv.best_index_
是3。查看xgb_cv.cv_results_
,我想找到每个折叠的最佳分数:
print(xgb_cv.cv_results_['split0_test_score'][xgb_cv.best_index_], xgb_cv.cv_results_['split1_test_score'][xgb_cv.best_index_], xgb_cv.cv_results_['split2_test_score'][xgb_cv.best_index_], xgb_cv.cv_results_['split3_test_score'][xgb_cv.best_index_], xgb_cv.cv_results_['split4_test_score'][xgb_cv.best_index_])
这给出:
0.8023562337946979, 0.8337404778903412, 0.861370681263761, 0.8749312273014963, 0.7058815015739375
我不确定这里计算的是什么,因为我的代码中scoring
设置为None
。XGBoost的文档帮助不大,但根据xgb_cv.best_estimator_.score?
,它应该是预测值的R2。无论如何,当我尝试手动计算拟合中使用的每个折叠的数据分数时,我无法得到这些值:
# 首先,需要从每个折叠中获取数据的实际索引:kfold_indexes = {}kfold_cnt = 0for train_index, test_index in xgb_kfold.split(X_train): kfold_indexes[kfold_cnt] = {'train': train_index, 'test': test_index} kfold_cnt = kfold_cnt+1# 接下来,计算每个折叠的分数 for p in range(5): print(xgb_cv.best_estimator_.score(X_train.iloc[kfold_indexes[p]['test']], y_train.iloc[kfold_indexes[p]['test']]))
这给我以下结果:
0.99549296185737860.9948448036661010.99631081520272450.99622745440898320.9931314653538819
BayesSearchCV是如何计算每个折叠的分数的,为什么我使用score
函数无法复制这些分数?我将非常感激对此问题提供的任何帮助。
(另外,手动计算这些分数的平均值得到:0.8156560…,而xgb_cv.best_score_
给出:0.8159277… 不确定这里为什么有精度差异。)
回答:
best_estimator_
是重新拟合的估计器,在选择超参数后在整个训练集上拟合;因此,在训练集的任何部分上对其进行评分都会产生乐观的偏见。要复制cv_results_
,你需要重新拟合每个训练折叠的估计器,并对相应的测试折叠进行score
评分。
除此之外,确实似乎还有XGBoost的random_state
未涵盖的更多随机性。还有另一个参数seed
;设置该参数对我来说可以产生一致的结果。(这里有一些较旧的帖子(示例)报告了即使设置了seed
也存在类似的问题,但或许这些问题已在新版本的xgb中得到解决。)