0

私は、124の特徴を持つカテゴリと数値のデータからなるデータセットを持っています。その次元を減らすために、私は無関係の特徴を取り除きたい。しかし、私は1つのホットとして、私はクロスバリデーションと再帰的な特徴の排除を実行することができ、結果のデータでは391再帰的特徴除去(RFE)から最適な特徴を抽出する

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) 

に機能の数を増加get_dummies、とそれをコードする特徴選択アルゴリズムに対してデータセットを実行します生成

Scikit Learn exampleごと

Cross Validated Score vs Features Graph

は、識別された特徴の最適な数は、8だったどのように私は機能名を特定しないことを考えると?私は分類アルゴリズムで使用するためにそれらを新しいDataFrameに抽出できると仮定していますか?


[EDIT]

次のように私は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'] 

を1つのホットエンコードは多重共を紹介することを考えると、私はターゲット列の選択が理想的ではないと思います非符号化連続データ機能が選択されています。私は、エンコードされていない再追加するターゲット列を試してみましたが、データがカテゴリであるため、RFEは、次のエラーがスローされます。

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

私は1つのホットエンコードされた機能の列がターゲットとして機能するグループの複数のする必要がありますか?


[EDIT 2]

Iは、単にターゲット列をLabelEncode場合は 'Y' example againを参照として、私はこのターゲットを使用することができます。ただし、出力は単一のフィーチャ(ターゲット列)のみを最適と判断します。私はこれが1つのホットエンコーディングのためかもしれないと思っています。密な配列を作りたいのであれば、それはRFEに対して実行できますか?

おかげで、自分の質問に答える

アダム

答えて

0

は、私は問題は、私は、データをワンホットエンコードされた方法に関連していた考え出しました。最初に、次のようにすべてのカテゴリ型の列に対して1つのホットエンコーディングを実行しました。これにより、多数の追加機能が導入されました。

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, ... | 
+---+---------------------------------------------------+-----------------+-----------------+-----------------------------------+---------------------------------------------------+ 

残念なことにが、次のようにhereからいくつかの助けを借りて、異なるアプローチを取って、Iは単位のカラム/特徴に基づいて複数の列を符号化する符号化を変更しましたこれは私が探していたものでしたが、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つのグラフにプロットすることができるが、それは私のために動作します。

乾杯、

関連する問題