[변수 선택] Python에서 변수 전처리 및 변형 해주는 Xverse 패키지 소개

2020. 3. 22. 16:01분석 Python/Data Preprocessing

728x90

광고 한번만 눌러주세요 ㅎㅎ 블로그 운영에 큰 힘이 됩니다.

Xverse는 X Universe를 줄인 말로, 특징 변환과 특징 선택을 통해 데이터 과학자를 지원하기 위한 기계 학습을 위한 Python 패키지입니다. 일단 필요성에 대해서 말하고자 한다고 합니다.

Background

대부분의 데이터 분석가는 80%는 분석 전처리에 쓰고 있다고 한다. 

Earlier works for this package

https://medium.com/@sundarstyles89/weight-of-evidence-and-information-value-using-python-6f05072e83eb

 

Weight of evidence and Information Value using Python

Weight of evidence (WOE) and Information value (IV) are simple, yet powerful techniques to perform variable transformation and selection…

medium.com

“Weight of evidence (WOE) and Information value (IV) are simple, yet powerful techniques to perform 
variable transformation and selection
. These concepts have huge connection with the logistic regression modeling technique. It is widely used in credit scoring to measure the separation of good vs bad customers.”

https://medium.com/@sundarstyles89/variable-selection-using-python-vote-based-approach-faa42da960f0

 

Variable Selection using Python — Vote based approach

Variable selection is one of the key process in predictive modeling process. It is an art. To put is simple terms, variable selection is…

medium.com

“The idea is to apply a variety of techniques to select variables. When an algorithm picks a variable, we give a vote for the variable. At the end, we calculate the total votes for each variables and then pick the best ones based on votes. This way, we end up picking the best variables with minimum effort in the variable selection process.”

Functionalities

https://github.com/Sundar0989/XuniVerse

 

Sundar0989/XuniVerse

xverse (XuniVerse) is collection of transformers for feature engineering and feature selection - Sundar0989/XuniVerse

github.com

위의 github 주소에서 패키지가 있고, Xverse.ipynb를 확인해보면 된다고 합니다.


1. Monotonic Binning

Monotonic Binning은 scorecard 개발에서 넓게 사용되는 data preparation 기술입니다. 
Monotonic Binning은 타깃과의 monotonic 관계를 가지는 bin을 생성함으로써, 수치형 변수를 범주형 변수로 전환해줍니다. 

변수 "balance"는 $-3,313.001 ~ $71.188까지의 범위를 보여준다. 이것은 굉장히 넓은 범위인 것을 모두 동의할 것입니다. 만약 우리가 도메인 지식을 기반으로 변수를 bin 한다면, monotonic 관계에 대해서 걱정할 필요가 없습니다. 
그러나 사전 지식이 존재하지 않을 때, bin 범주를 결정하는 것은 어렵습니다.
이것은 monotonic binning이 도움이 될 수 있는 이상적인 상황입니다. 보통 우리는 모든 도메인 지식을 가지고 있지 않기 때문에, 이러한 관계를 알아서 잘 만들어주는 변수를 만들어주는 기술이 필요할 겁니다.

Pros in Monotonic Binning:

  1. Handle outliers
  2. Establish a monotonic relationship between a feature and target variable

Cons in Monotonic Binning:

  1. We lose information during variable binning
  2. No proper way to treat missing values

Xverse를 사용해서 Monotonic Binning을 어떻게 수행할 수 있을까요?

from xverse.transformer import MonotonicBinning

clf = MonotonicBinning()
clf.fit(X, y)

print(clf.bins)
output_bins = clf.bins #will be used later in this exercise

X는 feature dataset으로 즉 binning 하고자 하는 변수들을 넣으면 될 것입니다.

clf = MonotonicBinning(custom_binning=output_bins) #output_bins was created earlier

out_X = clf.transform(X)
out_X.head()


2. Weight of Evidence(WOE) and Information Value(IV)

The WOE package is available in the transformer function. The advantages of WOE transformation are

  1. Handles missing values
  2. Handles outliers
  3. The transformation is based on logarithmic value of distributions. This is aligned with the logistic regression output function
  4. No need for dummy variables
  5. By using proper binning technique, it can establish monotonic relationship (either increase or decrease) between the independent and dependent variable
  6. IV value can be used to select variables quickly.

WOE는 미싱을 처리할 수 있으며, 뿐만 아니라 Outlier 그리고 log 변환을 해주며, 그리고 더미 변수로 만들 필요가 있다고 합니다! (거의 만능..?)

