python - 使用管道的 XGBRegressor

标签 python machine-learning pipeline xgboost

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

以下是完整的预处理步骤。 (我已经定义了 numeric_cols 和 cat_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。要做到这一点,最简单的方法是在没有“模型”步骤的情况下使用您的管道。在拟合管道之前使用以下代码:

# 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)
然后在更改 model__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)])

关于python - 使用管道的 XGBRegressor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58136107/

相关文章:

linux - 将 cat、head、tail 和 tr 与管道结合使用

python - 使用python将整个文本文件加载到数据库中

python - Cython 对结构的字符串成员函数表现异常

python - 列表中的反向索引

matlab - 使用非齐次隐马尔可夫模型预测降雨量

azure - 如何导出 datafactory v2 中的管道或迁移到另一个

shell - fish 管道状态

返回 bool 值和消息的 Pythonic 方式

python - 线性回归中MSE和RMSE的计算

python - 在 sklearn 中训练后是否必须再次使用 fit() ?