python 管道中的特征选择:如何确定特征名称?

python feature selection in pipeline: how determine feature names?

我使用管道和 grid_search 到 select 最佳参数,然后使用这些参数来拟合最佳管道 ('best_pipe')。但是,由于 feature_selection (SelectKBest) 在管道中,因此没有适合 SelectKBest。

我需要知道 'k' selected 特征的特征名称。任何想法如何检索它们?提前谢谢你

from sklearn import (cross_validation, feature_selection, pipeline,
                     preprocessing, linear_model, grid_search)
folds = 5
split = cross_validation.StratifiedKFold(target, n_folds=folds, shuffle = False, random_state = 0)

scores = []
for k, (train, test) in enumerate(split):

    X_train, X_test, y_train, y_test = X.ix[train], X.ix[test], y.ix[train], y.ix[test]

    top_feat = feature_selection.SelectKBest()

    pipe = pipeline.Pipeline([('scaler', preprocessing.StandardScaler()),
                                 ('feat', top_feat),
                                 ('clf', linear_model.LogisticRegression())])

    K = [40, 60, 80, 100]
    C = [1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001]
    penalty = ['l1', 'l2']

    param_grid = [{'feat__k': K,
                  'clf__C': C,
                  'clf__penalty': penalty}]

    scoring = 'precision'

    gs = grid_search.GridSearchCV(estimator=pipe, param_grid = param_grid, scoring = scoring)
    gs.fit(X_train, y_train)

    best_score = gs.best_score_
    scores.append(best_score)

    print "Fold: {} {} {:.4f}".format(k+1, scoring, best_score)
    print gs.best_params_

best_pipe = pipeline.Pipeline([('scale', preprocessing.StandardScaler()),
                          ('feat', feature_selection.SelectKBest(k=80)),
                          ('clf', linear_model.LogisticRegression(C=.0001, penalty='l2'))])

best_pipe.fit(X_train, y_train)
best_pipe.predict(X_test)

您可以在 best_pipe 中按名称访问功能选择器:

features = best_pipe.named_steps['feat']

然后您可以在索引数组上调用 transform() 以获取所选列的名称:

X.columns[features.transform(np.arange(len(X.columns)))]

此处的输出将是管道中选择的八十个列名称。

这可能是一个有启发性的选择:我遇到了与 OP 所要求的类似的需求。如果想直接从 GridSearchCV:

中获取 k 个最佳特征的索引
finalFeatureIndices = gs.best_estimator_.named_steps["feat"].get_support(indices=True)

并且通过index manipulation,可以获得你的finalFeatureList:

finalFeatureList = [initialFeatureList[i] for i in finalFeatureIndices]

杰克的回答完全有效。但是根据您使用的功能选择器,还有另一个我认为更简洁的选项。这个对我有用:

X.columns[features.get_support()]

它给了我与杰克的答案相同的答案。您可以在 the docs 中看到更多相关信息,但是 get_support returns 一个 true/false 值的数组,表示是否使用了该列。此外,值得注意的是 X 必须与特征选择器上使用的训练数据具有相同的形状。