2017-07-20 47 views
2

爲什麼Keras to_categorical在[1,-1]和[2,-2]上表現不同?Keras np_utils.to_categorical行爲不同

y = [1, -1, -1] 
y_ = np_utils.to_categorical(y) 
array([[ 0., 1.], 
     [ 0., 1.], 
     [ 0., 1.]]) 


y = [2, -2, -2] 
y_ = np_utils.to_categorical(y) 
array([[ 0., 0., 1.], 
     [ 0., 1., 0.], 
     [ 0., 1., 0.]]) 
+0

它爲什麼會表現相同的方式? –

+0

我想to_categorical應該將y數據集轉換爲one-hot-vector數據集。 [1]和[-1]應具有不同的編碼值。就像[2] ==> [0,0,1]和[-2] ===> [0,1,0]。 –

回答

3

to_categorical不取負值,如果你有一個具有負值的數據集,你可以通過y - y.min()to_categorical因此它可以如你所願:以上

>>> y = numpy.array([2, -2, -2]) 
>>> to_categorical(y) 
array([[ 0., 0., 1.], 
     [ 0., 1., 0.], 
     [ 0., 1., 0.]]) 
>>> to_categorical(y - y.min()) 
array([[ 0., 0., 0., 0., 1.], 
     [ 1., 0., 0., 0., 0.], 
     [ 1., 0., 0., 0., 0.]]) 
+0

謝謝,現在我明白了 –

1
y = np.array(y, dtype='int').ravel() 
if not num_classes: 
    num_classes = np.max(y) + 1 
n = y.shape[0] 
categorical = np.zeros((n, num_classes)) 
categorical[np.arange(n), y] = 1 

是執行to_categorical。

因此,在[1,-1,-1]的情況下發生了什麼是:
num_classes = 2 [np.max()+ 1]
分類形狀變得[3,2]
所以當-1它讀取最後一個索引並將其設置爲1.並且對於1還讀取索引1(索引從0開始)。
這就是爲什麼最終輸出在[2,-2,-2]的情況下發生了什麼是變得

array([[ 0., 1.], 
     [ 0., 1.], 
     [ 0., 1.]]) 


num_classes = 3 [np.max()+ 1]
分類形狀變得[3,3]
所以當-2到來時,它讀取第二個最後一個索引並使其爲1,對於2它讀取索引2(索引從0開始)。
這就是爲什麼最後的輸出成爲

array([[ 0., 0., 1.], 
     [ 0., 1., 0.], 
     [ 0., 1., 0.]]) 

所以如果你嘗試類似[2,-4,-4],它會給你一個錯誤,因爲沒有指數-4作爲分類形狀[3 ,3]。