我希望将XGBoost模型与输入缩放和PCA特征空间缩减相结合。此外,应使用交叉验证来调整模型的超参数以及PCA中使用的组件数。为防止模型过度拟合,需要添加早期停止。
为了将各个步骤组合起来,我决定使用sklearn的Pipeline功能。
一开始,我遇到了一些问题,无法确保PCA也应用于验证集。但是我认为使用XGB__eval_set就可以解决这个问题。
代码实际上没有出现任何错误,但似乎会永远运行下去(某个时候,所有核的CPU使用率都降至零,但进程仍然运行数小时;不得不在某个时候杀死会话)。
为了将各个步骤组合起来,我决定使用sklearn的Pipeline功能。
一开始,我遇到了一些问题,无法确保PCA也应用于验证集。但是我认为使用XGB__eval_set就可以解决这个问题。
代码实际上没有出现任何错误,但似乎会永远运行下去(某个时候,所有核的CPU使用率都降至零,但进程仍然运行数小时;不得不在某个时候杀死会话)。
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from xgboost import XGBRegressor
# Train / Test split
X_train, X_test, y_train, y_test = train_test_split(X_with_features, y, test_size=0.2, random_state=123)
# Train / Validation split
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=123)
# Pipeline
pipe = Pipeline(steps=[("Scale", StandardScaler()),
("PCA", PCA()),
("XGB", XGBRegressor())])
# Hyper-parameter grid (Test only)
grid_param_pipe = {'PCA__n_components': [5],
'XGB__n_estimators': [1000],
'XGB__max_depth': [3],
'XGB__reg_alpha': [0.1],
'XGB__reg_lambda': [0.1]}
# Grid object
grid_search_pipe = GridSearchCV(estimator=pipe,
param_grid=grid_param_pipe,
scoring="neg_mean_squared_error",
cv=5,
n_jobs=5,
verbose=3)
# Run CV
grid_search_pipe.fit(X_train, y_train, XGB__early_stopping_rounds=10, XGB__eval_metric="rmse", XGB__eval_set=[[X_val, y_val]])
XGB__eval_set
是不够的。请参阅此sklearn问题https://github.com/scikit-learn/scikit-learn/issues/8414,了解有关管道步骤子集的建议应用。 - Mischa Lisovyipop
出来,对数据进行transform
,然后重新附加分类器并不难。挑战在于在CV过程中,早期停止集不是验证集的情况下完成此操作。这可能需要自定义的GridSearchCV
。 - Bert Kellerman