region val region_id
0 Europe 940 2
1 North America 605 3
2 Africa 423 0
3 Europe 398 2
4 South America 504 4
5 South America 538 4
6 Asia 337 1
7 Africa 474 0
8 Asia 662 1
9 Europe 834 2
Africa < Asia < Europe < North America < South America
这与实际样品无关。
如果我们找到样本的平均值:
In [51]: df['region_id'].mean()
Out[51]: 1.9
1.9- 不携带任何语义负荷。那些。基于数据的这种表示,算法可能会做出错误的结论和假设。
使用One Hot Encoding消除了这些缺点。
region val Africa Asia Europe North America South America
0 Europe 940 0 0 1 0 0
1 North America 605 0 0 0 1 0
2 Africa 423 1 0 0 0 0
3 Europe 398 0 0 1 0 0
4 South America 504 0 0 0 0 1
5 South America 538 0 0 0 0 1
6 Asia 337 0 1 0 0 0
7 Africa 474 1 0 0 0 0
8 Asia 662 0 1 0 0 0
9 Europe 834 0 0 1 0 0
现在如果我们计算平均值,我们得到:
In [63]: df.drop(['region','val'],1).mean()
Out[63]:
Africa 0.2
Asia 0.2
Europe 0.3
North America 0.1
South America 0.2
dtype: float64
在这种情况下,这正确地描述了我们样本的频率特性,这将使我们能够做出更正确的进一步结论和假设。
@Mike 在评论中已经指出了另一个优点——如果一个对象可以同时包含多个属性,那么它One Hot Encoding会考虑到这个特性,而类别的编号在这里也无济于事。
示例 Python 代码:
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
l = ['Asia', 'Africa', 'Europe', 'North America', 'South America']
le = LabelEncoder()
np.random.seed(3)
reg = np.random.choice(l, size=10, p=[0.2, 0.15, 0.3, 0.2, 0.15])
df = pd.DataFrame({'region':reg, 'val':np.random.randint(1000, size=10)})
df['region_id'] = le.fit_transform(df['region'])
print(df)
print(df['region_id'].mean())
del df['region_id']
df = df.join(pd.get_dummies(df['region']))
print(df)
print(df.drop(['region','val'],1).mean())
想象一个分类属性,例如,一些标题/名称。
如果将其编码为整数序列,那么许多算法(对于神经网络尤其如此)会根据编码特征的数值特征(基于特征的数值表示的数据排名)做出错误的估计和结论:
那些。对于上面的例子:
这与实际样品无关。
如果我们找到样本的平均值:
1.9
- 不携带任何语义负荷。那些。基于数据的这种表示,算法可能会做出错误的结论和假设。使用
One Hot Encoding
消除了这些缺点。现在如果我们计算平均值,我们得到:
在这种情况下,这正确地描述了我们样本的频率特性,这将使我们能够做出更正确的进一步结论和假设。
@Mike 在评论中已经指出了另一个优点——如果一个对象可以同时包含多个属性,那么它
One Hot Encoding
会考虑到这个特性,而类别的编号在这里也无济于事。示例 Python 代码: