【Python学习】LabelEncoder、CountEncoder、TargetEncoder、CatBoostEncoder

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'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值