numpy array To One-hot

import numpy as np
num_classes = 5
targets = np.array([[2, 3, 4, 0]]).reshape(-1)
one_hot_targets = np.eye(num_classes)[targets]


The one_hot_targets is now:

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

The .reshape(-1) is there to make sure you have the right labels format 
(you might also have [[2], [3], [4], [0]]).
 The -1 is a special value which means "put all remaining stuff in this dimension". 
As there is only one, it flattens the array.
         

參考:https://stackoverflow.com/questions/38592324/one-hot-encoding-using-numpy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章