one-hot encoding 的解释
1. What is categorical data?
这里说什么,什么是分类的数据。简单来说,其实要input的数据,一般要训练的模型有很多个instances,每个instance可能有很多个features。对于每个features可能有很多个属性值。下面就是几个例子:
l A “pet” variable with the values: “dog” and “cat“.
l A “color” variable with the values: “red“, “green” and “blue“.
l A “place” variable with the values: “first”, “second” and “third“.
2. What is the problem with categorical data?
分类数据有多种形式,比如数字,文字或者图片。
有些算法可以直接处理这些数据,但是有些算法只能处理数字。
因此就需要把文字或者图片的像素转化成数字,进行使用。
同时对于输出结果是数字的,还需要将输出结果的数字和对应的类进行对应,才能输出正常的结果。
这也是为什么需要对categorical data进行处理的原因
3. How to convert data to numerical?
一般想把input的数据处理成数字的时候,有两种方法:integer encoding / one-hot encoding
3.1 Integer encoding
该方法其实就是将分类的数据和某一个int进行对应。
比如:我们假设 “red” is 1, “green” is 2, and “blue” is 3。当然这是在训练的时候自行进行定义的。
如果输入的input全部都是文字,那么在使用只能计算和训练数字的算法时,都需要基于这些对于关系。
可以很清楚的看到,这些数字的连续的,这种编码方式会构成一种顺序的关系。
当这种关系不适合的时候,就需要one-hot encoding
3.2 One-hot encoding
one-hot 编码方式也是需要将每个data(文字)和数字进行对应,但是这里选择只用0/1来表示。
比如,该列colour一共有3个属性值:red/green/blue。
那么我们就设定,每个属性值都用一个长度为3的向量(数组)来表示。如果属性值有4个,那么就向量(数组)长度就是4.
比如,定义red=[1,0,0].
A “1” value is placed in the binary variable for the color and “0” values for the other colors.
Red
|
Green
|
Blue
|
1
|
0
|
0
|
0
|
1
|
0
|
0
|
0
|
1
|