独热编码即 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.]]