[변수 선택] BorutaShap 활용 (Python)

2020. 10. 6. 20:45분석 Python/구현 및 자료

728x90

이전에도 Boruta를 이용해서 리뷰를 한 적이 있는데, 이번에는 Shap과 Brouta를 결합한 패키지를 찾게 되어서 공유한다.

 

해당 패키지의 장점이라고 생각하는 점은 일단 SHAP을 이용해서 변수 선택을 한다는 것이 가장 마음에 들었고, 

그리고 변수 선택에서 사용하는 알고리즘이 Tree Based 알고리즘은 다 되긴 하는데, XGB , CATBOOST, DT(sklearn), RF(sklearn)... ensemble method(sklearn)이다.

특히 xgb나 catboost 같이 category feature를 변환하지 않고 변수 선택 모델링할 수 있는 패키지를 사용할 수 있어서, 실제로 category에 대한 영향도를 더 잘 표현해줄 것으로 기대한다.

Algorithm

  1. Start by creating new copies of all the features in the data set and name them shadow + feature_name, shuffle these newly added features to remove their correlations with the response variable.

  2. Run a classifier on the extended data with the random shadow features included. Then rank the features using a feature importance metric the original algorithm used permutation importance as it's metric of choice.

  3. Create a threshold using the maximum importance score from the shadow features. Then assign a hit to any feature that had exceeded this threshold.

  4. For every unassigned feature preform a two sided T-test of equality.

  5. Attributes which have an importance significantly lower than the threshold are deemed 'unimportant' and are removed them from process. Deem the attributes which have importance significantly higher than than the threshold as 'important'.

  6. Remove all shadow attributes and repeat the procedure until an importance has been assigned for each feature, or the algorithm has reached the previously set limit of runs.

위를 보면 알겠지만 t-test 와 threshold를 통해서 중요하지 않는 변수를 통계적으로 분리한다는 점에서 마음에 들었다.

실제로 사용하는 방법도 매우 간단하다.

 

분류 같은 경우

from BorutaShap import BorutaShap, load_data
from xgboost import XGBClassifier

X, y = load_data(data_type='classification')
X.head()

model = XGBClassifier()

# if classification is False it is a Regression problem
Feature_Selector = BorutaShap(model=model,
                              importance_measure='shap',
                              classification=True)

Feature_Selector.fit(X=X, y=y, n_trials=100, sample=False,
            	     train_or_test = 'test', normalize=True,
		     verbose=True)

 

회귀 같은 경우

X, y = load_data(data_type='regression')
X.head()
Feature_Selector = BorutaShap(importance_measure='shap',
                              classification=False)

Feature_Selector.fit(X=X, y=y, n_trials=100, random_state=0)
Feature_Selector.plot(X_size=12, figsize=(19,8),
                      y_scale='log', which_features='all',)

importance_measure 지원되는 것은 shap과 gini이다.

if self.importance_measure == 'shap':

self.explain()
vals = self.shap_values

if normalize:
vals = self.calculate_Zscore(vals)

X_feature_import = vals[:len(self.X.columns)]
Shadow_feature_import = vals[len(self.X_shadow.columns):]


elif self.importance_measure == 'gini':

feature_importances_ =  np.abs(self.model.feature_importances_)

if normalize:
feature_importances_ = self.calculate_Zscore(feature_importances_)

X_feature_import = feature_importances_[:len(self.X.columns)]
Shadow_feature_import = feature_importances_[len(self.X.columns):]

else:

raise ValueError('No Importance_measure was specified select one of (shap, gini)')

변수 선택할 때 유용할 것 같으니 글로 남긴다!

 

 

github.com/Ekeany/Boruta-Shap

 

Ekeany/Boruta-Shap

A Tree based feature selection tool which combines both the Boruta feature selection algorithm with shapley values. - Ekeany/Boruta-Shap

github.com

data-newbie.tistory.com/494

 

Boruta 와 Lightgbm(rf)을 사용하여 변수 선택하기

광고 한 번씩 눌러주세요! 블로그 운영에 큰 힘이 됩니다 :) Boruta는 RandomForest를 사용하여 변수 선택을 하는 함수이다. 하지만 파이썬에서 흔히 알고 있는 sklearn에서는 범주형에 대한 처리를 해주

data-newbie.tistory.com

다른 패키지

github.com/Jie-Yuan/FeatureSelector

 

728x90