考慮多類情況。非onehot,標籤是類似0 1 2 3...n這樣。
而onehot標籤則是顧名思義,一個長度爲n的數組,只有一個元素是1.0,其他元素是0.0。
例如在n爲4的情況下,標籤2對應的onehot標籤就是 0.0 0.0 1.0 0.0
keras.utils.to_categorical這個方法,源碼中,它是這樣寫的:
Converts a class vector (integers) to binary class matrix.
E.g. for use with categorical_crossentropy.
也就是說它是對於一個類型的容器(整型)的轉化爲二元類型矩陣。比如用來計算多類別交叉熵來使用的。
其參數也很簡單:
def to_categorical(y, num_classes=None):
Arguments
y: class vector to be converted into a matrix
(integers from 0 to num_classes).
num_classes: total number of classes.
說的很明白了,y就是待轉換容器(其類型爲從0到類型數目),而num_classes則是類型的總數。
簡單來說,to_categorical就是將類別向量轉換爲二進制(只有0和1)的矩陣類型表示。其表現爲將原有的類別向量轉換爲獨熱編碼的形式。先上代碼看一下效果:
from keras.utils.np_utils import *
#類別向量定義
b = [0,1,2,3,4,5,6,7,8]
#調用to_categorical將b按照9個類別來進行轉換
b = to_categorical(b, 9)
print(b)
執行結果如下:
[[1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1.]]
使用onehot的直接原因是現在多分類cnn網絡的輸出通常是softmax層,而它的輸出是一個概率分佈,從而要求輸入的標籤也以概率分佈的形式出現,進而算交叉熵之類。