0

124 개의 기능이있는 범주 형 및 숫자 형 데이터로 구성된 데이터 집합이 있습니다. 차원을 줄이기 위해 관련없는 기능을 제거하고 싶습니다. 그러나, 피쳐 선택 알고리즘에 대한 데이터 세트를 실행하는 I 핫 같이 I 교차 검증과 재귀 기능 제거를 실행 결과 데이터 (391)RFE (Recursive Feature Elimination)에서 최적의 기능 추출

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으로 추출 할 수 있다고 가정합니다.


는 는

다음 I가 this post 도움으로,이를 달성 [EDIT]

: 생성

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 

내가 그룹에 뜨거운 대상으로 행동하는 기능 열을 인코딩 여러 하나가 필요하십니까?


[EDIT 2

단순히 대상 칼럼 LabelEncode 경우 'Y'example again 참조로서 I이 타겟을 사용할 수있다. 그러나 출력은 단일 피처 (목표 C 럼) 만 최적으로 판별합니다. 이것은 하나의 핫 인코딩 때문일 것으로 생각합니다. 밀집 어레이를 제작해야합니까? 그렇다면 RFE에 대해 실행할 수 있습니까?

감사합니다,

아담

답변

0

내 자신의 질문에 대답, 나는 문제는 내가 하나가 핫 데이터를 인코딩 한 방식과 관련이 알아 냈어. 처음에는 다음과 같이 모든 범주 형 열에 대해 하나의 핫 인코딩을 실행했습니다.

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

이로 인해 많은 추가 기능이 도입되었습니다.

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의 도움으로 다른 접근 방식을 가지고 가서, 나는 열 단위/기능으로 여러 열을 인코딩하는 인코딩을 수정 한 이것이 제가 검색 한 내용이었고 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 

나는이 청소기 될 수 확신이, 심지어 하나의 그래프에 그릴 수 있습니다,하지만 나를 위해 작동합니다.

건배,