sklearn 中估算器管道的参数 clf 无效

Col*_*ion 1 python pipeline pca scikit-learn

任何人都可以检查以下代码的问题吗?我在构建模型的任何步骤中都错了吗?我已经在参数中添加了两个“clf__”。

clf=RandomForestClassifier()
pca = PCA()
pca_clf = make_pipeline(pca, clf) 


kfold = KFold(n_splits=10, random_state=22)



parameters = {'clf__n_estimators': [4, 6, 9], 'clf__max_features': ['log2', 
'sqrt','auto'],'clf__criterion': ['entropy', 'gini'], 'clf__max_depth': [2, 
 3, 5, 10], 'clf__min_samples_split': [2, 3, 5],
'clf__min_samples_leaf': [1,5,8] }

grid_RF=GridSearchCV(pca_clf,param_grid=parameters,
        scoring='accuracy',cv=kfold)
grid_RF = grid_RF.fit(X_train, y_train)
clf = grid_RF.best_estimator_
clf.fit(X_train, y_train)
grid_RF.best_score_

cv_result = cross_val_score(clf,X_train,y_train, cv = kfold,scoring = 
"accuracy")

cv_result.mean()
Run Code Online (Sandbox Code Playgroud)

Viv*_*mar 9

您假设make_pipeline以错误的方式使用。从文档: -

这是 Pipeline 构造函数的简写;它不需要,也不允许,命名估算器。相反,它们的名称将自动设置为其类型的小写。

所以这意味着当你提供一个 PCA 对象时,它的名称将被设置为“pca”(小写),当你向它提供一个 RandomForestClassifier 对象时,它会被命名为“randomforestclassifier”,而不是你想的“clf” .

所以现在您制作的参数网格无效,因为它包含clf__但不存在于管道中。

解决方案1:

替换这一行:

pca_clf = make_pipeline(pca, clf) 
Run Code Online (Sandbox Code Playgroud)

pca_clf = Pipeline([('pca', pca), ('clf', clf)])
Run Code Online (Sandbox Code Playgroud)

解决方案2:

如果您不想更改该pca_clf = make_pipeline(pca, clf)行,则将所有出现的 clf 替换parameters为“randomforestclassifier”,如下所示:

parameters = {'randomforestclassifier__n_estimators': [4, 6, 9], 
              'randomforestclassifier__max_features': ['log2', 'sqrt','auto'],
              'randomforestclassifier__criterion': ['entropy', 'gini'], 
              'randomforestclassifier__max_depth': [2, 3, 5, 10], 
              'randomforestclassifier__min_samples_split': [2, 3, 5],
              'randomforestclassifier__min_samples_leaf': [1,5,8] }
Run Code Online (Sandbox Code Playgroud)

旁注:无需在您的代码中执行此操作:

clf = grid_RF.best_estimator_
clf.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)

best_estimator_会已配备带有最好找到PARAMS整个数据,所以你打电话clf.fit()是多余的。