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