Data Preprocessing (Label Encoder, One-Hot Encoder)

2021. 4. 13. 11:05·[AI] - Machine Learning

데이터 전처리는 머신러닝 알고리즘만큼 중요하다. 어떻게 처리하느냐에 따라 모델의 성능을 좌지우지 한다. 이번에는 사이킷런에서 제공하는 전처리 방법인 Label Encoder와 One-Hot Encoder에 대해 포스팅한다.

 

# Label Encoding
from sklearn.preprocessing import LabelEncoder

items = ['TV', '냉장고', '전자레인지', '컴퓨터']

encoder = LabelEncoder()
encoder.fit(items)
labels = encoder.transform(items)
print(labels)
print(encoder.classes_)
print(encoder.inverse_transform(labels))

>>
[0 1 2 3]

['TV' '냉장고' '전자레인지' '컴퓨터']

['TV' '냉장고' '전자레인지' '컴퓨터']

기본적으로 인코더는 fit() 메소드와 transfrom() 메소드를 통해 데이터를 인코딩한다.  labels를 출력한 것을 보면 알겠지만, 각 클래스를 정수형 데이터로 인코딩했다. 인코더의 classes_ 속성을 통해 각 클래스의 이름을 확인할 수 있다. 인코더의 inverse_transform() 메소드를 사용하면 인코딩된 데이터를 디코딩할 수 있다.

 

Label Encoder는 문자열 iterator를 순서대로 숫자로 매핑한다. 하지만 이로인해 특정 알고리즘에서는 성능이 떨어진다. 그 이유는 숫자가 오름차순으로 매핑됨에 의해 가중치가 부여되는 현상이 발생하기 때문이다. 이는 단순 코드이지, 중요도로 인식되서는 안된다. (트리계열 알고리즘은 OK) 고로 이러한 문제를 해결하기 위한 방식은 원-핫 인코딩이다.

 

# One-Hot Encoding
from sklearn.preprocessing import OneHotEncoder

# 먼저 숫자 값으로 변환을 위해 LabelEncoder 사용
encoder = LabelEncoder()
encoder.fit(items)
labels = encoder.transform(items)
labels = labels.reshape(-1, 1)  # 2차원 데이터로 변환
# One-Hot Encoder 사용
oh_encoder = OneHotEncoder()
oh_encoder.fit(labels)
oh_labels = oh_encoder.transform(labels)
print(oh_labels)
print(type(oh_labels))
print(oh_labels.shape)
print(oh_labels.toarray())

>>
# print(oh_labels)
  (0, 0)	1.0
  (1, 1)	1.0
  (2, 2)	1.0
  (3, 3)	1.0
  
# print(type(oh_labels))
<class 'scipy.sparse.csr.csr_matrix'>

# print(oh_labels.shape)
(4, 4)

# print(oh_labels.toarray())
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

One-Hot Encoder의 주의사항을 먼저 살펴보자.

1. 원-핫 인코더는 변환하기 전 모든 문자열 값이 숫자형으로 변환되어야 한다.
2. 원-핫 인코더는 입력값이 2차원 데이터가 필요하다.

 

One-Hot Encoder는 새로운 피처를 추가하여 고여 값에 해당하는 컬럼만 1, 나머지는 0으로 표기하는 방식이다. 마지막의 oh_labels.toarray()를 보면 알겠지만, 각 클래스가 해당하는 컬럼에만 1이 부여되고 나머지는 0이 부여된 것이다. 

 

pandas에서는 DataFrame을 통해 One-Hot Encoding을 쉽게 해주는 API를 제공한다.

import pandas as pd

df = pd.DataFrame({'item': ['TV', '냉장고', '전자레인지', '컴퓨터']})
oh_df = pd.get_dummies(df)
print(df)
print(oh_df)

>>
    item
0     TV
1    냉장고
2  전자레인지
3    컴퓨터

   item_TV  item_냉장고  item_전자레인지  item_컴퓨터
0        1         0           0         0
1        0         1           0         0
2        0         0           1         0
3        0         0           0         1

'[AI] - Machine Learning' 카테고리의 다른 글

정확도와 오차행렬 (Accuracy and Confusion matrix)  (0) 2021.10.11
Feature Scaling and Normalization (StandardScaler, MinMaxScaler)  (0) 2021.04.16
GridSearchCV  (0) 2021.04.12
Stratified K 폴드  (0) 2021.04.01
교차 검증 (K-폴드 교차 검증)  (0) 2021.04.01
'[AI] - Machine Learning' 카테고리의 다른 글
  • 정확도와 오차행렬 (Accuracy and Confusion matrix)
  • Feature Scaling and Normalization (StandardScaler, MinMaxScaler)
  • GridSearchCV
  • Stratified K 폴드
Bebsae
Bebsae
  • Bebsae
    뱁새zip
    Bebsae
  • 전체
    오늘
    어제
    • 분류 전체보기 (108)
      • [DevOps] - Kubernetes (5)
      • [DevOps] - AWS (1)
      • [AI] - Machine Learning (19)
      • [AI] - Neural Network (7)
      • [CS] - Network (2)
      • [CS] - Data Structure (3)
      • [CS] - Design Pattern (6)
      • [Language] - Python (15)
      • [Library] - Numpy (7)
        • Quick Start (5)
        • API (2)
      • [Framework] - Django (3)
      • [Framework] - QGIS (6)
      • [Framework] - PyQT (4)
      • [Mathematics] - Linear Alge.. (14)
      • [Mathematics] - Statistical (2)
      • [ETC] - Python (3)
      • [ETC] - C++ (1)
      • [ETC] - Linux (1)
      • 논문 (5)
      • 회고록 (3)
      • 생산성 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    Linear
    디자인패턴
    Convolution
    Machine
    Learning
    MachineLearning
    QGIS
    Python
    파이썬
    분해
    RNN
    교차검증
    algebra
    decomposition
    선형대수
    numpy
    linearalgebra
    DEEPLEARNING
    신경망
    머신러닝
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Bebsae
Data Preprocessing (Label Encoder, One-Hot Encoder)
상단으로

티스토리툴바