【问题标题】:Extracting selected feature names from scikit pipeline从 scikit 管道中提取选定的特征名称
【发布时间】:2016-05-24 09:51:42
【问题描述】:
# 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)

以上代码基于Ensuring right order of operations in random forest classification in scikit learn

由于我使用的是 SelectFromModel,我想打印(在 SelectFromModel 管道中)选择的特征的名称,但不知道如何提取它们。

【问题讨论】:

    标签: python numpy scikit-learn


    【解决方案1】:

    一种方法是在功能名称上调用功能选择器的transform(),但必须以示例列表的形式显示功能名称。

    首先,您必须从GridSearchCV 中找到的最佳估计器中获得特征选择阶段。

    fs = gs.best_estimator_.named_steps['fs']
    

    从 feature_names 创建一个示例列表:

    feature_names_example = [iris.feature_names]
    

    使用特征选择器来转换这个例子。

    selected_features = fs.transform(feature_names_example)
    
    print selected_features[0] # Select the one example
    # ['sepal length (cm)' 'petal length (cm)' 'petal width (cm)']
    

    【讨论】:

    • 此代码中 fs__threshold 的 0.7 在 scikit-learn 0.17.1 和 Python 2.7 以及 load_iris 数据集上导致以下错误。 gs.fit(X,y) 行产生以下错误 C:\Python27\lib\site-packages\sklearn\feature_selection\base.py:80: UserWarning: No features were selected: 无论是数据太嘈杂还是选择测试太严格。 UserWarning)回溯(最近一次调用最后一次):ValueError:找到具有 0 个特征的数组(形状 =(99, 0)),而至少需要 1 个。我发现如果去掉 0.7,代码会按预期运行。看起来很奇怪,但至少它可以运行。
    • 是的。如果没有重要性大于 0.7 的特征,这将是有道理的,这不足为奇。如果没有给出random_state,RandomForestClassifier 也不是确定性的。
    【解决方案2】:

    SelectFromModel 有一个 get_support() 方法,该方法返回所选特征的布尔掩码。所以你可以这样做(除了@David Maust 描述的初步步骤):

    feature_names = np.array(iris.feature_names)
    selected_features = feature_names[fs.get_support()]
    

    【讨论】:

      【解决方案3】:

      s=model.named_steps['fs'].fit(X,y)

      X.columns[s.get_support()]

      【讨论】:

        猜你喜欢
        • 2016-06-23
        • 2016-05-27
        • 2019-08-10
        • 2016-01-27
        • 2022-11-26
        • 2017-02-10
        • 2016-08-06
        • 1970-01-01
        • 2016-11-30
        相关资源
        最近更新 更多