数值映射和独热编码
在机器学习和深度学习中,当输入特征为类别型 Categorical 数据时,为了实现特征扩充使得这些特征可以参与网络的线性求和及后续的激活,可以根据类别特征是否具有量值属性而将其按照如下两种方式进行处理:
如果类别特征具有量值属性,且可以在后续计算中应该以不同大小的数值形式参与计算,如尺寸,型号等,那么可以直接以映射的形式分配数值编码
如果类别特征没有量值属性,可以将分类设置成相应数量的多个特征,并将输入的值在对应特征分类下设置为 1,如此不仅有效的处理了类别特征,还可以使这些特征有效的参与计算,这种方法称为独热编码 One-hot encoding
one-hot is a group of bits among which the legal combinations of values are only those with a single high (1) bit and all the others low (0).[1] A similar implementation in which all bits are '1' except one '0' is sometimes called one-cold. - Wiki

上述两种方式都可以方便的通过 Pandas 进行:
import pandas as pd
df = pd.DataFrame([
['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']],
columns=['color', 'size', 'prize', 'class_label'])
df
Out[2]:
color size prize class_label
0 green M 10.1 class1
1 red L 13.5 class2
2 blue XL 15.3 class1
对尺寸这个具有量值意义的特征进行量值映射,在此等级这个属性也不具有量值意义,但由于只有两个分类,因此在此演示采用映射的形式进行,需要注意的是也可以通过后续对于颜色的处理方式进行:
In [3]:
# mapping the size
size_mapping = {'XL': 3, 'L': 2, 'M': 1}
df['size'] = df['size'].map(size_mapping)
# mapping the class
class_mapping = {label: index for index, label in enumerate(set(df['class_label']))}
df['class_label'] = df['class_label'].map(class_mapping)
df
Out[3]:
color size prize class_label
0 green 1 10.1 1
1 red 2 13.5 0
2 blue 3 15.3 1
对颜色这列没有量值意义的分类使用 pd.get_dummies( ) 进行独热编码,并在编码后去掉原数据中的 color 列:
In [8]:
one_hot_encoded = pd.concat([df, pd.get_dummies(df['color'], prefix='color')], axis=1)
one_hot_encoded
Out[8]:
color size prize class_label color_blue color_green color_red
0 green 1 10.1 1 0 1 0
1 red 2 13.5 0 0 0 1
2 blue 3 15.3 1 1 0 0
In [10]:
one_hot_encoded.drop('color', axis=1)
Out[10]:
size prize class_label color_blue color_green color_red
0 1 10.1 1 0 1 0
1 2 13.5 0 0 0 1
2 3 15.3 1 1 0 0
在 Keras 中利用 np_utils.to_categorical( ) 进行 One-hot key encoding 的实现过程如下:
In [1]
from keras.utils import np_utils
# print first ten (integer-valued) training labels
print('Integer-valued labels:')
print(y_train[:10])
# one-hot encode the labels
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# print first ten (one-hot) training labels
print('One-hot labels:')
print(y_train[:10])
Out[1]
Integer-valued labels:
[5 0 4 1 9 2 1 3 1 4]
One-hot labels:
[[ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]