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

2024-02-23

有人可以检查以下代码的问题吗? 我在构建模型的过程中是否有任何错误? 我已经在参数中添加了两个“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()

您假设使用make_pipeline以错误的方式。从文档 http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html:-

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

因此,这意味着当您提供 PCA 对象时,其名称将被设置为“pca”(小写),当您向其提供 RandomForestClassifier 对象时,它将被命名为“randomforestclassifier”,而不是您所想的“clf” 。

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

解决方案1:

替换这一行:

pca_clf = make_pipeline(pca, clf) 

With

pca_clf = Pipeline([('pca', pca), ('clf', clf)])

解决方案2:

如果您不想更改pca_clf = make_pipeline(pca, clf)行,然后替换所有出现的 clf 在你的parameters像这样的“随机森林分类器”:

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] }

Sidenote:无需在代码中执行此操作:

clf = grid_RF.best_estimator_
clf.fit(X_train, y_train)

The best_estimator_将已经安装了具有最佳找到参数的整个数据,因此您调用clf.fit()是多余的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

sklearn 中估计器管道的参数 clf 无效 的相关文章

随机推荐