使用管道的 XGBRegressor

XGBRegressor using Pipeline

我在管道中使用 XGBRegressor。管道包含预处理步骤和模型 (XGBRegressor)。

以下是完整的预处理步骤。 (我已经定义了numeric_colscat_cols

numerical_transfer = SimpleImputer()
cat_transfer = Pipeline(steps = [
   ('imputer', SimpleImputer(strategy = 'most_frequent')),
   ('onehot', OneHotEncoder(handle_unknown = 'ignore'))
   ])
preprocessor = ColumnTransformer(
   transformers = [
   ('num', numerical_transfer, numeric_cols),
   ('cat', cat_transfer, cat_cols)
   ])

最后的管道是

my_model = Pipeline(steps = [('preprocessor', preprocessor), ('model', model)])

当我尝试不使用 early_stopping_rounds 时,代码工作正常。

(my_model.fit(X_train, y_train))

但是当我如下所示使用 early_stopping_rounds 时出现错误。

my_model.fit(X_train, y_train, model__early_stopping_rounds=5, model__eval_metric = "mae", model__eval_set=[(X_valid, y_valid)])

我在以下位置遇到错误:

 model__eval_set=[(X_valid, y_valid)]) and the error is

ValueError: DataFrame.dtypes for data must be int, float or bool.
Did not expect the data types in fields MSZoning, Street, Alley, LotShape, LandContour, Utilities, LotConfig, LandSlope, Condition1, Condition2, BldgType, HouseStyle, RoofStyle, RoofMatl, MasVnrType, ExterQual, ExterCond, Foundation, BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1, BsmtFinType2, Heating, HeatingQC, CentralAir, Electrical, KitchenQual, Functional, FireplaceQu, GarageType, GarageFinish, GarageQual, GarageCond, PavedDrive, PoolQC, Fence, MiscFeature, SaleType, SaleCondition

这是否意味着我应该在应用到 my_model.fit() 之前预处理 X_valid 还是我做错了什么?

如果问题是我们需要在应用 fit() 之前预处理 X_valid 如何使用我在上面定义的预处理器来做到这一点?

编辑:我尝试在没有管道的情况下预处理 X_valid,但出现功能不匹配的错误。

问题是管道不适合eval_set。所以,正如你所说,你需要预处理X_valid。要做到这一点,最简单的方法是使用没有 'model' 步骤的管道。在安装管道之前使用以下代码:

# Make a copy to avoid changing original data
X_valid_eval=X_valid.copy()
# Remove the model from pipeline
eval_set_pipe = Pipeline(steps = [('preprocessor', preprocessor)])
# fit transform X_valid.copy()
X_valid_eval = eval_set_pipe.fit(X_train, y_train).transform (X_valid_eval)

然后在更改模型后安装您的管道__eval_set如下:

my_model.fit(X_train, y_train, model__early_stopping_rounds=5, model__eval_metric = "mae", model__eval_set=[(X_valid_eval, y_valid)])