When I was working on my machine learning project, I was looking for a line of code to turn my labels into one-hot vectors. I came across this nifty line of code from u/benanne on Reddit.
np.eye(n_labels)[target_vector]
For example, for a target_vector = np.array([1, 4, 2, 1, 0, 1, 3, 2])
, it returns the one-hot coded values:
np.eye(5)[target_vector]
Out:
array([[ 0., 1., 0., 0., 0.],
[ 0., 0., 0., 0., 1.],
[ 0., 0., 1., 0., 0.],
...,
[ 0., 1., 0., 0., 0.],
[ 0., 0., 0., 1., 0.],
[ 0., 0., 1., 0., 0.]])
While it definitely does work, I'm not sure how or why it works.