其他分享
首页 > 其他分享> > 数据特征的编码方式

数据特征的编码方式

作者:互联网

数据的探索型分析

数据的特征探索

image

数据探索性分析需要从两种方面来看:

字段vs标签

字段vs字段

数据分布分析

有可能因为训练集和验证集分布不一样,比如出现本地和线上得分变换趋势相反的情况。

可以构造一个分类器区分训练集和验证集,如果无法分辨样本(AUC接近0.5)说明数据分布一致,否则,说明训练集和测试集分布不太一致。

特征工程基础——特征类型及处理方法

类别特征

在任何时候都要进行处理

高基数(类别多)会带来离散数据

很难进行缺失值填充

分成有序和无序的

处理过程

独热编码

优点:简单,能将类别特征进行有效编码

缺点:会带来维度爆炸和特征稀疏

标签编码

优点:简单,不添加类别的维度

缺点:会改变原始标签的次序关系

适合在树模型中使用。数模型中labelEncoder甚至优于独热编码

方法:pandas中的facotrize或sklearn上的LABELENCODER

顺序编码

按照类别大小关系进行编码

优点:简单,不增加类别的维度

缺点:需要人工知识且

df[feature].map({映射的字典})必须覆盖所有种类,但是这个方法需要覆盖所有类别

频率编码

将出现或次数频率作为编码

image

Mean/Target编码

将类别给出的标签概率作为编码,此时最后一列的含义是以该国家分类下target的平均值

image

数值特征处理方法

数值特征时最常见的连续特征,容易出现异常值和离群点

Round

形式:将数值进行缩放、取整,可以保留大部分信息

image

Binning将数值进行分箱

就和分段函数一样

image

特征过程代码处理速查

构造实验数据集如下所示:

df = pd.DataFrame({
    'student_id': [1,2,3,4,5,6,7],
    'country': ['China', 'USA', 'UK', 'Japan', 'Korea', 'China', 'USA'],
    'education': ['Master', 'Bachelor', 'Bachelor', 'Master', 'PHD', 'PHD', 'Bachelor'],
    'target': [1, 0, 1, 0, 1, 0, 1]
})

image

下面给出其特征编码方式,作为代码参考:

Onehot_code

首先我们对教育编码

pd.get_dummies(df, columns=['education'])

image

建议使用pandas库,因为操作很简单

还可以用sklearn中的OneHotEncoder方法,操作较为复杂

这里最后将得出的独热特征写入df

from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder()
labels = []
for i in range(len(df['country'].unique())):
    label = 'country_'+str(i)
    labels.append(label)
df[labels] = ohe.fit_transform(df[['country']]).toarray()

LabelEncoder

进行类型编码,可以使用LabelEncoder库

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['country_LabelEncoder'] = le.fit_transform(df['country'])
df.head(10)

image

还可以使用pandas中自带的方法

df['country_LabelEncoder'] = pd.factorize(df['country'])[0]
df.head(10)

其中,pd.factorize方法得出一个这样的结果

image

[0]为编码号,[1]为编码对应的类型

Ordinal Encoding

这里必须序号和所有出现的评级相对应,不然会报错

df['education'] = df['education'].map(
                    {'Bachelor': 1, 
                    'Master': 2, 
                    'PHD': 3})
df.head(10)

image

二进制编码

import category_encoders as ce
encoder = ce.BinaryEncoder(cols= ['country'])

pd.concat([df, encoder.fit_transform(df['country']).iloc[:, 1:]], axis=1)

image

Frequency Encoding、Count Encoding

注意这里.map函数的使用

这里是把标签出现的频率作为特征进行编码

df['country_count'] = df['country'].map(df['country'].value_counts()) / len(df)
df.head(10)

image

df['country_count'] = df['country'].map(df['country'].value_counts())
df.head(10)

image

Mean/Target Encoding

这里是将标签的平均值作为编码(注意,这种方法会将标签信息泄露)

df['country_target'] = df['country'].map(df.groupby(['country'])['target'].mean())
df.head(10)

image

标签:编码,LabelEncoder,map,特征,country,df,编码方式,数据
来源: https://www.cnblogs.com/xiaoyunbowen/p/15480556.html