实现独热编码的方法

本文介绍了三种实现One-Hot编码的方法:使用Scikit-Learn的LabelBinarizer和OneHotEncoder,以及使用NumPy手动实现。这些方法适用于将分类变量转化为机器学习算法所需的数值型数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一、用 Scikit-Learn 实现 One-Hot Encoding

 

scikit-learn 的 LabelBinarizer 函数(二值化)可以很方便地把你的目标(labels)转化成独热编码向量。请看:

import numpy as np
from sklearn import preprocessing

# Example labels 示例 labels
labels = np.array([1,5,3,2,1,4,2,1,3])

# Create the encoder 创建编码器
lb = preprocessing.LabelBinarizer()

# Here the encoder finds the classes and assigns one-hot vectors 
# 编码器找到类别并分配 one-hot 向量
lb.fit(labels)

# And finally, transform the labels into one-hot encoded vectors
# 最后把目标(lables)转换成独热编码的(one-hot encoded)向量
lb.transform(labels)
array([[1, 0, 0, 0, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0]])

方法二、使用Sklearn.Preprocessing 的 OneHotEncoder

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder()
encoder.fit(np.arange(6).reshape(-1, 1))
def one_hot_encode(x):
    return encoder.transform(np.array(x).reshape(-1, 1)).toarray()
labels = [1,5,3,2,1,4,2,1,3]
a= one_hot_encode(labels)
print(a)
[[0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0.]]

注意这里存在一个问题:当原标签不是从0开始;

方法三、使用numpy实现one-hot:

import numpy as np

_y = [1,4,3,2,6,5]
_y = np.asarray(_y,dtype=int)
b = np.zeros((_y.size, _y.max()+1))
b[np.arange(_y.size),_y] = 1
print(b)

[[0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0. 1. 0.]]



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值