1、LabelEncoder
from sklearn.preprocessing import LabelEncoder
cat_features = ['category', 'currency', 'country']
encoder = LabelEncoder()
#Apply the label encoder to each column
encoded = ks[cat_features].apply(encoder.fit_transform)
2、CountEncoder
介绍:
Count encoding replaces each categorical value with the number of times it appears in the dataset. For example, if the value “GB” occured 10 times in the country feature, then each “GB” would be replaced with the number 10.
使用:
import category_encoders as ce
cat_features = ['category', 'currency', 'country']
#Create the encoder
count_enc = ce.CountEncoder()
#Transform the features, rename the columns with the _count suffix, and join to dataframe
count_encoded = count_enc.fit_transform(ks[cat_features])
data = data.join(count_encoded.add_suffix("_count"))
3、TargetEncoder
介绍:
Target encoding replaces a categorical value with the average value of the target for that value of the feature. For example, given the country value “CA”, you’d calculate the average outcome for all the rows with country == ‘CA’, around 0.28. This is often blended with the target probability over the entire dataset to reduce the variance of values with few occurences.
使用:
target_enc = ce.TargetEncoder(cols=cat_features)
target_enc.fit(train[cat_features], train['outcome'])
#Transform the features, rename the columns with _target suffix, and join to dataframe
train_TE = train.join(target_enc.transform(train[cat_features]).add_suffix('_target'))
valid_TE = valid.join(target_enc.transform(valid[cat_features]).add_suffix('_target'))
4、CatBoostEncoder
介绍:
This is similar to target encoding in that it’s based on the target probablity for a given value. However with CatBoost, for each row, the target probability is calculated only from the rows before it.
使用:
#Create the encoder
target_enc = ce.CatBoostEncoder(cols=cat_features)
target_enc.fit(train[cat_features], train['outcome'])
#Transform the features, rename columns with _cb suffix, and join to dataframe
train_CBE = train.join(target_enc.transform(train[cat_features]).add_suffix('_cb'))
valid_CBE = valid.join(target_enc.transform(valid[cat_features]).add_suffix('_cb'))