Machine learning

[데이터 전처리] . 데이터 구간화 ( Data binning )

Acdong 2020. 10. 23. 17:39
728x90

데이터의 구간을 나눠보자

  • Equal width

    값으로 구간을 나눠주는 구간화 방법

  • Equal frequency

    빈도 수로 구간을 나눠주는 구간화 방법


샘플데이터

raw_data= {'regiment':['Nighthawks','Nighthawks','Nighthawks','Nighthawks','Dragons','Dragons','Dragons','Dragons','Scouts','Scouts','Scouts','Scouts'],
          'company':['1st','1st','2nd','2nd','1st','1st','2nd','2nd','1st','1st','2nd','2nd'],
          'postTestScore':[25,94,57,62,70,25,94,57,62,70,62,70]}
df = pd.DataFrame(raw_data,columns=['regiment','company','postTestScore'])
df

postTestScore를 구간화해보자

 

구간화는 pd.cat( ) 함수를 이용하면 쉽게 처리할 수 있다.

bins = [0,25,50,75,100] # Define bins as 0 to 25, 25 to 50, 60 to 75, 75 to 100
group_names = ['Low','Okay','Good','Great'] #구간명
categorise = pd.cut(df['postTestScore'],bins,labels=group_names)
# Cut 후 categirues에 할당
df['categorise'] = categorise
df


sklearn 패키지로 구간화 하기

구간화 역시 sklearn 에 preprocessing 을 통해서 사용할 수 있다.

from sklearn import preprocessing
le = preprocessing.LabelEncoder()

먼저 라벨인코더 객체를 생성합니다.

raw_example = df.values
data = raw_example.copy()

데이터 프레임의 값들을 복사하여 사용합니다.

le.fit(raw_example[:,0])

해당 규칙을 fitting 합니다. (기억합니다. )

#데이터 라벨링
le.transform(raw_example[:,0])

transform을 통해 규칙을 기반으로 데이터를 변환합니다.

#데이터 변경하기
data[:,0] = le.transform(raw_example[:,0])
data[:3]


함수로 구현

label_column = [0,1,2,3]
lable_enconder_list = []
for column_index in label_column:
    le = preprocessing.LabelEncoder()
    le.fit(raw_example[:,column_index])
    data[:,column_index] = le.transform(raw_example[:,column_index])
    lable_enconder_list.append(le) #기존 label encoder를 따로 저장
    del le
data[:3]

함수로 모든 자료형을 구간화 해보았습니다.

lable_enconder_list[0].transform(raw_example[:10,0])

이런 식으로 따로따로 구간화 해도 됩니다.

 

 

구간화에 대해서 알아봤습니다.

데이터를 전처리할 때 구간화 역시 머신러닝을 돌리기 위해서 꼭 필요한 작업입니다.

 

반응형