代码之家  ›  专栏  ›  技术社区  ›  Columbiafashion

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

  •  2
  • Columbiafashion  · 技术社区  · 7 年前

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

    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()
    
    1 回复  |  直到 6 年前
        1
  •  9
  •   Vivek Kumar    7 年前

    您假设使用 make_pipeline 以错误的方式。从…起 the documentation :-

    这是管道建造商的简写;它不需要, 不允许,命名估计器。相反,他们的名字会 自动设置为其类型的小写。

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

    因此,现在您创建的参数网格无效,因为它包含 clf__ 并且它不存在于管道中。

    解决方案1:

    替换此行:

    pca_clf = make_pipeline(pca, clf) 
    

    具有

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

    解决方案2:

    如果您不想更改 pca_clf = make_pipeline(pca, 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] }
    

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

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

    这个 best_estimator_ 将已安装具有最佳参数的整个数据,因此您可以调用 clf.fit() 是多余的。