从递归特征消除(RFE)中提取最佳特征

时间:2017-12-09 15:55:00

标签: python-2.7 machine-learning scikit-learn feature-selection rfe

我有一个数据集,包含124个特征的分类和数字数据。为了减少其维度,我想删除不相关的功能。但是,为了针对特征选择算法运行数据集,我使用get_dummies对其进行了热编码,这使得特征数量增加到391个。

In[16]:
X_train.columns
Out[16]:
Index([u'port_7', u'port_9', u'port_13', u'port_17', u'port_19', u'port_21',
   ...
   u'os_cpes.1_2', u'os_cpes.1_1'], dtype='object', length=391)

根据结果数据,我可以根据Scikit Learn example运行交叉验证来递归递归功能:

产生:

Cross Validated Score vs Features Graph

鉴于已识别的最佳功能数量为8,如何识别功能名称?我假设我可以将它们提取到一个新的DataFrame中用于分类算法?

[编辑]

this post

的帮助下,我已达到以下目的
def column_index(df, query_cols):
    cols = df.columns.values
    sidx = np.argsort(cols)
    return sidx[np.searchsorted(cols, query_cols, sorter = sidx)]

feature_index = []
features = []
column_index(X_dev_train, X_dev_train.columns.values)

for num, i in enumerate(rfecv.get_support(), start=0):
    if i == True:
        feature_index.append(str(num))

for num, i in enumerate(X_dev_train.columns.values, start=0):
    if str(num) in feature_index:
        features.append(X_dev_train.columns.values[num])

print("Features Selected: {}\n".format(len(feature_index)))
print("Features Indexes: \n{}\n".format(feature_index))
print("Feature Names: \n{}".format(features))

产生:

Features Selected: 8
Features Indexes: 
['5', '6', '20', '26', '27', '28', '67', '98']
Feature Names: 
['port_21', 'port_22', 'port_199', 'port_512', 'port_513', 'port_514', 'port_3306', 'port_32768']

鉴于一个热编码引入了多重共线性,我不认为目标列选择是理想的,因为它选择的特征是非编码的连续数据特征。我尝试重新添加目标列未编码,但RFE抛出以下错误,因为数据是分类的:

ValueError: could not convert string to float: Wireless Access Point

我是否需要将多个热编码功能列分组才能充当目标?

[编辑2]

如果我只是对目标列进行LabelEncode,我可以将此目标用作' y'见example again。但是,输出仅将单个要素(目标列)确定为最佳。我想这可能是因为一个热门编码,我应该考虑生成密集数组,如果是这样,它可以针对RFE运行吗?

谢谢,

亚当

2 个答案:

答案 0 :(得分:0)

回答我自己的问题,我发现问题与我对热门数据编码的方式有关。最初,我对所有分类列运行了一个热编码,如下所示:

ohe_df = pd.get_dummies(df[df.columns])              # One-hot encode all columns

这引入了大量附加功能。采用不同的方法,在here的帮助下,我修改了编码,以按列/功能为基础对多列进行编码,如下所示:

cf_df = df.select_dtypes(include=[object])      # Get categorical features
nf_df = df.select_dtypes(exclude=[object])      # Get numerical features
ohe_df = nf_df.copy()

for feature in cf_df:
    ohe_df[feature] = ohe_df.loc[:,(feature)].str.get_dummies().values.tolist()

产:

ohe_df.head(2)      # Only showing a subset of the data
+---+---------------------------------------------------+-----------------+-----------------+-----------------------------------+---------------------------------------------------+
|   |                      os_name                      |    os_family    |     os_type     |             os_vendor             |                     os_cpes.0                     |
+---+---------------------------------------------------+-----------------+-----------------+-----------------------------------+---------------------------------------------------+
| 0 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... | [0, 1, 0, 0, 0] | [1, 0, 0, 0, 0] | [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0] | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, ... |
| 1 | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... | [0, 0, 0, 1, 0] | [0, 0, 0, 1, 0] | [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0] | [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... |
+---+---------------------------------------------------+-----------------+-----------------+-----------------------------------+---------------------------------------------------+

不幸的是,尽管这是我正在寻找的,但它并没有针对RFECV执行。接下来我想也许我可以把所有新功能切片并作为目标传递,但这导致了错误。最后,我意识到我必须遍历所有目标值并从每个目标值中获取最高输出。代码最终看起来像这样:

for num, feature in enumerate(features, start=0):

    X = X_dev_train
    y = X_dev_train[feature]

    # Create the RFE object and compute a cross-validated score.
    svc = SVC(kernel="linear")
    # The "accuracy" scoring is proportional to the number of correct classifications
    # step is the number of features to remove at each iteration
    rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(kfold), scoring='accuracy')
    try:
        rfecv.fit(X, y)

        print("Number of observations in each fold: {}".format(len(X)/kfold))
        print("Optimal number of features : {}".format(rfecv.n_features_))

        g_scores = rfecv.grid_scores_
        indices = np.argsort(g_scores)[::-1]

        print('Printing RFECV results:')
        for num2, f in enumerate(range(X.shape[1]), start=0):
            if g_scores[indices[f]] > 0.80:
                if num2 < 10:
                    print("{}. Number of features: {} Grid_Score: {:0.3f}".format(f + 1, indices[f]+1, g_scores[indices[f]]))

        print "\nTop features sorted by rank:"
        results = sorted(zip(map(lambda x: round(x, 4), rfecv.ranking_), X.columns.values))
        for num3, i in enumerate(results, start=0):
            if num3 < 10:
                print i

        # Plot number of features VS. cross-validation scores
        plt.rc("figure", figsize=(8, 5))
        plt.figure()
        plt.xlabel("Number of features selected")
        plt.ylabel("CV score (of correct classifications)")
        plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
        plt.show()

    except ValueError:
        pass

我确定这可能更干净,甚至可以在一张图中绘制,但它对我有用。

干杯,

答案 1 :(得分:0)

您可以这样做:

`
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
rfe = RFE(model, 5) 
rfe = rfe.fit(X, y)
print(rfe.support_)
print(rfe.ranking_)
f = rfe.get_support(1) #the most important features
X = df[df.columns[f]] # final features`

然后,您可以将X用作神经网络或任何算法的输入

相关问题