当前位置: 首页 > news >正文

《sklearn机器学习——数据预处理》类别特征编码

sklearn 数据预处理中的类别特征编码

在机器学习中,许多算法无法直接处理字符串形式的类别特征(如“男”、“女”、“红色”、“蓝色”等),需要将其转换为数值形式。sklearn.preprocessing 模块提供了多种类别特征编码方法,以下是常用编码器的详细介绍。


1. LabelEncoder(标签编码)

核心思想

将每个类别映射为一个整数(0 到 n_classes-1)。适用于目标变量(y)或有序类别变量。

常用函数与类

  • LabelEncoder()

主要方法

  • .fit(y):拟合标签编码器
  • .transform(y):转换标签为数值
  • .fit_transform(y):拟合并转换
  • .inverse_transform(y):逆转换,还原为原始标签

参数

无特殊参数,自动推断类别。

返回值

一维数组(ndarray),元素为整数编码。

示例代码

from sklearn.preprocessing import LabelEncoder# 示例数据
colors = ['red', 'blue', 'green', 'blue', 'red']# 创建编码器
le = LabelEncoder()# 拟合并转换
encoded = le.fit_transform(colors)
print("编码结果:", encoded)  # [2 0 1 0 2]# 逆转换
original = le.inverse_transform(encoded)
print("还原结果:", original)  # ['red' 'blue' 'green' 'blue' 'red']# 查看类别映射
print("类别顺序:", le.classes_)  # ['blue' 'green' 'red']

⚠️ 注意:LabelEncoder 不适用于无序分类特征作为模型输入,因为整数隐含顺序关系(如 0 < 1 < 2),可能导致模型误解。

2. OrdinalEncoder(序数编码)

核心思想

LabelEncoder 类似,但支持多列输入。适用于多个有序分类特征。

常用函数与类

OrdinalEncoder()

主要参数

categories: ‘auto’ 或 list of array-like,默认 ‘auto’,自动推断类别。
dtype: 输出数据类型,默认 np.float64。
handle_unknown: ‘error’ 或 ‘use_encoded_value’,处理未知类别。
unknown_value: 与 handle_unknown=‘use_encoded_value’ 配合使用。

返回值

二维数组(ndarray),形状为 (n_samples, n_features)。

示例代码

from sklearn.preprocessing import OrdinalEncoder
import numpy as np# 示例数据(两列类别特征)
data = np.array([['男', '北京'],['女', '上海'],['男', '广州'],['女', '北京']])# 创建编码器
oe = OrdinalEncoder()# 拟合并转换
encoded = oe.fit_transform(data)
print("编码结果:\n", encoded)
# [[0. 0.]
#  [1. 2.]
#  [0. 1.]
#  [1. 0.]]# 查看每列的类别
print("各列类别:", oe.categories_)
# [array(['男', '女'], dtype='<U1'), array(['北京', '广州', '上海'], dtype='<U2')]

3. OneHotEncoder(独热编码)

核心思想

将每个类别转换为一个二进制向量(只有一位为1,其余为0),消除类别间的“大小”关系,适合无序分类变量。

常用函数与类

OneHotEncoder()

主要参数

categories: ‘auto’ 或 list,默认 ‘auto’
drop: {‘first’, ‘if_binary’} 或 array,用于删除某一列以避免多重共线性
sparse_output: 是否返回稀疏矩阵,默认 True(⚠️ sklearn 1.2+ 已弃用 sparse,改用 sparse_output)
handle_unknown: {‘error’, ‘ignore’, ‘infrequent_if_exist’},处理未知类别
dtype: 输出数据类型

返回值

默认返回稀疏矩阵(csr_matrix),设置 sparse_output=False 可返回稠密数组。

示例代码

from sklearn.preprocessing import OneHotEncoder
import numpy as np# 示例数据
data = np.array([['男'], ['女'], ['男'], ['女']])# 创建编码器
ohe = OneHotEncoder(sparse_output=False)  # 返回稠密数组# 拟合并转换
encoded = ohe.fit_transform(data)
print("独热编码结果:\n", encoded)
# [[1. 0.]
#  [0. 1.]
#  [1. 0.]
#  [0. 1.]]# 获取特征名称
feature_names = ohe.get_feature_names_out(['性别'])
print("特征名:", feature_names)  # ['性别_男' '性别_女']# 逆转换
original = ohe.inverse_transform(encoded)
print("还原结果:\n", original)
# [['男']
#  ['女']
#  ['男']
#  ['女']]

4. 使用 pandas.get_dummies 的替代方案(非 sklearn,但常用)

虽然不属于 sklearn,但在实践中常与 sklearn 配合使用:

import pandas as pddf = pd.DataFrame({'颜色': ['红', '蓝', '绿', '蓝']})
dummies = pd.get_dummies(df['颜色'], prefix='颜色')
print(dummies)
#    颜色_红  颜色_蓝  颜色_绿
# 0     1     0     0
# 1     0     1     0
# 2     0     0     1
# 3     0     1     0

5. 编码器选择建议

场景推荐编码器
目标变量(分类标签)LabelEncoder
有序分类特征(如:低/中/高)OrdinalEncoder
无序分类特征(如:颜色、城市)OneHotEncoder
高基数类别(如邮政编码)考虑 TargetEncoder (来自 category_encoders 库)或嵌入

