python one hot编码_One-Hot编码详解与Python实现

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))

结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值