机器学习 数据预处理之独热编码

5 篇文章 0 订阅
4 篇文章 0 订阅

1、什么是独热编码

让由0和1组成的占位符取表示每列特征,让不同样本之间相同特征之间的两两距离(两两差异)相同
例:

                       特征1  特征2  特征3
	 	数据集	       1      3       2
	                   7       5       4
	                   1       8       6
	                   7       1       9
	      用独热编码表示:      
	          1:10       3:0001    2:0001
	          7:01       1:0010    4:0010
	                        5:0100    6:0100
	                        8:1000    9:1000
	     独热编码转换后:
	         10        0001        0001
	         01        0100        0010    
	         10        1000        0100
	         01        0001        1000

2、 作用

优点:独热编码解决了分类器不好处理属性数据的问题,在一定程度上也起到了扩充特征的作用。它的值只有0和1,不同的类型存储在垂直的空间。

缺点:当类别的数量很多时,特征空间会变得非常大,成为一个高维稀疏矩阵。在这种情况下,一般可以用PCA来减少维度。而且one hot encoding(独热编码)+PCA这种组合在实际中也非常有用。

3、原理示例代码

import numpy as np
import sklearn.preprocessing as sp
raw_samples = np.array([
    [1, 3, 2],
    [7, 5, 4],
    [1, 8, 6],
    [7, 1, 9],
])

# 找出每一列(特征)有多少种不同的取值
code_tables = []
for col in raw_samples.T:
    code_table = {}   #空字典
    for val in col:
        code_table[val] = None   #通过空字典去重   因为相同键会覆盖
    code_tables.append(code_table)
print(code_tables)

for code_table in code_tables:
    size = len(code_table)
    for one,key in enumerate(sorted(code_table.keys())):   #enumerate会生成给一个列表 返回索引和值
        code_table[key] = np.zeros(shape=size,dtype=int)   #生成一个size大小(同列特征不同值个数)的0矩阵
        code_table[key][one] = 1   #把相应位置的0改为1
print(code_tables)   #列类似于这样的列表[{1: array([1, 0]), 7: array([0, 1])}, {3: array([0, 1, 0, 0]), 5: array([0, 0, 1, 0]), 8: array([0, 0, 0, 1])]

ohe_samples = []
for raw_sample in raw_samples:
    ohe_sample = np.array([],dtype=int) #创建一个举矩阵
    for i, key in enumerate(raw_sample):   #返回一个列表  返回索引值和值
        ohe_sample = np.hstack((ohe_sample,code_tables[i][key]))   #code_tables[i][key]获取第i列特征(这个列表中第i个字典)中键为数据中的键的对应的矩阵  对每列特征都会生成一个列表   然后水平拼接
    ohe_samples.append(ohe_sample)  #独热编码转换后的列表
ohe_samples = np.array(ohe_samples)  #转换为矩阵
print(ohe_samples)

4、调用库包代码

import numpy as np
import sklearn.preprocessing as sp

raw_samples = np.array([
    [1, 3, 2],
    [7, 5, 4],
    [1, 8, 6],
    [7, 1, 9],
])

ohe = sp.OneHotEncoder(sparse=False, dtype=int) #非压缩格式   一般都False 独热编码器
new_sample = ohe.fit_transform(raw_samples)
print(new_sample)
samp = np.array([[7,5,4]])
ohe_samp = ohe.transform(samp) #根据上面生成的独热编码器预测
print(ohe_samp)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值