one-hot的基本思想:将离散型特征的每一种取值都看成一种状态,若你的这一特征中有N个不相同的取值,那么我们就可以将该特征抽象成N种不同的状态,one-hot编码保证了每一个取值只会使得一种状态处于“激活态”,也就是说这N种状态中只有一个状态位值为1,其他状态位都是0。
举个例子,假设我们以浏览器为例,我们想要研究的类别为
浏览器:[“Firefox”,”Chrome”,”Safari”,”Internet Explorer”]
共有4个类别,我们使用one-hot对其编码就会得到:
Firefox: [1, 0, 0, 0]
Chorme: [0, 1, 0, 0]
Safari: [0, 0, 1, 0]
IE: [0, 0, 0, 1]
如果出现多个特征
比如:
性别:[“male”,”female”]
那么对于实例(Firefox, female)编码即为[1, 0, 0, 0, 0, 1],即将两个类别的One-Hot编码组装在一起了。
当然这样的缺点就是编码向量太稀疏了。
Python实现:
Python
browser = ["Firefox", "Chrome", "Safari", "Internet Explorer"]
gender = ["male", "female"]
def onehotEncoding(instance1, instance2, class1, class2):
temp1, temp2 = [0] * len(class1), [0] * len(class2)
temp1[class1.index(instance1)] = 1
temp2[class2.index(instance2)] = 1
return temp1 + temp2
for i in browser:
for j in gender:
print(onehotEncoding(i, j, browser, gender))
1
2
3
4
5
6
7
8
9
10
11
12
13
browser=["Firefox","Chrome","Safari","Internet Explorer"]
gender=["male","female"]
defonehotEncoding(instance1,instance2,class1,class2):
temp1,temp2=[0]*len(class1),[0]*len(class2)
temp1[class1.index(instance1)]=1
temp2[class2.index(instance2)]=1
returntemp1+temp2
foriinbrowser:
forjingender:
print(onehotEncoding(i,j,browser,gender))
结果: