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
|