【问题标题】:How to use GridSearchCV output for a scikit prediction?如何使用 GridSearchCV 输出进行 scikit 预测?
【发布时间】:2016-05-25 03:21:48
【问题描述】:

在以下代码中:

# Load dataset
iris = datasets.load_iris()
X, y = iris.data, iris.target

rf_feature_imp = RandomForestClassifier(100)
feat_selection = SelectFromModel(rf_feature_imp, threshold=0.5)

clf = RandomForestClassifier(5000)

model = Pipeline([
          ('fs', feat_selection), 
          ('clf', clf), 
        ])

 params = {
    'fs__threshold': [0.5, 0.3, 0.7],
    'fs__estimator__max_features': ['auto', 'sqrt', 'log2'],
    'clf__max_features': ['auto', 'sqrt', 'log2'],
 }

 gs = GridSearchCV(model, params, ...)
 gs.fit(X,y)

预测应该使用什么?

  • gs?
  • gs.best_estimator_? 或
  • gs.best_estimator_.named_steps['clf']?

这三个有什么区别?

【问题讨论】:

    标签: python scikit-learn grid-search


    【解决方案1】:

    gs.predict(X_test) 等价于gs.best_estimator_.predict(X_test)。使用其中任何一个,X_test 将通过您的整个管道并返回预测。

    gs.best_estimator_.named_steps['clf'].predict(),然而只是流水线的最后一个阶段。要使用它,必须已经执行了特征选择步骤。这只有在您之前通过 gs.best_estimator_.named_steps['fs'].transform() 运行数据时才有效

    生成预测的三种等效方法如下所示:

    直接使用gs

    pred = gs.predict(X_test)
    

    使用best_estimator_

    pred = gs.best_estimator_.predict(X_test)
    

    单独调用管道中的每个步骤。

    X_test_fs = gs.best_estimator_.named_steps['fs'].transform(X_test)
    pred = gs.best_estimator_.named_steps['clf'].predict(X_test_fs)
    

    【讨论】:

    • 非常感谢!有没有官方文档这么说?
    猜你喜欢
    • 2012-12-13
    • 2021-03-24
    • 2013-05-31
    • 2018-03-21
    • 2021-01-11
    • 2017-09-09
    • 2020-11-22
    • 2022-09-27
    • 2015-02-28
    相关资源
    最近更新 更多