원
특성 자동 선택 방법에는 두가지 방법이 있다.
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)
# 특성자동선택 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)