類別型特徵

用 Python 拿下 Kaggle 競賽

Yauhen Babakhin

Kaggle Grandmaster

標籤編碼(Label encoding)

ID 類別型特徵
1 A
2 B
3 C
4 A
5 D
6 A
ID 標籤編碼
1 0
2 1
3 2
4 0
5 3
6 0
用 Python 拿下 Kaggle 競賽

標籤編碼(Label encoding)

# Import LabelEncoder
from sklearn.preprocessing import LabelEncoder

# Create a LabelEncoder object le = LabelEncoder()
# Encode a categorical feature df['cat_encoded'] = le.fit_transform(df['cat'])
     ID   cat  cat_encoded
0     1   A    0
1     2   B    1
2     3   C    2
3     4   A    0
用 Python 拿下 Kaggle 競賽

One-Hot 編碼

ID 類別型特徵
1 A
2 B
3 C
4 A
5 D
6 A
ID Cat == A Cat == B Cat == C Cat == D
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
4 1 0 0 0
5 0 0 0 1
6 1 0 0 0
用 Python 拿下 Kaggle 競賽

One-Hot 編碼

# Create One-Hot encoded features
ohe = pd.get_dummies(df['cat'], prefix='ohe_cat')

# Drop the initial feature df.drop('cat', axis=1, inplace=True)
# Concatenate OHE features to the dataframe df = pd.concat([df, ohe], axis=1)
     ID ohe_cat_A ohe_cat_B ohe_cat_C ohe_cat_D
0     1         1         0         0         0
1     2         0         1         0         0
2     3         0         0         1         0
3     4         1         0         0         0
用 Python 拿下 Kaggle 競賽

二元特徵

# DataFrame with a binary feature
binary_feature
      binary_feat
0     Yes
1     No
le = LabelEncoder()
binary_feature['binary_encoded'] = le.fit_transform(binary_feature['binary_feat'])
  binary_feat binary_encoded
0     Yes     1
1     No      0
用 Python 拿下 Kaggle 競賽

其他編碼方法

  • 反差分編碼(Backward Difference Coding)
  • BaseN
  • 二進位
  • CatBoost 編碼器
  • 雜湊(Hashing)
  • Helmert 編碼
  • James-Stein 編碼器
  • Leave-One-Out(留一法)
  • M-estimate(M 估計)
  • One Hot
  • 序數
  • 多項式編碼
  • 和編碼(Sum Coding)
  • 目標編碼(Target Encoder)
  • 證據權重(Weight of Evidence)
用 Python 拿下 Kaggle 競賽

其他編碼方法

  • 反差分編碼(Backward Difference Coding)
  • BaseN
  • 二進位
  • CatBoost 編碼器
  • 雜湊(Hashing)
  • Helmert 編碼
  • James-Stein 編碼器
  • Leave-One-Out(留一法)
  • M-estimate(M 估計)
  • One Hot
  • 序數
  • 多項式編碼
  • 和編碼(Sum Coding)
  • 目標編碼(Target Encoder)
  • 證據權重(Weight of Evidence)
用 Python 拿下 Kaggle 競賽

一起來練習吧!

用 Python 拿下 Kaggle 競賽

Preparing Video For Download...