1). Count Encoding
Count encoding是将分类特征替换为它们的出现次数,比如某个分类中'Peking'出现了10次,那么'Peking'就会被替换为10. 我们可以用categorical-encodings
包中的CountEncoder
实现。
import category_encoders as ce
features = ['Peking', 'Peking', 'Shanghai', 'Peking', 'Guangzhou', 'Shanghai']
count_enc = ce.CountEncoder()
count_enc.fit_transform(features)
返回(第一列是索引): 0 3 1 3 2 2 3 3 4 1 5 2
2). Target Encoding target encoding其实就是将分类特征替换为对应目标值的后验概率。比如以下例子:
第三列编码值的计算过程其实很简单,比如说cat出现次数是5次,5次中target是1的次数有2次,因为编码值为0.4 。
代码语言:javascript复制import pandas as pd
from category_encoders import TargetEncoder
encoder = TargetEncoder()
df['Encoded Animal '] = encoder.fit_transform(df['Animal'], df['Target'])
参考:https://medium.com/analytics-vidhya/target-encoding-vs-one-hot-encoding-with-simple-examples-276a7e7b3e64