我正在使用xgboost回归器,如果我使用GridsearchCV,我有一个关于如何使用model.evals_result()的问题
我知道如果不使用Gridsearch,我可以使用下面的代码得到想要的东西
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.33, random_state=1,shuffle=False)
evals_result = {}
eval_s = [(X_train, y_train), (X_test, y_test)]
gbm = xgb.XGBRegressor()
gbm.fit(X_train, y_train,eval_metric=["rmse"],eval_set=eval_s)
results = gbm.evals_result()
但是,如果我在代码中使用GridsearchCV,则无法获得evals_result()(见下文)。
有人线索吗?
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.33, random_state=1,shuffle=False)
gbm_param_grid = {'learning_rate': [.01, .1, .5, .9],
'n_estimators': [200, 300],
'subsample': [0.3, 0.5, 0.9]
}
fit_params = {"early_stopping_rounds": 100,
"eval_metric": "mae",
"eval_set": [(X_train, y_train), (X_test, y_test)]}
evals_result = {}
eval_s = [(X_train, y_train), (X_test, y_test)]
gbm = xgb.XGBRegressor()
tscv = TimeSeriesSplit(n_splits=2)
xgb_Gridcv = GridSearchCV(estimator=gbm, param_grid=gbm_param_grid, cv=tscv,refit = True, verbose=0)
xgb_Gridcv.fit(X_train, y_train,eval_metric=["rmse"],eval_set=eval_s)
ypred = xgb_Gridcv.predict(X_test)
现在我跑步
results = gbm.evals_result()
我收到此错误
Traceback (most recent call last):
File "/Users/prasadkamath/.conda/envs/Pk/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2961, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-11-95ef57081806>", line 1, in <module>
results = gbm.evals_result()
File "/Users/prasadkamath/.conda/envs/Pk/lib/python3.5/site-packages/xgboost/sklearn.py", line 401, in evals_result
if self.evals_result_:
AttributeError: 'XGBRegressor' object has no attribute 'evals_result_'
答案 0 :(得分:1)
xgb_Gridcv
将是包含最佳XGB模型的对象,可以通过xgb_Gridcv.best_estimator_
访问它,现在您可以在其上调用evals_result
方法,以便获得{{1 }}您需要使用:
evals_result
代替
xgb_Gridcv.best_estimator_.evals_result()
希望有帮助!
答案 1 :(得分:1)
通常,您可以直接访问字典evals_result
,而不是访问模型的方法,例如xgb_model.evals_result()。例如:
eval_s = [(X_train, y_train), (X_test, y_test)]
evals_result = {}
xgb_model = xgb.train(param,
train_orig_data_dmat,
num_boost_round=100,
evals=eval_s,
early_stopping_rounds=10,
evals_result=evals_result)
print(evals_result)
将分别打印出训练和测试的错误,以及您定义的任何评估指标。这是另一个更详细的参考:https://github.com/dmlc/xgboost/blob/master/demo/guide-python/evals_result.py