'enc.active_features_'에 해당되는 글 1건

  1. 2016.12.18 [Python] 범주형 변수의 이항변수화 : sklearn.preprocessing.OneHotEncoder()

지난번 포스팅에서는 Python sklearn.preprocessing.Binarizer() 를 사용해서 연속형 변수를 이항변수로 변환하는 방법을 소개하였습니다.

 

이번 포스팅에서는 Python sklearn.preprocessing.OneHotEncoder()를 사용해서 범주형 변수를 이항변수화(binarization of categorical feature) 하는 방법을 알아보겠습니다.

 

가령, 성별(gender)가 '남성(Male)'이면 '0', '여성(Female)'이면 '1'로 encoding 하고,

연령대(age group)가 '20대'이면 '0', '30대'이면 '1', '40대'이면 '2'로 encoding 하고,

등급(grade)가 'S'이면 '0', 'A'이면 '1', 'B'이면 '2', 'C'이면 '3', 'D'이면 '4'로 encoding 한다고 했을 때,

 

이를 value로 '0'과 '1'만을 가진 가변수(dummy variable)로 바꾸는 이항변수화했을 때의 예시가 아래의 이미지입니다.  이것을 Python은 자동으로(auto) 변수별 범주(catogory)의 종류, 개수를 파악해서 이항변수화 해줍니다. 아주 편해요.

 

 

 

 

위의 이미지에 나타난 예제 데이터를 가지고 sklearn.preprocessing.OneHotEncoder() 예를 들어보겠습니다.

 

먼저, 필요한 모듈을 불러오고, 예제 데이터 arrary를 만들어보겠습니다.

 

 

# importing modules

In [1]: from sklearn.preprocessing import OneHotEncoder


In [2]: import numpy as np

 


# making an example data arrary

In [3]: data_train = np.array([[0, 0, 0],

   ...: [0, 1, 1],

   ...: [0, 2, 2],

   ...: [1, 0, 3],

   ...: [1, 1, 4]])

   ...:


In [4]: data_train

Out[4]:

array([[0, 0, 0],
       [0, 1, 1],
       [0, 2, 2],
       [1, 0, 3],
       [1, 1, 4]])

 

 

 

 

  (1) OneHotEncoder() 로 범주형 변수의 이항변수화 적합시키기 : enc.fit()

 

 

# making the utility class OneHotEncoder

In [5]: enc= OneHotEncoder()

 

# fitting OneHotEncoder

In [6]: enc.fit(data_train)

Out[6]:

OneHotEncoder(categorical_features='all', dtype=<class 'float'>,

handle_unknown='error', n_values='auto', sparse=True)

 

 

 

 

  (2) 적합된(fitted) OneHotEncoder()의 Attributes 확인해보기

       : enc.active_features_ , enc.n_values_ , enc.feature_indices_

 

위의 이미지로 예를 들어보였던 범주형 변수의 '변환 이전' => 이항변수화 '변환 이후' 모습을 보면서 아래의 Attributes 결과를 비교해보면 이해하기가 수월할 거예요.

 


# Attributes : active_features_
#               - Indices for active features, actually occur in the training set

In [7]: enc.active_features_

Out[7]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64)

# 부연설명:  [남, 여, 20대, 30대, 40대, S, A, B, C, D]

 


# Attributes : n_values_
#                - Number of values per feature

In [8]: enc.n_values_

Out[8]: array([2, 3, 5])

# 부연설명: [성별 2개 범주, 연령대 3개 범주, 등급 5개 범주] 


# Attributes : feature_indices_
#                - Indices to feature ranges

In [9]: enc.feature_indices_

Out[9]: array([ 0, 2, 5, 10], dtype=int32)

# 부연설명: [성별 0이상~2미만, 연령대 2이상~5미만, 등급 5이상~10미만]

 

 

 

 

  (3) 적합된 OneHotEncoder()로 새로운 범주형 데이터셋을 이항변수화 변환하기

 

성별 '여성(1)', 연령대 '40대(2)', 등급 'D(4)' 의 범주형 속성을 가진 새로운 고객에 대해서 위의 (1)번에서 적합시킨 OneHotEncoder()의 enc.transform(new data).toarray()를 사용해서 이항변수화 시켜보겠습니다.

 

 

# new data : femail, age_group 40s, D grade

In [10]: data_new = np.array([[1, 2, 4]])

 

# applying OneHotEncoder to new data, returning array

In [11]: enc.transform(data_new).toarray()

Out[11]: array([[ 0., 1., 0., 0., 1., 0., 0., 0., 0., 1.]])

 

 

 

다음번 포스팅에서는 Python으로 연속형 변수를 다수개의 범주로 구분하는 이산형화(discretization) 방법에 대해서 알아보겠습니다.

 

많은 도움 되었기를 바랍니다.

 

 

728x90
반응형
Posted by Rfriend
,