引言
最近我一直在用分类器处理定性数据。虽然我用的 XGBoost 自带编码功能,但我注意到,定性数据的编码方式其实有好几种,各有优缺点。这篇文章收录了我的一些笔记,以及可以直接复制粘贴的代码片段,其中大部分由 GPT 生成。
环境准备
先来准备环境,这里假设已经安装好了 Python。
首先安装必要的库:
pip install numpy pandas scikit-learn category_encoders
接下来准备所需的数据,并定义要编码的列:
import pandas as pd
data = {'Color': ['Red', 'Blue', 'Blue', 'Blue', 'Blue'],
'Size': ['S', 'S', 'M', 'M', 'M'],
'Mixed': ['A', 0, 1.0, True, np.nan]}
df = pd.DataFrame(data)
# Filling nulls with a placeholder and converting all to strings
df.fillna('Null', inplace=True)
df = df.astype(str)
# Defining four identical lists for each encoding method
columns_for_one_hot = ['Color', 'Size', 'Letter']
columns_for_label = ['Color', 'Size', 'Letter']
columns_for_binary = ['Color', 'Size', 'Letter']
columns_for_frequency = ['Color', 'Size', 'Letter']
现在,DataFrame df 应该长这样:
Color Size Mixed
0 Red S A
1 Blue S 0
2 Blue M 1.0
3 Blue M True
4 Blue M Null
准备就绪!
独热编码(One-Hot Encoding)
思路:为每个不同的类别取值新建一列,用 1 和 0 表示该值是否出现。
代码:
import pandas as pd
def apply_one_hot_encoding(df, columns):
return pd.get_dummies(df, columns=columns)
df_one_hot = apply_one_hot_encoding(df, columns_for_one_hot)
原始数据:
Color Size Mixed
0 Red S A
1 Blue S 0
2 Blue M 1.0
3 Blue M True
4 Blue M Null
独热编码后:
Color_Blue Color_Red Size_M Size_S Mixed_0 Mixed_1.0 Mixed_A Mixed_Null Mixed_True
0 0 1 0 1 0 0 1 0 0
1 1 0 0 1 1 0 0 0 0
2 1 0 1 0 0 1 0 0 0
3 1 0 1 0 0 0 0 0 1
4 1 0 1 0 0 0 0 1 0
优点:
- 不隐含顺序:这种方法不会暗示类别之间存在任何顺序或优先级。
- 直观:对人来说很好理解——每一列对应一个取值。
- 应用广泛:兼容多种类型的模型,是许多应用场景中的标准做法。
缺点:
- 新增维度多:可能大幅增加数据集的维度,导致计算变慢。
- 稀疏矩阵:产生的大多是稀疏矩阵,不利于某些类型的计算。
这种方法最适合只有少数几个不同取值的列。当类别变量本身没有内在顺序,或者所用的模型不能直接处理类别变量(比如线性回归模型)时,它的效果最好。它也很适合深度学习 / 神经网络,因为这类模型相对更擅长处理高维数据。
标签编码(Label Encoding)
思路:给每个类别取值分配一个唯一的整数。
代码:
from sklearn.preprocessing import LabelEncoder
def apply_label_encoding(df, columns):
df_encoded = df.copy()
le = LabelEncoder()
for col in columns:
df_encoded[col] = le.fit_transform(df_encoded[col])
return df_encoded
df_label = apply_label_encoding(df, columns_for_label)
原始数据:
Color Size Mixed
0 Red S A
1 Blue S 0
2 Blue M 1.0
3 Blue M True
4 Blue M Null
标签编码后:
Color Size Mixed
0 1 1 2
1 0 1 0
2 0 0 1
3 0 0 4
4 0 0 3
优点:
- 不新增维度:节省空间,无论有多少类别,都只需要一列。
- 直观:对人来说很好理解——每个数字代表一个唯一的取值。
缺点:
- 隐含顺序:可能会错误地暗示类别之间存在大小顺序(例如 Red > Blue)。
这种方法最适合具有内在顺序的类别变量,比如“低”“中”“高”。它也适用于基于树的算法,例如决策树、随机森林和梯度提升树,因为这类算法在分裂决策时能够处理“顺序”这一概念。不过,如果把它用在没有内在顺序的特征上,隐含的顺序可能会影响线性回归等对顺序敏感的模型。
二进制编码(Binary Encoding)
思路:与独热编码类似,但会在标签编码之后把所有值转换成二进制,并为每一个二进制位新建一列。
代码:
import category_encoders as ce
def apply_binary_encoding(df, columns):
be = ce.BinaryEncoder(cols=columns)
return be.fit_transform(df)
df_binary = apply_binary_encoding(df, columns_for_binary)
原始数据:
Color Size Mixed
0 Red S A
1 Blue S 0
2 Blue M 1.0
3 Blue M True
4 Blue M Null
二进制编码后:
Color_0 Color_1 Size_0 Size_1 Mixed_0 Mixed_1 Mixed_2
0 0 1 0 1 0 0 1
1 1 0 0 1 0 1 0
2 1 0 1 0 0 1 1
3 1 0 1 0 1 0 0
4 1 0 1 0 1 0 1
优点:
- 新增维度较少:减少了新增列的数量,是独热编码与标签编码之间不错的折中。
- 保留信息:与单纯的标签编码相比,能保留更多信息,而且不隐含顺序。
缺点:
- 不直观:很难直观地理解每一列的含义。
这种方法最适合没有顺序、取值种类又比较多的类别数据。本质上,可以把它看作可解释性与维度数量之间的取舍:更难理解,但需要操心的列更少。
频率编码(Frequency Encoding)
思路:用类别出现的频率替换类别本身。
代码:
def apply_frequency_encoding(df, columns):
df_freq = df.copy()
for col in columns:
freq = df[col].value_counts().to_dict()
df_freq[col] = df[col].map(freq)
return df_freq
df_freq = apply_frequency_encoding(df, columns_for_frequency)
原始数据:
Color Size Mixed
0 Red S A
1 Blue S 0
2 Blue M 1.0
3 Blue M True
4 Blue M Null
频率编码后:
Color Size Letter
0 1 2 1
1 4 2 1
2 4 3 1
3 4 3 1
4 4 3 1
优点:
- 不新增维度:只需要一列,和标签编码一样。
- 捕捉频率信息:编码后的大小顺序可能是有意义的,因为它包含了每个类别的频率信息。
缺点:
- 缺乏区分度:截然不同的类别最终可能有相同的频率。
- 过拟合风险:如果频率与目标变量直接相关,可能会导致过拟合。
这种方法最适合取值的出现频率本身很重要的类别变量。当不同取值的数量很多,且各取值的频率分布不均匀时,它尤其有用。
完整代码
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
import category_encoders as ce
# Setting up the data
data = {'Color': ['Red', 'Blue', 'Blue', 'Blue', 'Blue'],
'Size': ['S', 'S', 'M', 'M', 'M'],
'Mixed': ['A', 0, 1.0, True, np.nan]}
df = pd.DataFrame(data)
# Filling nulls with a placeholder and converting all to strings
df.fillna('Null', inplace=True)
df = df.astype(str)
# Defining four identical lists for each encoding method
columns_for_one_hot = ['Color', 'Size', 'Mixed']
columns_for_label = ['Color', 'Size', 'Mixed']
columns_for_binary = ['Color', 'Size', 'Mixed']
columns_for_frequency = ['Color', 'Size', 'Mixed']
# One-Hot Encoding Function
def apply_one_hot_encoding(df, columns):
return pd.get_dummies(df, columns=columns)
# Label Encoding Function
def apply_label_encoding(df, columns):
df_encoded = df.copy()
le = LabelEncoder()
for col in columns:
df_encoded[col] = le.fit_transform(df_encoded[col])
return df_encoded
# Binary Encoding Function
def apply_binary_encoding(df, columns):
be = ce.BinaryEncoder(cols=columns)
return be.fit_transform(df)
# Frequency Encoding Function
def apply_frequency_encoding(df, columns):
df_freq = df.copy()
for col in columns:
freq = df[col].value_counts().to_dict()
df_freq[col] = df[col].map(freq)
return df_freq
# Applying the encoding methods
df_one_hot = apply_one_hot_encoding(df, columns_for_one_hot)
df_label = apply_label_encoding(df, columns_for_label)
df_binary = apply_binary_encoding(df, columns_for_binary)
df_freq = apply_frequency_encoding(df, columns_for_frequency)
# Printing the results
print("One-Hot Encoded Data:\n", df_one_hot)
print("\nLabel Encoded Data:\n", df_label)
print("\nBinary Encoded Data:\n", df_binary)
print("\nFrequency Encoded Data:\n", df_freq)
附赠:不同维度适用的算法
特征数量多(1,000 - 100,000+)
- 深度学习 / 神经网络:擅长处理高维数据,尤其是在图像识别、语音识别等领域。
- 降维技术:PCA、UMAP 等技术常用于降低数据的维度,同时保留大部分信息。
- 正则化线性模型:LASSO 或岭回归等模型通过加入正则化项来抑制过拟合,从而能够处理高维数据。
特征数量中等(100 - 10,000)
- 梯度提升机(如 XGBoost、LightGBM、CatBoost):这类算法能很好地处理中等数量的特征,也擅长捕捉数据中的复杂模式。
- 随机森林:这种集成方法在特征数量中等时很有效,而且不容易过拟合。
- 支持向量机:只要核函数选择得当,SVM 在中等规模的特征空间中可以很有效,尤其是在数据线性不可分的情况下。
特征数量少(< 1000)
- 逻辑回归与线性回归:对于简单的低维数据集,这些模型可以非常有效,而且易于实现和解释。
- 决策树:在特征数量较少时效果不错,可解释,还能对非线性关系建模。
- 朴素贝叶斯:这种算法特别适合小型数据集,即使数据量有限也能有不错的表现。
混合维度
- 集成方法:把不同的模型(比如一个随机森林、几个神经网络,再加上梯度提升机)组合起来,可以在维度混杂的数据集上取得不错的效果。
- 特征工程:如果什么方法都不奏效,可以试着把数据集变换到更高维或更低维的空间,从而转化成前面的某一种情况。