How to perform WOE using “Xverse”?

from xverse.transformer import WOE
clf = WOE()
clf.fit(X, y)
clf.woe_df # weight of evidence transformation dataset. This dataset will be used in making bivariate charts as well. 
clf.iv_df #information value dataset

How to apply WOE transformation on future dataset?

output_woe_bins = clf.woe_bins #future transformation
output_mono_bins = clf.mono_custom_binning  #future transformation
clf = WOE(woe_bins=output_woe_bins, mono_custom_binning=output_mono_bins) #output_bins was created earlier
out_X = clf.transform(X)

오... custom까지 가능하다니 좋아 보입니다.

Additional features to explore in WOE package:

treat_missing: {‘separate’, ‘mode’, ‘least_frequent’} (default=’separate’)
This parameter setting is used to handle missing values in the dataset.
 ‘separate’ — Missing values are treated as a own group (category)
 ‘mode’ — Missing values are combined with the highest frequent item in the dataset
 ‘least_frequent’ — Missing values are combined with the least frequent item in the dataset

음 결측치는 결국에... 결측치는 일반론적인 특정 상수 대체, 최빈값과 같은 걸로 한다고 한다... 특별한 처리를 해주는 것은 아닌 것 같습니다. ㅠㅠ


3. Bar Charts for Bivariate distributions

Bivariate distributions help us explore relationship between X and y variables. This option is available in “xverse” as well.

How to chart using “Xverse”?

To make bivariate charts, we need the “woe_df” dataset generated from the WOE option shown above.

woe_df = clf.woe_df
from xverse.graph import BarCharts
clf = BarCharts(bar_type='v')
clf.plot(woe_df)

Additional features to explore in Bar charts:

plot_metric: 'count' or 'mean' (default='mean')
        Metric to be used while plotting the bivariate chart.
        'count' - Event counts in the particular bin
        'mean' - Mean event rate in the particular bin
bar_type: 'horizontal' or 'vertical' (default='vertical')
        Type of bar chart.
fig_size: figure size for each of the individual plots (default=(8,6))
bar_color: CSS color style picker. Use it with the hashtag in the front. (default='#058caa')
        Bar color
        
    num_color: CSS color style picker. Use it with the hashtag in the front (default='#ed8549')
        Numbers color. It represents the numbers written on top of the bar.

 

4. Voting Selector for variable selection (변수 선택)

Variable selection is one of the key process in predictive modeling process. It is an art. To put in simple terms, variable selection is like picking a soccer team to win the World cup. You need to have the best player in each position and you don’t want two or many players who plays the same position.

파이썬에서, 변수 선택하는 다른 기술들을 가지고 있습니다. 

  • Recursive feature elimination
  • Tree-based selection
  • L1 based feature selection

이러한 기술들을 가지고 있는데, 이 패키지에서는 다양한 기술들을 적용하여 변수를 선택한다고 합니다.
알고리즘이 변수를 선택할 때, 패키지에서는 변수에 대해 투표를 합니다. 
마지막으로, 각각의 변수에 대해서 총 투표들을 계산하고, 투표를 기반으로 해서 최고의 것을 선택한다고 합니다.
최소한의 노력으로 변수 선택 과정에서 최고의 변수 선택을 할 수 있다고 합니다. 

변수 선택 투표 방식

from xverse.ensemble import VotingSelector
clf = VotingSelector()
clf.fit(X, y)
clf.feature_importances_

clf.feature_votes_

Additional features to explore in Voting Selector:

selection_techniques: 'all', 'quick' or list(default='all')
    List of selection techniques to be applied on the data. 
    Available techniques - Weight of evidence ('WOE'), Random Forest ('RF'), Recursive Feature Elimination ('RFE'), Extra Trees Classifier ('ETC'), Chi Square ('CS'), L1 feature selection ('L_ONE').
        
    'all' - Apply all selection techniques ['WOE', 'RF', 'RFE', 'ETC', 'CS', 'L_ONE']
    'quick' - ['WOE','RF','ETC']
    list - user provided list of feature selection techniques from available techniques 
    
no_of_featues: 'auto', 'sqrt' or int(default='auto')
    Number of features to be selected by each selection technique.
    'auto' - len(features)/2
    'sqrt' - sqrt(len(features)) rounded to the lowest number
    int - user provided number in integer format
    
handle_category= 'woe' or 'le' (default='woe')
    Handle category values transformation using Label encoder or Weight of Evidence option. Takes care of missing values too. It treats missing values as separate level.
    'woe' - use weight of evidence transformation
    'le' - use label encoder transformation
    
