파이썬 특성 자동 선택

특성 자동 선택 방법에는 두가지 방법이 있다.

SelectKBest를 사용하여 개수 만큼 특성을 선택하는 방법과

sklearn.feature_selection.SelectKBest( score_func = <함수 f_classif> , * , k = 10 )

SelectPercentile을 사용하여 입력한 비율 만큼 특성을 고르는 방법이 있다.

sklearn.feature_selection.SelectPercentile( score_func = <함수 f_classif> , * , 백분위 수 = 10 )

상황에 맞는 함수를 사용하면 되겠다.

# 특성자동선택 SelectKBest(개수), SelectPercentile(비율)
def SelectKBest(X, y, n):
  from sklearn.feature_selection import SelectKBest, chi2
  
  select = SelectKBest(chi2, k=n)
  select.fit(X, y)

  X_selected = select.transform(X)

  print("X.shape: {} ".format(X.shape))
  print("X_selected.shape: {} ".format(X_selected.shape))
  mask = select.get_support()
  print('Mask : {}'.format(mask))
  print('{}개의 pvalue 값에 따른 최고 점수의 feature : {} 선택'.format(n, list(X.iloc[:,mask].columns)))
  display(X.iloc[:,mask])

# 출력
SelectKBest(X, y, 2)

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/975e07e2-47c3-4f78-9873-1119bfb9943c/Untitled.png

추가 수정 코드 표

# 특성자동선택 SelectKBest(개수), SelectPercentile(비율)
def mySelectKBest(X, y, n):
  from sklearn.feature_selection import SelectKBest, f_regression
  
  select = SelectKBest(f_regression, k=n).fit(X, y)
  X_selected = select.transform(X)

  # 점수 표 내림 차순
  score = select.scores_
  import pandas as pd
  print('\\n점수 표 내림 차순')
  display(pd.DataFrame([score], index = ['score'], columns = X.columns).sort_values(by = 'score', axis = 1, ascending = False))

  # X 형태
  print('\\nX 형태 변환 과정')
  print("X.shape: {} ".format(X.shape))
  print("X_selected.shape: {} ".format(X_selected.shape))
  
  # 마스킹 시각화 검은 부분이 True, 흰 부분이 False
  mask = select.get_support()
  import matplotlib.pyplot as plt
  plt.matshow(mask.reshape(1, -1), cmap='gray_r')
  plt.xlabel("feature number")
  plt.yticks([0])
  plt.title("RFE")
  print('\\n마스킹 시각화. True = Black, False = White')
  plt.show()

  # 출력
  print('\\nOutput :')
  print('{}개의 pvalue 값에 따른 최고 점수의 feature : {} 선택'.format(n, list(X.iloc[:,mask].columns)))
  display(X.iloc[:,mask])

# 출력
mySelectKBest(X, y, 20)

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0bdce900-5e0d-4007-9561-6be8856f491b/Untitled.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f05f36a2-4b47-4c1f-9b90-04ff5f43bec4/Untitled.png