Feature categoriche

Vincere una competizione Kaggle con Python

Yauhen Babakhin

Kaggle Grandmaster

Label encoding

ID Feature categorica
1 A
2 B
3 C
4 A
5 D
6 A
ID Label encoding
1 0
2 1
3 2
4 0
5 3
6 0
Vincere una competizione Kaggle con Python

Label encoding

# Importa LabelEncoder
from sklearn.preprocessing import LabelEncoder

# Crea un oggetto LabelEncoder le = LabelEncoder()
# Esegui l'encoding di una feature categorica 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
Vincere una competizione Kaggle con Python

One-Hot encoding

ID Feature categorica
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
Vincere una competizione Kaggle con Python

One-Hot encoding

# Crea feature One-Hot
ohe = pd.get_dummies(df['cat'], prefix='ohe_cat')

# Rimuovi la feature iniziale df.drop('cat', axis=1, inplace=True)
# Concatena le feature OHE al 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
Vincere una competizione Kaggle con Python

Feature binarie

# DataFrame con una feature binaria
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
Vincere una competizione Kaggle con Python

Altri metodi di encoding

  • Backward Difference Coding
  • BaseN
  • Binary
  • CatBoost Encoder
  • Hashing
  • Helmert Coding
  • James-Stein Encoder
  • Leave One Out
  • M-estimate
  • One Hot
  • Ordinale
  • Polynomial Coding
  • Sum Coding
  • Target Encoder
  • Weight of Evidence
Vincere una competizione Kaggle con Python

Altri metodi di encoding

  • Backward Difference Coding
  • BaseN
  • Binary
  • CatBoost Encoder
  • Hashing
  • Helmert Coding
  • James-Stein Encoder
  • Leave One Out
  • M-estimate
  • One Hot
  • Ordinale
  • Polynomial Coding
  • Sum Coding
  • Target Encoder
  • Weight of Evidence
Vincere una competizione Kaggle con Python

Ayo berlatih!

Vincere una competizione Kaggle con Python

Preparing Video For Download...