如何使用GridSearchCV搜索Pipeline内部模型的参数?
问题解决方法
报错原因
直接使用learning_rate这类参数名时,GridSearch会默认查找Pipeline自身的参数,但Pipeline本身并没有这些参数——这些参数属于Pipeline内部的模型步骤。要指定搜索Pipeline中某个步骤内的模型参数,必须用步骤名称__参数名(双下划线分隔)的格式。
修正步骤
确认模型步骤的名称:
用make_pipeline创建的Pipeline会自动为每个步骤生成名称,比如你的Pipeline最后一步是XGBRegressor,自动生成的名称是xgbregressor。可以通过print(Or_pipeline.named_steps)查看所有步骤的名称。修改参数字典的键名:
在每个参数名前加上步骤名称和双下划线,把learning_rate改成xgbregressor__learning_rate,n_estimators改成xgbregressor__n_estimators。修正后的完整代码:
from sklearn.pipeline import make_pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OrdinalEncoder from xgboost import XGBRegressor from sklearn.model_selection import GridSearchCV # 假设OR_preprocessor是已定义的预处理模块 OR_preprocessor = ColumnTransformer(transformers=[('or', OrdinalEncoder(), ['country', 'store', 'product'])]) XGB_model = XGBRegressor() Or_pipeline = make_pipeline(OR_preprocessor, XGB_model) # 修正参数键名,同时修复原代码中400.600的笔误 params = { 'xgbregressor__learning_rate': [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1], 'xgbregressor__n_estimators': [200,400,600,800,1000] } grid_search_XGB = GridSearchCV( estimator=Or_pipeline, param_grid=params, scoring='neg_mean_absolute_error', n_jobs=1, cv=3 ) grid_search_XGB.fit(x_train, y_train)
额外提醒
原代码中n_estimators列表里的400.600是笔误,需改成400,600,否则会被识别为浮点数,而XGBoost的n_estimators要求传入整数。
内容的提问来源于stack exchange,提问作者Efan Mutembo
相关产品推荐
相关产品推荐