numerical_missing_values= 'median', 'mean' or 0 (default='median')
    Handle numerical variable missing values.
    'median' - use median of the column
    'mean' - use mean of the column
    0 - use 0 to impute the missing values
    
minimum_votes = int (default=0)
    Minimum number of votes needed to select a variable after feature selection. Only used in the transform process. Default value is set to 0 to select all variables.

5. Pipeline feature

마지막으로, "Xverse"의 한 가지 중요한 것은 파이프라인 기능입니다.
패키지에서 모든 단계를 파이프라인의 일부로 추가하고 우리의 삶을 훨씬 더 편하게 만들 수 있다고 합니다. 

from sklearn.pipeline import Pipeline
clf = Pipeline(steps=[('split_x_y', SplitXY(['target'])),('feature_votes', VotingSelector())])
clf.fit(df, df['target'])

적용해보기

https://github.com/Sundar0989/XuniVerse/blob/master/Xverse.ipynb

 

Sundar0989/XuniVerse

xverse (XuniVerse) is collection of transformers for feature engineering and feature selection - Sundar0989/XuniVerse

github.com

주어진 데이터로 해당 주피터를 돌리다가 특별한 것을 발견하여 발견한 것만 공유합니다.

돌린 것 중에서 WOE 관련된 것에서 특이한 점을 발견했습니다. 
만약 실제 데이터가 결측이 있을 때, 결측을 처리하는 방법을 적용한 것과 적용하지 않는 것에서 transform시 에러가 나는 것을 확인했습니다.

from xverse.transformer import WOE
custom_binning = {"AGE": np.array([10,20,30,40,50,60]) }
clf = WOE(treat_missing='separate', woe_bins=None,
          mono_feature_names= num_var , 
          monotonic_binning=True,mono_custom_binning= custom_binning)
clf.fit(XX, y)

이제 이 데이터에 대해서 transform을 하면 다음과 같은 에러가 발생한다.

clf.transform(XX.head(1))

 결측치를 그대로 있는 상태에서 데이터 변환을 해보려고 하니, TypeError가 발생하게 됩니다.
데이터가 많은 경우에는 이러한 문제가 발생하지 않습니다.

그래서 안에 있는 값을 확인해보니, na값이 string으로 되어있습니다. 

그래서 저걸 NA로 바꿔봤지만,,, 동일한 에러가 발생합니다.

그래서 treat_missing을 separate -> mode 같이 다른 것으로 바꾸니, 잘 작동하는 것을 확인하였습니다.

## treat_missing을 그냥 놔두면 에러가 나지만, 다른 것에서는 에러가 안남.
clf = WOE(treat_missing='mode',
          mono_feature_names = num_var , 
         )
clf.fit(XX, y)
clf.transform(XX.head(1))

실제 하나만 해도 잘 작동하고, 결측이 있는 부분은 결측으로 남고? 처리가 되네요.

이제 VotingSelector를 사용해서 변수 선택을 해보자.

from xverse.ensemble import VotingSelector
clf = VotingSelector(handle_category='woe',
                     numerical_missing_values='median')
clf.fit(XX, y)

일단 아래 예제에서는 변수 선택보다는 결측치 대체와 범주형 변수가 woe로 처리된 결과에 대해서는 다음과 같습니다.
처리된 것을 확인할 수 있습니다.

여기서 Voting 결과를 확인해보자. 그러면 PAY_0 , PAY_AMT1은 6개의 알고리즘에서 중요하다고 나온 것을 확인하였다.
이제 그러면 여기서 투표가 3개 이상된 것만 뽑아보자.

minimum_votes로 제한을 하니, transform에서 선택되는 변수는 PAY_AMT3까지 선택되는 것을 확인하였습니다.

clf.minimum_votes = 3
clf.transform(XX).head()

>> 일단 monotonic binding과 같이 자동으로 binning을 해준다는 것이 쓸모가 있어 보이고, woe 기법을 통해서 binning도 적절하게 하면서 동시에, category variable도 더미 변수화 할 필요도 없어진다고 합니다. 
그래서 IV라는 값을 사용해서 변수 선택까지 할 수 있으니, 괜찮은 방법론인 것 같습니다. 
가장 인상 깊은 것은 voting 기법을 통해 여러 가지 변수 선택 테크닉을 종합적으로 해보고, 뽑을 수 있는 것 같아 아주 쓸만해 보입니다.

 

728x90