6. 完整实战示例

from sklearn.preprocessing import LabelEncoder, OrdinalEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
import pandas as pd
import numpy as np# 创建示例数据框
df = pd.DataFrame({'城市': ['北京', '上海', '广州', '北京'],'性别': ['男', '女', '男', '女'],'收入等级': ['低', '中', '高', '中']
})print("原始数据:")
print(df)# 方法1:使用 ColumnTransformer 组合不同编码器
ct = ColumnTransformer(transformers=[('onehot', OneHotEncoder(drop='first', sparse_output=False), ['城市', '性别']),('ordinal', OrdinalEncoder(categories=[['低', '中', '高']]), ['收入等级'])],remainder='passthrough'
)encoded_array = ct.fit_transform(df)
feature_names = (ct.named_transformers_['onehot'].get_feature_names_out(['城市', '性别']).tolist() +['收入等级']
)encoded_df = pd.DataFrame(encoded_array, columns=feature_names)
print("\n组合编码后:")
print(encoded_df)# 方法2:分别编码
ohe = OneHotEncoder(sparse_output=False)
city_gender_encoded = ohe.fit_transform(df[['城市', '性别']])
print("\n城市+性别独热编码:")
print(city_gender_encoded)oe = OrdinalEncoder(categories=[['低', '中', '高']])
income_encoded = oe.fit_transform(df[['收入等级']])
print("\n收入等级序数编码:")
print(income_encoded)

7. 注意事项

  • 训练/测试一致性:必须使用 .fit_transform() 在训练集上拟合,然后对测试集使用 .transform(),避免数据泄露。
  • 未知类别处理:使用 handle_unknown='ignore''infrequent_if_exist' 避免预测时报错。
  • 稀疏性:当类别数量大时,使用稀疏矩阵节省内存。
  • 多重共线性:独热编码后建议删除一列(如 drop='first'),尤其在线性模型中。

✅ 掌握以上编码方法,可灵活应对各类分类特征预处理需求,为后续建模打下坚实基础。


文章转载自:

http://P68z3Uqb.ypqwm.cn
http://ResnXthh.ypqwm.cn
http://aNKDOfli.ypqwm.cn
http://CliNdkaf.ypqwm.cn
http://ijUin3hw.ypqwm.cn
http://q3RNHqLz.ypqwm.cn
http://ohHmLAxJ.ypqwm.cn
http://FN7GFZ92.ypqwm.cn
http://lCdiut1q.ypqwm.cn
http://PHrC8cCO.ypqwm.cn
http://QYrYz0wW.ypqwm.cn
http://FRtGDe7J.ypqwm.cn
http://M0E7KAnY.ypqwm.cn
http://ssl7EyOv.ypqwm.cn
http://zruYjjVF.ypqwm.cn
http://PGvwidNY.ypqwm.cn
http://ef1uTkUJ.ypqwm.cn
http://1cWufDmV.ypqwm.cn
http://xrOSY6lp.ypqwm.cn
http://UWtJpxha.ypqwm.cn
http://Cs5VQqw5.ypqwm.cn
http://Aq6qAU5A.ypqwm.cn
http://fxAbiAzn.ypqwm.cn
http://UQ7GGals.ypqwm.cn
http://zOYzktb9.ypqwm.cn
http://CIiYqvmE.ypqwm.cn
http://iEJkQ6rk.ypqwm.cn
http://vpaHV1gE.ypqwm.cn
http://5Zn7xjPF.ypqwm.cn
http://lz2K6PVq.ypqwm.cn
http://www.dtcms.com/a/377536.html

相关文章:

  • #C语言——刷题攻略:牛客编程入门训练(十一):攻克 循环控制(三),轻松拿捏!
  • 深入剖析 Chrome PartitionAlloc 内存池源码原理与性能调优实践
  • Shell 脚本编程:函数
  • C++ STL 容器的一个重要成员函数——`emplace_back`
  • vue3:触发自动el-input输入框焦点
  • python range函数练习题
  • Q2(门座式)起重机司机的理论知识考试考哪些内容?
  • 企业微信消息推送
  • 顺序表:数据结构中的基础线性存储结构
  • 什么是X11转发?
  • OpenCV计算机视觉实战(24)——目标追踪算法
  • 4.2 I2C通信协议
  • Spring Boot 读取 YAML 配置文件
  • 【系统分析师】第20章-关键技术:微服务系统分析与设计(核心总结)
  • SAP-MM:SAP MM模块精髓:仓储地点(Storage Location)完全指南图文详解
  • Shell脚本周考习题及答案
  • 广东省省考备考(第九十六天9.10)——言语(刷题巩固第二节课)
  • Pthread定时锁与读写锁详解
  • Go模块自动导入教学文档
  • 技术文章大纲:开学季干货——知识梳理与经验分享
  • TensorFlow平台介绍
  • Vue3 中实现按钮级权限控制的最佳实践:从指令到组件的完整方案
  • 生成模型与概率分布基础
  • Cookie之domain
  • JavaSSM框架-MyBatis 框架(五)
  • 中州养老:设备管理介绍
  • 【Day 51|52 】Linux-tomcat
  • MySQL - 如果没有事务还要锁吗?
  • “高德点评”上线,阿里再战本地生活
  • JUC的常见类、多线程环境使用集合类