범주형 변수 다루기

Python으로 배우는 Machine Learning 특성 공학

Robert O'Callaghan

Director of Data Science, Ordergroove

범주형 특성 인코딩

Python으로 배우는 Machine Learning 특성 공학

범주형 특성 인코딩

Python으로 배우는 Machine Learning 특성 공학

범주형 특성 인코딩

  • 원-핫 인코딩
  • 더미 인코딩
Python으로 배우는 Machine Learning 특성 공학

원-핫 인코딩

pd.get_dummies(df, columns=['Country'], 
               prefix='C')
    C_France    C_India    C_UK    C_USA
0          0          1       0        0
1          0          0       0        1
2          0          0       1        0
3          0          0       1        0
4          1          0       0        0
Python으로 배우는 Machine Learning 특성 공학

더미 인코딩

pd.get_dummies(df, columns=['Country'],
               drop_first=True, prefix='C')
     C_India    C_UK    C_USA
0          1       0        0
1          0       0        1
2          0       1        0
3          0       1        0
4          0       0        0
Python으로 배우는 Machine Learning 특성 공학

원-핫 vs 더미

  • 원-핫 인코딩: 해석하기 쉬운 특성
  • 더미 인코딩: 중복 없이 필요한 정보만
Python으로 배우는 Machine Learning 특성 공학
Index Sex
0 Male
1 Female
2 Male
Index Male Female
0 1 0
1 0 1
2 1 0
Index Male
0 1
1 0
2 1
Python으로 배우는 Machine Learning 특성 공학

열 수 제한하기

counts = df['Country'].value_counts()
print(counts)
'USA'      8
'UK'       6
'India'    2
'France'   1
Name: Country, dtype: object
Python으로 배우는 Machine Learning 특성 공학

열 수 제한하기

mask = df['Country'].isin(counts[counts < 5].index)

df['Country'][mask] = 'Other'
print(pd.value_counts(colors))
'USA'      8
'UK'       6
'Other'    3
Name: Country, dtype: object
Python으로 배우는 Machine Learning 특성 공학

이제 범주형 변수를 다룰 수 있습니다

Python으로 배우는 Machine Learning 특성 공학

Preparing Video For Download...