我正在处理一个机器学习项目,尝试将以下内容结合起来:
- 使用sklearn列变换对我的数字和类别特征应用不同的转换器
- 使用管道对我的不同转换器和评估器进行应用
- 使用
GridSearchCV
搜索最佳参数。
只要我在管道中手动填写不同转换器的参数,代码就能完美运行。但是,一旦我尝试传递列表比较网格搜索参数中的不同值,我就会收到各种无效参数错误消息。
下面是我的代码:
首先将我的特征分为数字和类别两个部分
from sklearn.compose import make_column_selector
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.impute import KNNImputer
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
numerical_features=make_column_selector(dtype_include=np.number)
cat_features=make_column_selector(dtype_exclude=np.number)
然后我为数值特征和分类特征创建两个不同的预处理管道:
numerical_pipeline= make_pipeline(KNNImputer())
cat_pipeline=make_pipeline(SimpleImputer(strategy='most_frequent'),OneHotEncoder(handle_unknown='ignore'))
我将两者结合到另一个管道中,设置参数,然后运行我的 GridSearchCV
代码。
model=make_pipeline(preprocessor, LinearRegression() )
params={
'columntransformer__numerical_pipeline__knnimputer__n_neighbors':[1,2,3,4,5,6,7]
}
grid=GridSearchCV(model, param_grid=params,scoring = 'r2',cv=10)
cv = KFold(n_splits=5)
all_accuracies = cross_val_score(grid, X, y, cv=cv,scoring='r2')
我尝试了不同的参数声明方式,但从未找到正确的方法。我总是收到“无效参数”错误消息。
请帮助我理解出了什么问题?
非常感谢您的支持,保重!
preprocessor
了。尝试使用grid.get_params()
。 - Ben Reiniger