One-Hot 编码

独热编码即 One-Hot 编码,又称一位有效编码,其方法是使用N位状态寄存器来对N个状态进行编码,每个状态都由他独立的寄存器位,并且在任意时候,其中只有一位有效。独热编码恰好是一种解决上述问题的好办法。不过数据也因此变得稀疏。
[{‘city’: ‘北京’,‘location’:‘北方’,‘temperature’:100},
{‘city’: ‘上海’,‘location’:‘南方’,‘temperature’:60},
{‘city’: ‘深圳’,‘location’:‘南方’,‘temperature’:30},
{‘city’: ‘深圳’,‘location’:‘南方’,‘temperature’:20}]
上述中对于city类别进行数字化,我们可以使用123分表来表示北京、上海、深圳;在特征量非常少的情况下,使用这种简单数字化的方式表示一个类别是可以,但是在面对大量特征的时候,我们就会发现无法继续使用这个方式来唯一的表示一个类别。而one-hot编码刚好契合的这个问题,对于city特征,在这里我们发现它一共有3个类别,那么我们是否可以使用3个状态位来分别表示呢,对于location使用2个状态位来表示呢?
对于特征city:
北京:100
上海:010
深圳:001

对于特征location:
北方01
南方10

对于特征temperature:
本身是数字,不使用one-hot编码

对于样本1编码为:100 01 100

from sklearn.feature_extraction import DictVectorizer
import numpy as np

def dictvec():
    '''
    字典数据抽取
    return None
    '''
    # 实例化
    # dict = DictVectorizer() # sparse默认为True
    dict = DictVectorizer(sparse=False)  # data输出为ndarray数组

    # 调用fit_transform
    data = dict.fit_transform([{'city': '北京','location':'北方','temperature':100},
{'city': '上海','location':'南方','temperature':60},
{'city': '深圳','location':'南方','temperature':30},
{'city': '深圳','location':'南方','temperature':20}])
    print(dict.get_feature_names())
    # 字典数据抽取:把字典中一些类别的数据,分别进行转换成特征
    print(data)

    return None

if __name__ == '__main__':
    dictvec()

得到的输出结果如下,为ndarray数组。
[‘city=上海’, ‘city=北京’, ‘city=深圳’, ‘location=北方’, ‘location=南方’, ‘temperature’]
[[ 0. 1. 0. 1. 0. 100.]
[ 1. 0. 0. 0. 1. 60.]
[ 0. 0. 1. 0. 1. 30.]
[ 0. 0. 1. 0. 1. 20.]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值